branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "libtess2",
products: [
.library(name: "libtess2",type: .static,targets: ["libtess2"])
],
targets: [
.target(name: "libtess2",dependencies: [],path:"Sources/libtess2")
]
)
| 7405b82d025b80afc85b453e3c9ce24cd7c019e8 | [
"Swift"
] | 1 | Swift | aestesis/libtess2 | 9f25198b9f9aecf62abb57a50f071f7e9df61794 | df3af67d45bb24aa5404aee01d3ee95fd997e279 | |
refs/heads/master | <file_sep>/*
* 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 trivia;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.Scanner;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
/**
* FXML Controller class
*
* @author Arthur
*/
public class BasicQuestionTemplateController implements Initializable {
@FXML
private Label questions;
@FXML
private Label a;
@FXML
private Label b;
@FXML
private Label c;
@FXML
private Label d;
/**
* @author Alec
*/
public void scan(Scanner s, ArrayList<String> a){
while(s.hasNext()){
String q = s.next();
a.add(q);
}
}
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
/**
* @author Alec
*/
File q = new File("Trivia Questions.txt");
File correct = new File("Correct Answers.txt");
File w1 = new File("Wrong Answers 1.txt");
File w2 = new File("Wrong Answers 2.txt");
File w3 = new File("Wrong Answers 3.txt");
try{
Scanner myScan = new Scanner(q);
ArrayList<String> ques = new ArrayList<String>();
scan(myScan, ques);
Scanner cor = new Scanner(correct);
ArrayList<String> correctAnswers = new ArrayList<String>();
scan(cor, correctAnswers);
Scanner first = new Scanner(w1);
ArrayList<String> wrong1 = new ArrayList<String>();
scan(first, wrong1);
Scanner sec = new Scanner(w2);
ArrayList<String> wrong2 = new ArrayList<String>();
scan(sec, wrong2);
Scanner third = new Scanner(w3);
ArrayList<String> wrong3 = new ArrayList<String>();
scan(third, wrong3);
Random rand = new Random();
int i = rand.nextInt(ques.size());
String newQ = ques.get(i);
String newC = correctAnswers.get(i);
String newA1 = wrong1.get(i);
String newA2 = wrong2.get(i);
String newA3 = wrong3.get(i);
Label questions = new Label(newQ);
Label labelC = new Label(newC);
Label firstL = new Label(newA1);
Label secL = new Label(newA2);
Label thirdL = new Label(newA3);
int n = rand.nextInt(3);
if(n == 0){
a = labelC;
b = firstL;
c = secL;
d = thirdL;
}
else if(n == 1){
b = labelC;
c = firstL;
d = secL;
a = thirdL;
}
else if(n == 2){
c = labelC;
d = firstL;
a = secL;
b = thirdL;
}
else if(n == 3){
d = labelC;
a = firstL;
b = secL;
c = thirdL;
}
}
catch (FileNotFoundException caught){
System.out.println("The file does not exist");
}
}
}
| b2d0cc7bbf1e46137a29f48eef803371e6b0c7ec | [
"Java"
] | 1 | Java | Akappy/Trivia | 9bacb33503d4f413c5ba1b1390b466f4d994be60 | 7f8e837380d662c5c9a3e176696f6e45d9b4f6f5 | |
refs/heads/master | <file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* putwstr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dengstra <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/23 13:33:14 by dengstra #+# #+# */
/* Updated: 2017/06/03 18:32:55 by dengstra ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
char *ft_putwchar(wchar_t c, t_id *id)
{
char *result;
if (c <= 127 || (id->specifier == 'c' && id->e_length == none))
result = one_byte(c);
else if (c <= 2047)
result = two_byte(c);
else if (c <= 65535)
result = three_byte(c);
else
result = four_byte(c);
return (result);
}
size_t ft_putwstr(wchar_t *str, t_id *id)
{
size_t len;
char *result;
char *tmp;
len = 0;
if (!str)
return (ft_putwstr(L"(null)", id));
while (str[len++])
;
result = ft_strnew(len * 4);
if (!result)
exit(-1);
while (*str)
{
tmp = ft_putwchar(*str++, id);
ft_strcat(result, tmp);
free(tmp);
}
len = ft_printstr(result, id);
free(result);
return (len);
}
int ft_putbinary(size_t num)
{
int len;
len = 0;
if (!num)
return (0);
len += ft_putbinary(num >> 8);
if (num >> 8)
len += write(1, " ", 1);
len += ft_printf("%c%c%c%c%c%c%c%c",
(num & 0b10000000) ? '1' : '0',
(num & 0b01000000) ? '1' : '0',
(num & 0b00100000) ? '1' : '0',
(num & 0b00010000) ? '1' : '0',
(num & 0b00001000) ? '1' : '0',
(num & 0b00000100) ? '1' : '0',
(num & 0b00000010) ? '1' : '0',
(num & 0b00000001) ? '1' : '0');
return (len);
}
int ft_putzerochar(t_id *id)
{
size_t width;
width = 0;
if (id->width)
width = id->width - 1;
if (id->minus)
{
ft_putchar(0);
while (width--)
ft_putchar(id->zero);
}
else
{
while (width--)
ft_putchar(id->zero);
ft_putchar(0);
}
return ((id->width) ? id->width : 1);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* btree_delone.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: douglas <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/07/09 00:57:48 by douglas #+# #+# */
/* Updated: 2017/07/09 02:06:57 by douglas ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static t_btree *find_leftmost_node(t_btree *root)
{
while (root->left)
root = root->left;
return (root);
}
t_btree *btree_delone(t_btree *root, void *item, int (*cmp)(void *, void *),
void (*free_node)(void *))
{
t_btree *tmp;
if (!root)
return (NULL);
if (cmp(root->item, item) > 0)
root->right = btree_delone(root->right, item, cmp, free_node);
else if (cmp(root->item, item) < 0)
root->left = btree_delone(root->left, item, cmp, free_node);
else
{
if (root->left == NULL)
{
tmp = root->right;
free_node(root);
return (tmp);
}
else if (root->right == NULL)
{
tmp = root->left;
free_node(root);
return (tmp);
}
tmp = find_leftmost_node(root->right);
root->item = tmp->item;
root->right = btree_delone(root, item, cmp, free_node);
}
return (root);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* printnbr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dengstra <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/24 11:48:35 by douglas #+# #+# */
/* Updated: 2017/06/07 12:11:20 by dengstra ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static char *precision(char *nbr, t_id *id)
{
size_t p_len;
size_t nbr_len;
char *result;
if (!nbr)
exit(-1);
if (id->precision == 0 && *nbr == '0')
return (ft_strnew(0));
p_len = id->precision;
nbr_len = ft_strlen(nbr);
if (p_len > nbr_len)
{
if (!(result = ft_strnew(p_len)))
exit(-1);
ft_memset(result, '0', p_len);
ft_memmove(result + p_len - nbr_len, nbr, nbr_len);
}
else
result = ft_strdup(nbr);
return (result);
}
static char *get_sign(int minus, t_id *id)
{
char specifier;
specifier = id->specifier;
if (specifier == 'x' || specifier == 'p')
return ("0x");
else if (specifier == 'X')
return ("0X");
else if (specifier == 'o' || specifier == 'O')
return ("0");
else if (minus)
return ("-");
else if (id->plus == '+')
return ("+");
else
return ("");
}
static int sign_adder(t_id *id, int minus, char *nbr, int len)
{
char *joined;
if ((!ft_only_char(nbr, '0') || *nbr != '0'
|| id->plus || id->specifier == 'p' || minus)
&& (!ft_strchr("oOxX", id->specifier)
|| (id->hash &&
(*nbr || ft_strchr("oO", id->specifier)))))
{
if ((id->plus || id->hash || minus) && id->zero == '0')
{
len += ft_putstr(get_sign(minus, id));
len += ft_putstrfree(padding(nbr, id, len));
}
else
{
joined = ft_strjoin(get_sign(minus, id), nbr);
len += ft_putstrfree(padding(joined, id, len));
free(joined);
}
}
else
len += ft_putstrfree(padding(nbr, id, len));
return (len);
}
int ft_print_nbr(char *nbr, t_id *id)
{
int len;
int minus;
char *prec;
if (!nbr)
exit(-1);
if ((minus = (*nbr == '-') ? 1 : 0))
nbr++;
prec = NULL;
if (id->has_precision)
{
if (!(prec = precision(nbr, id)))
exit(-1);
nbr = prec;
id->zero = ' ';
}
len = 0;
if (id->space && ft_strchr("di", id->specifier) && !minus && !id->plus)
len = write(1, " ", 1);
len = sign_adder(id, minus, nbr, len);
free(prec);
return (len);
}
int ft_base(size_t n, char c, t_id *id)
{
char *base;
char *tmp;
int len;
if (c == 'x' || c == 'p')
base = BASE_16;
else if (c == 'X')
base = BASE_16_U;
else
base = BASE_8;
tmp = ft_itoa_base(n, base);
len = ft_print_nbr(tmp, id);
if (tmp)
free(tmp);
return (len);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* padding.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dengstra <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/06 18:45:13 by dengstra #+# #+# */
/* Updated: 2017/06/03 18:34:45 by dengstra ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
char *padding(char *str, t_id *id, size_t sign_len)
{
size_t width;
size_t str_len;
void *result;
str_len = ft_strlen(str) + sign_len;
if (id->specifier == 's' && id->has_precision)
str_len = (id->precision < str_len) ? id->precision : str_len;
width = (id->width > str_len) ? id->width : str_len;
result = ft_strnew(width);
if (!result)
exit(-1);
ft_memset(result, id->zero, width);
if (!id->minus)
ft_memmove(result + width - str_len, str, ft_strlen(str) + 1);
else
ft_memmove(result, str, str_len);
return (result);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dengstra <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/23 13:20:35 by dengstra #+# #+# */
/* Updated: 2017/06/08 17:35:40 by dengstra ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FT_PRINTF_H
# define FT_PRINTF_H
# include <unistd.h>
# include <stdarg.h>
# include <stdlib.h>
# include "../libft.h"
# define BASE_16_U "0123456789ABCDEF"
# define BASE_16 "0123456789abcdef"
# define BASE_10 "0123456789"
# define BASE_8 "01234567"
typedef struct s_id
{
char hash;
char zero;
char plus;
char minus;
char space;
size_t width;
size_t precision;
int has_precision;
char specifier;
struct s_id *next;
enum {
none,
h,
hh,
l,
ll,
j,
z
} e_length;
} t_id;
t_id *ft_get_flags(char *format);
int ft_printf(const char *format, ...);
int ft_printer(char *format, t_id *id, va_list ap);
int ft_base(size_t n, char c, t_id *id);
char ft_is_specifier(char c);
int ft_print_nbr(char *nbr, t_id *id);
int ft_printstr(char *str, t_id *id);
size_t ft_putwstr(wchar_t *str, t_id *id);
char *ft_putwchar(wchar_t c, t_id *id);
int ft_putbinary(size_t c);
size_t length_converter(va_list ap, int len);
size_t ulength_converter(va_list ap, int len);
char *padding(char *str, t_id *id, size_t sign_len);
int ft_putzerochar(t_id *id);
void input_checker(t_id *id);
char *one_byte(int c);
char *two_byte(int c);
char *three_byte(int c);
char *four_byte(int c);
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_flags.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dengstra <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/05 22:27:28 by douglas #+# #+# */
/* Updated: 2017/06/03 18:34:11 by dengstra ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static char *get_length(char *format, t_id **id)
{
if (*format == 'l' && *(format + 1) == 'l')
{
(*id)->e_length = ll;
return (format + 2);
}
if (*format == 'h' && *(format + 1) == 'h')
{
(*id)->e_length = hh;
return (format + 2);
}
(*format == 'l') ? (*id)->e_length = l : 0;
(*format == 'h') ? (*id)->e_length = h : 0;
(*format == 'j') ? (*id)->e_length = j : 0;
(*format == 'z') ? (*id)->e_length = z : 0;
if ((*id)->e_length)
return (++format);
return (format);
}
static char *get_flags(t_id **id, char *format)
{
while (ft_strchr("#0- +", *format))
{
if (*format == '#')
(*id)->hash = *format;
if (*format == '0' && !(*id)->minus)
(*id)->zero = *format;
if (*format == '-')
{
(*id)->minus = *format;
(*id)->zero = ' ';
}
if (*format == '+')
(*id)->plus = *format;
if (*format == ' ')
(*id)->space = ' ';
format++;
}
return (format);
}
static t_id *ft_id(char *format)
{
t_id *id;
if (!(id = (t_id*)ft_memalloc(sizeof(t_id))))
exit(-1);
id->zero = ' ';
id->specifier = 0;
format = get_flags(&id, format);
if (*format >= '1' && *format <= '9')
{
id->width = ft_atoi(format);
while (ft_isdigit(*format))
format++;
}
if (*format == '.')
{
id->precision = ft_atoi(++format);
id->has_precision = 1;
while (ft_isdigit(*format))
format++;
}
format = get_length(format, &id);
id->specifier = *format;
if (id->specifier == 'p')
id->hash = '#';
return (id);
}
static void add_to_lst(t_id **lst, t_id *id)
{
t_id *tmp;
if (*lst == NULL)
{
*lst = id;
return ;
}
tmp = *lst;
while (tmp->next)
tmp = tmp->next;
tmp->next = id;
}
t_id *ft_get_flags(char *format)
{
t_id *lst;
lst = NULL;
while (*format)
{
if (*format == '%')
add_to_lst(&lst, ft_id(++format));
format++;
}
return (lst);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dengstra <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/04/18 11:14:59 by dengstra #+# #+# */
/* Updated: 2017/04/18 11:19:58 by dengstra ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static unsigned int is_white(char c)
{
return (c == ' ' || c == '\n' || c == '\t');
}
char *ft_strtrim(char const *s)
{
unsigned int needs_trim;
unsigned int len;
char *trimmed;
if (!s)
return (NULL);
while (*s && is_white(*s))
s++;
if (!*s)
return (ft_strnew(0));
len = ft_strlen(s);
needs_trim = 0;
while (is_white(s[--len]))
needs_trim = 1;
if (needs_trim == 0)
return (ft_strdup(s));
trimmed = (char*)malloc(len + 2);
if (!trimmed)
return (NULL);
trimmed[++len] = '\0';
while (len--)
trimmed[len] = s[len];
return (trimmed);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* printer.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dengstra <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/05 22:27:44 by douglas #+# #+# */
/* Updated: 2017/06/03 18:27:51 by dengstra ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static int function_caller(char c, size_t num, t_id *id, va_list ap)
{
int len;
char *tmp;
len = 0;
tmp = NULL;
len += (ft_strchr("uU", c)) ?
ft_print_nbr((tmp = ft_itoa_base(num, BASE_10)), id) : 0;
len += (ft_strchr("idD", c)) ? ft_print_nbr((tmp = ft_itoa(num)), id) : 0;
len += (c == '%') ? ft_printstr("%", id) : 0;
len += (num && ft_strchr("cC", c)) ?
ft_printstr((tmp = ft_putwchar(num, id)), id) : 0;
len += (!num && ft_strchr("cC", c)) ? ft_putzerochar(id) : 0;
len += (c == 's' && id->e_length != l) ?
ft_printstr(va_arg(ap, char*), id) : 0;
len += (ft_strchr("xXoO", c)) ? ft_base(num, c, id) : 0;
len += (c == 'p') ? ft_base((long)va_arg(ap, void*), c, id) : 0;
len += (c == 'b') ? ft_putbinary(va_arg(ap, size_t)) : 0;
len += (c == 'S' || (c == 's' && id->e_length == l))
? ft_putwstr(va_arg(ap, wchar_t*), id) : 0;
if (tmp)
free(tmp);
return (len);
}
static size_t len_converter(char c, va_list ap, t_id *id)
{
if (ft_strchr("cdDi", c))
return (length_converter(ap, id->e_length));
else if (ft_strchr("xXoOuUC", c))
return (ulength_converter(ap, id->e_length));
return (0);
}
int ft_printer(char *format, t_id *id, va_list ap)
{
char c;
int len;
t_id *tmp;
len = 0;
if (!id)
return (ft_putstr(format));
while (*format)
{
if (*format != '%' && (len += ft_putchar(*format++)))
continue;
c = id->specifier;
(ft_strchr("DOU", c)) ? id->e_length = l : 0;
if (ft_is_specifier(c))
len += function_caller(c, len_converter(c, ap, id), id, ap);
(c == '%') ? format++ : 0;
while (*format && *format++ != c)
;
tmp = id;
id = id->next;
free(tmp);
}
free(id);
return (len);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dengstra <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/04/18 11:14:50 by dengstra #+# #+# */
/* Updated: 2017/04/18 12:35:05 by dengstra ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static unsigned int count_words(char const *s, char c)
{
unsigned int i;
unsigned int words;
if (!*s)
return (0);
i = 0;
words = 0;
while (s[i + 1])
{
if (s[i] != c && s[i + 1] == c)
words++;
i++;
}
if (s[i] != c)
words++;
return (words);
}
static const char *skip_c(char const *s, char c)
{
while (*s == c)
s++;
return (s);
}
static unsigned int word_len(char const *s, char c)
{
unsigned int len;
len = 0;
while (*s && *s != c)
{
len++;
s++;
}
return (len);
}
static char **spliter(const char *s, char c, char **split,
unsigned int words)
{
unsigned int i;
unsigned int len;
i = 0;
while (words--)
{
s = skip_c(s, c);
len = word_len(s, c);
split[i] = ft_strnew(len);
if (!split[i])
return (NULL);
ft_memmove(split[i], s, len);
split[i][len] = '\0';
s += len;
i++;
}
split[i] = NULL;
return (split);
}
char **ft_strsplit(char const *s, char c)
{
unsigned int words;
char **split;
if (!s)
return (NULL);
s = skip_c(s, c);
words = count_words(s, c);
split = (char**)malloc(sizeof(*split) * (words + 1));
if (!split)
return (NULL);
return (spliter(s, c, split, words));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* length_converter.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dengstra <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/24 11:35:29 by douglas #+# #+# */
/* Updated: 2017/06/03 18:29:00 by dengstra ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
size_t length_converter(va_list ap, int len)
{
if (len == h)
return (short)(va_arg(ap, int));
if (len == hh)
return (char)(va_arg(ap, int));
if (len == l)
return (va_arg(ap, long));
if (len == ll)
return (va_arg(ap, long long));
if (len == j)
return (va_arg(ap, uintmax_t));
if (len == z)
return (va_arg(ap, size_t));
return (va_arg(ap, int));
}
size_t ulength_converter(va_list ap, int len)
{
if (len == h)
return (unsigned short)(va_arg(ap, unsigned int));
if (len == hh)
return (unsigned char)(va_arg(ap, unsigned int));
if (len == l)
return (va_arg(ap, unsigned long));
if (len == ll)
return (va_arg(ap, unsigned long long));
if (len == j)
return (va_arg(ap, uintmax_t));
if (len == z)
return (va_arg(ap, size_t));
return (va_arg(ap, unsigned int));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dengstra <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/02 11:42:19 by dengstra #+# #+# */
/* Updated: 2017/06/02 14:11:07 by dengstra ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static int ft_enqueue(t_queue *q)
{
t_node *node;
if (!(node = (t_node*)malloc(sizeof(t_node))))
return (-1);
node->next = NULL;
if (!q->head)
{
q->tail = node;
q->head = node;
}
else
{
q->tail->next = node;
q->tail = node;
}
return (1);
}
static int read_and_enqueue(int fd, t_queue *q)
{
char *buffer;
int i;
int read_return;
int new_line;
new_line = 0;
read_return = 1;
while (!new_line && read_return > 0)
{
if (!(buffer = ft_strnew(BUFF_SIZE)))
return (-1);
read_return = read(fd, buffer, BUFF_SIZE);
i = 0;
while (read_return > 0 && buffer[i])
{
if (-1 == ft_enqueue(q))
return (-1);
q->tail->value = buffer[i++];
if (buffer[i] == '\n')
new_line = 1;
}
free(buffer);
}
return (read_return);
}
static char dequeue(t_queue *q)
{
t_node *tmp;
char c;
if (!q->head)
return ('\0');
c = q->head->value;
tmp = q->head;
q->head = q->head->next;
free(tmp);
return (c);
}
static int add_line_and_dequeue(t_queue *q, char **line)
{
int len;
int ii;
t_node *i_node;
len = 0;
i_node = q->head;
while (i_node && i_node->value != '\n')
{
i_node = i_node->next;
len++;
}
if (!(line[0] = ft_strnew(len)))
return (-1);
ii = 0;
while (len--)
line[0][ii++] = dequeue(q);
return (1);
}
int get_next_line(const int fd, char **line)
{
static t_queue *start_q;
t_queue *current_q;
int read_return;
current_q = start_q;
while (current_q && current_q->fd != fd)
current_q = current_q->next;
if (!current_q)
{
if (!(current_q = (t_queue*)ft_memalloc(sizeof(t_queue))))
return (-1);
current_q->fd = fd;
current_q->head = NULL;
current_q->next = start_q;
start_q = current_q;
}
if (0 > (read_return = read_and_enqueue(fd, current_q)))
return (-1);
if (-1 == add_line_and_dequeue(current_q, line))
return (-1);
if (!dequeue(current_q) && !line[0][0])
return (0);
return (1);
}
| 90df756031263f4b55e3aa10e701d7ec1bd64bbb | [
"C"
] | 11 | C | doueng/libft | 915b6e4af38077176de17440e90f82a1248ceda1 | 33703eaaa44536d44edfacebfc39ccc16c897353 | |
refs/heads/master | <file_sep>package com.example.exercise3
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.*
class MainActivity : AppCompatActivity() {
lateinit var spinnerAge: Spinner
lateinit var radioGroupGender: RadioGroup
lateinit var radioButtonMale: RadioButton
lateinit var radioButtonFemale: RadioButton
lateinit var checkBoxSmoker: CheckBox
lateinit var textViewPremium: TextView
lateinit var buttonCalculate: Button
lateinit var buttonReset: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
spinnerAge = findViewById(R.id.spinnerAge)
radioGroupGender = findViewById(R.id.radioGroupGender)
radioButtonMale = findViewById(R.id.radioButtonMale)
radioButtonFemale = findViewById(R.id.radioButtonFemale)
checkBoxSmoker = findViewById(R.id.checkBoxSmoker)
textViewPremium = findViewById(R.id.textViewPremium)
buttonCalculate = findViewById(R.id.buttonCalculate)
buttonReset = findViewById(R.id.buttonReset)
buttonCalculate.setOnClickListener{ calculate() }
buttonReset.setOnClickListener{ reset() }
}
private fun calculate(){
var mySpinner: String = spinnerAge.getSelectedItem().toString()
var totalInsurance: Int = 0
var premiumPrice: Int = 0
var genderFee: Int = 0
var smokerFee: Int = 0
if(mySpinner.equals("Less than 17")) {
premiumPrice = 60
genderFee = 0
smokerFee = 0
}
else if(mySpinner.equals("17 to 25")){
premiumPrice = 70
if(radioGroupGender.checkedRadioButtonId != -1){
if(radioButtonMale.isChecked){
genderFee = 50
} else if (radioButtonFemale.isChecked){
genderFee = 0
}
}
if(checkBoxSmoker.isChecked){
smokerFee = 100
} else {
smokerFee = 0
}
}
else if(mySpinner.equals("26 to 30")){
premiumPrice = 90
if(radioGroupGender.checkedRadioButtonId != -1){
if(radioButtonMale.isChecked){
genderFee = 100
} else if (radioButtonFemale.isChecked){
genderFee = 0
}
}
if(checkBoxSmoker.isChecked){
smokerFee = 150
} else {
smokerFee = 0
}
}
else if(mySpinner.equals("31 to 40")){
premiumPrice = 120
if(radioGroupGender.checkedRadioButtonId != -1){
if(radioButtonMale.isChecked){
genderFee = 150
} else if (radioButtonFemale.isChecked){
genderFee = 0
}
}
if(checkBoxSmoker.isChecked){
smokerFee = 200
} else {
smokerFee = 0
}
}
else if(mySpinner.equals("41 to 55")){
premiumPrice = 150
if(radioGroupGender.checkedRadioButtonId != -1){
if(radioButtonMale.isChecked){
genderFee = 200
} else if (radioButtonFemale.isChecked){
genderFee = 0
}
}
if(checkBoxSmoker.isChecked){
smokerFee = 250
} else {
smokerFee = 0
}
}
else if(mySpinner.equals("More than 55")){
premiumPrice = 150
if(radioGroupGender.checkedRadioButtonId != -1){
if(radioButtonMale.isChecked){
genderFee = 200
} else if (radioButtonFemale.isChecked){
genderFee = 0
}
}
if(checkBoxSmoker.isChecked){
smokerFee = 300
} else {
smokerFee = 0
}
}
totalInsurance = premiumPrice + genderFee + smokerFee
textViewPremium.text = textViewPremium.text.toString() + " " + totalInsurance.toString()
}
private fun reset(){
spinnerAge.setSelection(0)
radioGroupGender.clearCheck();
//radioButtonMale.setChecked(false)
//radioButtonFemale.setChecked(false)
checkBoxSmoker.setChecked(false)
textViewPremium.text = resources.getString(R.string.insurance_premium)
}
}
| ca057eb66d42627f61ed80783661771eebf49254 | [
"Kotlin"
] | 1 | Kotlin | khang0714/Exercise_3 | 9a008e0549988cadcbe25b4d3c21329138e852b2 | 00d6ce297871f5baa86c66588b9c96de1a75803c | |
refs/heads/master | <repo_name>vcCoderBlue/DCVisitPlanner<file_sep>/src/pages/pageitems/AddTodo.js
import React, { Component } from 'react';
class AddTodo extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(event) {
event.preventDefault();
this.props.onAdd(this.contentInput.value);
this.contentInput.value = '';
}
render() {
return (
<form onSubmit={this.onSubmit}>
<h4>Add a Todo</h4>
<input placeholder="Type a Todo" ref={contentInput => this.contentInput = contentInput} /> <br />
<button>Add</button>
<hr />
</form>
);
}
}
export default AddTodo;
<file_sep>/src/pages/pageitems/actions/linkAction.js
export function addLink(favorites) {
return {
type: "ADD_LINK",
payload: favorites
};
}
<file_sep>/src/pages/pageitems/Main1.js
import React from 'react';
export const Main1 = (props) => {
return (
<div>
<div onClick={() => props.addFavsfavorite(<li></li>)}>
<i class="fa fa-heart-o fa-2x"></i>
</div>
</div>
);
}
<file_sep>/src/pages/Shopping.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import '../App.css';
import Shopping1 from "./pageitems/Shopping1";
import Shopping2 from "./pageitems/Shopping2";
import Shopping3 from "./pageitems/Shopping3";
import Shopping4 from "./pageitems/Shopping4";
import Shopping5 from "./pageitems/Shopping5";
import Footer from "../components/Footer";
import Gmps from "./maps/Gmps";
function Font5() {
return (
<i class="fa fa-shopping-bag fa-3x"></i>
)
}
class Shopping extends Component {
render() {
return (
<div>
<Router>
<div className="pages">
<h2>Shopping</h2>
<div className="items">
<ul>
<li>1<Font5 /><Link to="/DCVisitPlanner/Shopping/Shopping1"> CityCenterDC</Link></li><br />
<li>2<Font5 /><Link to="/DCVisitPlanner/Shopping/Shopping2"> Fashion Centre at Penatagon City</Link></li><br />
<li>3<Font5 /><Link to="/DCVisitPlanner/Shopping/Shopping3"> Georgetown</Link></li><br />
<li>4<Font5 /><Link to="/DCVisitPlanner/Shopping/Shopping4"> Mazza Gallerie</Link></li><br />
<li>5<Font5 /><Link to="/DCVisitPlanner/Shopping/Shopping5"> Tysons Corner Center</Link></li><br />
</ul>
<Route path="/DCVisitPlanner/Shopping/Shopping1" component={Shopping1}/>
<Route path="/DCVisitPlanner/Shopping/Shopping2" component={Shopping2}/>
<Route path="/DCVisitPlanner/Shopping/Shopping3" component={Shopping3}/>
<Route path="/DCVisitPlanner/Shopping/Shopping4" component={Shopping4}/>
<Route path="/DCVisitPlanner/Shopping/Shopping5" component={Shopping5}/>
</div>
</div>
</Router>
<div className="map">
<Gmps /><br /><br /><br /><br/><br /><br /><br /><br/><br /><br /><br /><br/><br /><br /><br /><br/>
</div>
<Footer />
</div>
);
}
}
export default Shopping;
<file_sep>/src/pages/pageitems/TodoItem.js
import React, { Component } from 'react';
class TodoItem extends Component {
constructor(props) {
super(props);
this.state = {
isEdit: false
};
this.onDelete = this.onDelete.bind(this);
this.onEdit = this.onEdit.bind(this);
this.onEditSubmit = this.onEditSubmit.bind(this);
}
onDelete() {
const { onDelete, content } = this.props;
onDelete(content);
}
onEdit() {
this.setState({ isEdit: true });
}
onEditSubmit(event) {
event.preventDefault();
this.props.onEditSubmit(this.contentInput.value, this.props.content);
this.setState({ isEdit: false });
}
render() {
const { content } = this.props;
return (
<div>
{
this.state.isEdit
? (
<form onSubmit={this.onEditSubmit}>
<input placeholder="Todo" ref={contentInput => this.contentInput = contentInput} defaultValue={content} />
<br />
<button>Save</button>
</form>
)
: (
<div>
<p>{content}</p>
<button onClick={this.onEdit}>Edit</button>
{' | '}
<button onClick={this.onDelete}>Delete</button>
</div>
)
}
</div>
);
}
}
export default TodoItem;
<file_sep>/src/pages/Todo.js
import React, { Component } from 'react';
import '../App.css';
import Footer from '../components/Footer';
import AddTodo from './pageitems/AddTodo';
import TodoItem from './pageitems/TodoItem';
const todos = [{ content: 'remember to smile ;)'}
];
localStorage.setItem('todos', JSON.stringify(todos));
class Todo extends Component {
constructor(props) {
super(props);
this.state = {
todos: JSON.parse(localStorage.getItem('todos')),
};
this.onAdd = this.onAdd.bind(this);
this.onDelete = this.onDelete.bind(this);
this.onEditSubmit = this.onEditSubmit.bind(this);
}
componentWillMount () {
const todos = this.getTodos();
this.setState({ todos });
}
getTodos() {
return this.state.todos;
}
onAdd (content) {
const todos = this.getTodos();
todos.push({
content
});
this.setState({ todos });
localStorage.setItem('todos', JSON.stringify(todos));
}
onDelete(content, index) {
const todos = this.getTodos();
const filteredTodos = todos.filter(todo => {
return todo.content !== content;
});
this.setState({
todos: filteredTodos
});
localStorage.setItem('todos', JSON.stringify(todos));
}
onEditSubmit(content, originalContent) {
let todos = this.getTodos();
todos = todos.map(todo => {
if (todo.content === originalContent) {
todo.content = content;
}
return todo;
});
this.setState({ todos });
localStorage.setItem('todos', JSON.stringify(todos));
}
render() {
return (
<div>
<h2>Todos</h2>
<div className="todos">
<AddTodo
onAdd={this.onAdd}
/>
{
this.state.todos.map((todo, index) => {
return (
<TodoItem
key={todo.index}
{...todo}
onDelete={this.onDelete}
onEditSubmit={this.onEditSubmit}
/>
);
})
}
</div>
<br /><br /><br /><br /><br /><br /><br />
<Footer />
</div>
);
}
}
export default Todo;
<file_sep>/src/pages/Search.js
import React from "react";
import { NavLink } from 'react-router-dom';
import Footer from "../components/Footer";
const Font12 = () => {
return (
<i class="fa fa-folder-open fa-2x" aria-hidden="true"></i>
)
}
const Font13 = () => {
return (
<i class="fa fa-file-text-o" aria-hidden="true"></i>
)
}
const Font14 = () => {
return (
<i class="fa fa-file-text-o fa-2x" aria-hidden="true"></i>
)
}
const Font15 = () => {
return (
<i class="fa fa-folder-open fa-3x" aria-hidden="true"></i>
)
}
class Search extends React.Component {
onClick() {
window.scrollTo(0, 0)
}
render() {
return (
<div>
<h2>Sitemap</h2>
<div className="items">
<Font15 /> DC Visit Planner <br />
<NavLink to='/DCVisitPlanner/Museums'><Font12 /></NavLink> Monuments/Museums <br />
<NavLink to='/DCVisitPlanner/Museums/Museum1'><Font13 /></NavLink> Arlington National Cemetary <br />
<NavLink to='/DCVisitPlanner/Museums/Museum2'><Font13 /></NavLink> International Spy Museum <br />
<NavLink to='/DCVisitPlanner/Museums/Museum3'><Font13 /></NavLink> National Museum of African American History and Culture<br />
<NavLink to='/DCVisitPlanner/Museums/Museum4'><Font13 /></NavLink> National World War II Memorial <br />
<NavLink to='/DCVisitPlanner/Museums/Museum5'><Font13 /></NavLink> United States Holocaust Memorial Museum <br />
<NavLink to='/DCVisitPlanner/Dining'><Font12 /></NavLink> Dining <br />
<NavLink to='/DCVisitPlanner/Dining/Dining1'><Font13 /></NavLink> Beefsteak <br />
<NavLink to='/DCVisitPlanner/Dining/Dining2'><Font13 /></NavLink> Chix <br />
<NavLink to='/DCVisitPlanner/Dining/Dining3'><Font13 /></NavLink> District Taco <br />
<NavLink to='/DCVisitPlanner/Dining/Dining4'><Font13 /></NavLink> The Hamilton <br />
<NavLink to='/DCVisitPlanner/Dining/Dining5'><Font13 /></NavLink> Union Market <br />
<NavLink to='/DCVisitPlanner/Shopping'><Font12 /></NavLink> Shopping <br />
<NavLink to='/DCVisitPlanner/Shopping/Shopping1'><Font13 /></NavLink> CityCenterDC <br />
<NavLink to='/DCVisitPlanner/Shopping/Shopping2'><Font13 /></NavLink> Fashion Centre at Pentagon City <br />
<NavLink to='/DCVisitPlanner/Shopping/Shopping3'><Font13 /></NavLink> Georgetown <br />
<NavLink to='/DCVisitPlanner/Shopping/Shopping4'><Font13 /></NavLink> Mazza Gallerie <br />
<NavLink to='/DCVisitPlanner/Shopping/Shopping5'><Font13 /></NavLink> Tysons Corner Center <br />
<NavLink to='/DCVisitPlanner/Hotels'><Font12 /></NavLink> Hotels <br />
<NavLink to='/DCVisitPlanner/Hotels/Hotel1'><Font13 /></NavLink> Hotel Lombardy <br />
<NavLink to='/DCVisitPlanner/Hotels/Hotel2'><Font13 /></NavLink> Kimpton Hotel Rouge <br />
<NavLink to='/DCVisitPlanner/Hotels/Hotel3'><Font13 /></NavLink> Mandarin Oriental <br />
<NavLink to='/DCVisitPlanner/Hotels/Hotel4'><Font13 /></NavLink> The Watergate Hotel <br />
<NavLink to='/DCVisitPlanner/Hotels/Hotel5'><Font13 /></NavLink> Washington Plaza Hotel <br />
<NavLink to='/DCVisitPlanner/' exact ><Font14 /></NavLink> Home <br />
<NavLink to='/DCVisitPlanner/Transport'><Font12 /></NavLink> Transport <br />
<NavLink to='/DCVisitPlanner/Transport/Transport1'><Font13 /></NavLink> capital bikeshare <br />
<NavLink to='/DCVisitPlanner/Transport/Transport2'><Font13 /></NavLink> Metro <br />
<NavLink to='/DCVisitPlanner/Weather'><Font14 /></NavLink> Weather <br />
<NavLink to='/DCVisitPlanner/Todo'><Font14 /></NavLink> Todos <br />
<NavLink to='/DCVisitPlanner/Favorites'><Font14 /></NavLink> Favorites <br />
<div onClick={this.onClick}><Font14 /> Sitemap </div> <br />
</div>
<br /><br /><br /><br /><br /><br /><br />
<Footer />
</div>
);
}
};
export default Search;
<file_sep>/src/pages/maps/Gmpd.js
import React, { Component } from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
import API_KEYM from "./config_keys1";
const apiKey = API_KEYM;
const style = {
width: '100%',
height: '275px'
}
export class Gmpd extends Component {
state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {},
};
windowHasOpened =() =>
this.setState({
showingInfoWindow: true
});
windowHasClosed =() =>
this.setState({
showingInfoWindow: false
});
onMarkerClick = (props, marker, e) =>
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: !this.state.showingInfoWindow
});
onMapClicked = (props) => {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
})
}
};
render() {
return (
<Map
google={this.props.google}
style={style}
initialCenter={{
lat: 38.9145,
lng: -77.0218
}}
zoom={11}
onClick={this.onMapClicked}
>
<Marker onClick={this.onMarkerClick}
title={'Beefsteak: 22nd St'}
name={'Beefsteak: 22nd St'}
label={'1'}
position={{lat: 38.899920, lng: -77.049430}}
/>
<Marker onClick={this.onMarkerClick}
title={'Beefsteak: Wisc Ave'}
name={'Beefsteak: Wisc Ave'}
label={'1'}
position={{lat: 38.948805, lng: -77.079693}}
/>
<Marker onClick={this.onMarkerClick}
title={'Beefsteak: Conn Ave'}
name={'Beefsteak: <NAME>'}
label={'1'}
position={{lat: 38.910764, lng: -77.044427}}
/>
<Marker onClick={this.onMarkerClick}
title={'Chix: 14th St NW'}
name={'Chix: 14th St NW'}
label={'2'}
position={{lat: 38.904533, lng: -77.031574}}
/>
<Marker onClick={this.onMarkerClick}
title={'Chix: Half St SE'}
name={'Chix: Half St SE'}
label={'2'}
position={{lat: 38.876282, lng: -77.007260}}
/>
<Marker onClick={this.onMarkerClick}
title={'District Taco: Tenleytown'}
name={'District Taco: Tenleytown'}
label={'3'}
position={{lat: 38.949947, lng: -77.080864}}
/>
<Marker onClick={this.onMarkerClick}
title={'District Taco: Dupont'}
name={'District Taco: Dupont'}
label={'3'}
position={{lat: 38.906026, lng: -77.044483}}
/>
<Marker onClick={this.onMarkerClick}
title={'District Taco: Eastern Market'}
name={'District Taco: Eastern Market'}
label={'3'}
position={{lat: 38.885242, lng: -76.996720}}
/>
<Marker onClick={this.onMarkerClick}
title={'District Taco: Metro Center'}
name={'District Taco: Metro Center'}
label={'3'}
position={{lat: 38.897597, lng: -77.030156}}
/>
<Marker onClick={this.onMarkerClick}
title={'The Hamilton'}
name={'The Hamilton'}
label={'4'}
position={{lat: 38.897655, lng: -77.032274}}
/>
<Marker onClick={this.onMarkerClick}
title={'Union Market'}
name={'Union Market'}
label={'5'}
position={{lat: 38.9087, lng: -76.9980}}
/>
<InfoWindow
marker={this.state.activeMarker}
onOpen={this.windowHasOpened}
onClose={this.windowHasClosed}
visible={this.state.showingInfoWindow}>
<div>
<h1>{this.state.selectedPlace.name}</h1>
</div>
</InfoWindow>
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: apiKey
})(Gmpd)
<file_sep>/src/pages/Home.js
import React, { Component } from 'react';
import Footer from "../components/Footer";
class Home extends Component {
render() {
return (
<div>
<h2>
<NAME>. <br/>
Visit Planner
</h2>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam placerat dapibus purus ac ultricies. Donec placerat porttitor scelerisque. Suspendisse placerat tristique nibh eu luctus. Fusce ultrices, lacus eu hendrerit lobortis, felis nisi porttitor diam, id pulvinar mi mauris sed eros.
<br /><br /><br /><br />
<Footer />
</div>
);
}
}
export default Home;
<file_sep>/src/pages/Hotels.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import '../App.css';
import Hotel1 from "./pageitems/Hotel1";
import Hotel2 from "./pageitems/Hotel2";
import Hotel3 from "./pageitems/Hotel3";
import Hotel4 from "./pageitems/Hotel4";
import Hotel5 from "./pageitems/Hotel5";
import Footer from "../components/Footer";
import Gmph from "./maps/Gmph";
function Font3() {
return (
<i class="fa fa-bed fa-3x"></i>
)
}
class Hotels extends Component {
render() {
return (
<div>
<Router>
<div className="pages">
<h2>Hotels</h2>
<div className="items">
<ul>
<li>1<Font3 /><Link to="/DCVisitPlanner/Hotels/Hotel1"> Hotel Lombardy</Link></li><br />
<li>2<Font3 /><Link to="/DCVisitPlanner/Hotels/Hotel2"> Kimpton Hotel Rouge</Link></li><br />
<li>3<Font3 /><Link to="/DCVisitPlanner/Hotels/Hotel3"> Mandarin Oriental</Link></li><br />
<li>4<Font3 /><Link to="/DCVisitPlanner/Hotels/Hotel4"> The Watergate Hotel</Link></li><br />
<li>5<Font3 /><Link to="/DCVisitPlanner/Hotels/Hotel5"> Washington Plaza Hotel</Link></li><br />
</ul>
<Route path="/DCVisitPlanner/Hotels/Hotel1" component={Hotel1}/>
<Route path="/DCVisitPlanner/Hotels/Hotel2" component={Hotel2}/>
<Route path="/DCVisitPlanner/Hotels/Hotel3" component={Hotel3}/>
<Route path="/DCVisitPlanner/Hotels/Hotel4" component={Hotel4}/>
<Route path="/DCVisitPlanner/Hotels/Hotel5" component={Hotel5}/>
</div>
</div>
</Router>
<div className="map">
<Gmph /><br /><br /><br /><br/><br /><br /><br /><br/><br /><br /><br /><br/><br /><br /><br /><br/>
</div>
<Footer />
</div>
);
}
}
export default Hotels;
<file_sep>/src/pages/pageitems/Shopping4.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { Main1 } from './Main1';
import { addLink } from './actions/linkAction';
function Font5() {
return (
<i class="fa fa-shopping-bag fa-3x"></i>
)
}
class Shopping4 extends Component {
onClick() {
window.scrollTo(0, 0)
}
render() {
return (
<div>
<div id="content1">
<nav1>
<div className="favorite">
<div>
<Main1 addFavsfavorite={() => this.props.addLink(
<ul><li><Font5 /><Link to="/DCVisitPlanner/Shopping/Shopping4"> <NAME></Link></li></ul>)} />
</div>
</div>
</nav1>
<aside1>
<div className="pic">
<Font5 /> <br />
<a href= "https://www.mazzagallerie.com/" target="_blank" rel="noopener noreferrer">Website</a> <br/>
<a href= "https://www.google.com/maps" target="_blank" rel="noopener noreferrer">Directions</a> <br/>
</div>
</aside1>
<header1>
<h3><NAME></h3>
</header1>
<main1>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam placerat dapibus purus ac ultricies. Donec placerat porttitor scelerisque. Suspendisse placerat tristique nibh eu luctus. Fusce ultrices, lacus eu hendrerit lobortis, felis nisi porttitor diam, id pulvinar mi mauris sed eros. Sed nulla diam, placerat sed purus feugiat, dignissim suscipit tortor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent sit amet metus ut nunc gravida rutrum.<br /> <br />
<div className="top" onClick={this.onClick}>Top of Page</div>
</main1>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
link: state.link
};
};
const mapDispatchToProps = (dispatch) => {
return {
addLink: (favorites) => {
dispatch(addLink(favorites));
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Shopping4);
| 7365c3b5cbbea7ac9eb09ca44235609f89b76b5c | [
"JavaScript"
] | 11 | JavaScript | vcCoderBlue/DCVisitPlanner | 72078091a2975c2118958b02115a710e99eabae3 | 8aa8f82d9c4e75d635ec521b0bd55802a6cd043d | |
refs/heads/master | <file_sep>from flask import Flask
from flask import request
import pytesseract
from PIL import Image
import requests
from io import BytesIO
import sys
from github import Github
import os
mykey = {"my_key1":"key1_value"}
port = sys.argv[1]
app = Flask(__name__)
@app.route('/postjson', methods = ['GET'])
def getJsoHandler():
return {"values":"1234"}
@app.route('/github', methods = ['POST'])
def github():
content = request.get_json()
project = content["repository"]["name"]
action = content["action"]
title = content["issue"]["title"]
description = content["issue"]["body"]
number = content["issue"]["number"]
userfull = content["repository"]["full_name"]
tokenUser = userfull.split("/")
user = tokenUser[0]
if action == "opened":
token1 = description.split("](https://user-images.githubusercontent.com")#seach url image
textOCR = ""
if len(token1)>1:
datanameim = []
datatextim = []
n = len(token1)
i = 0
while i < n-1:
token2 = token1[i+1].split(')')
url = "https://user-images.githubusercontent.com"+token2[0]
nameImage = token1[i].split("![") #seach name image
datanameim.append(nameImage[1])
response = requests.get(url)
img = Image.open(BytesIO(response.content))
text = pytesseract.image_to_string(img, lang='Thai',config='preserve_interword_spaces')
datatextim.append(text)
i = i+1
n = len(datanameim)
i = 0
while i < n:
description=description+"\n<details>\n<summary>"+datanameim[i]+"</summary>\n\n```\n"+datatextim[i]+"\n```\n\n</details>\n"
i = i+1
g = Github(os.environ['TOKEN'])
repo = g.get_repo(user+"/"+project)
repo.get_issue(int(number)).edit(body=description)
return ""
@app.route('/postjson', methods = ['POST'])
def postJsonHandler():
content = request.get_json()
response = requests.get(content['url'])
img = Image.open(BytesIO(response.content))
text = pytesseract.image_to_string(img, lang='Thai',config='preserve_interword_spaces')
return text
app.run(debug=True,host='0.0.0.0',port=port)
<file_sep>flask
flask_restful
pytesseract
pillow
requests
PyGithub | 16bab3966de8879ef3334279cd93198045976224 | [
"Python",
"Text"
] | 2 | Python | liiiiiiiiife/tesseract-service | 57d60cd4f1a30235b266e4da4890d468f5c2600d | a0215580c01305d12e2a1dec86489b631e573e2c | |
refs/heads/master | <file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Exceptions;
final class InvalidBouquetSize extends \InvalidArgumentException
{
public static function fromCharacter(string $size): self
{
return new self("The bouquet size '$size'' is invalid");
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Factories;
use Faker\Factory;
use Solaing\FlowerBouquets\Aggregates\Bouquet;
use Solaing\FlowerBouquets\Entities\BouquetName;
use Solaing\FlowerBouquets\Entities\Flower;
use Solaing\FlowerBouquets\Entities\BouquetSize;
final class BouquetFactory
{
public static function build(string $name, string $size, array $flowers, int $totalOfFlowers): Bouquet
{
return new Bouquet(
new BouquetName(strtoupper($name)),
new BouquetSize($size),
$flowers,
$totalOfFlowers
);
}
/**
* @param Flower[] $flowers
* @param int $totalOfFlowers
* @return Bouquet
*/
public static function buildWithFlowers(array $flowers, int $totalOfFlowers): Bouquet
{
$faker = Factory::create();
return new Bouquet(
new BouquetName(strtoupper($faker->randomLetter)),
new BouquetSize($faker->randomElement(['S', 'L'])),
$flowers,
$totalOfFlowers
);
}
public static function buildWithNameAndSize(string $name, string $size): Bouquet
{
return new Bouquet(
new BouquetName($name),
new BouquetSize($size),
[],
0
);
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets;
use Solaing\FlowerBouquets\Input\GenerateFlowerBouquetContainer;
use Solaing\FlowerBouquets\Output\GenerateBouquetCollection;
use Symfony\Component\Console\Input\StreamableInputInterface;
use Symfony\Component\Console\Output\OutputInterface;
final class GenerateBouquets
{
private $output;
/**
* @var StreamableInputInterface
*/
private $input;
public function __construct(StreamableInputInterface $input, OutputInterface $output) {
$this->output = $output;
$this->input = $input;
}
public function exec(): void
{
$container = GenerateFlowerBouquetContainer::fromResource($this->input->getStream());
$bouquets = GenerateBouquetCollection::fromContainer($container);
$this->output->writeln("-------------------------");
$this->output->writeln("----- Flower Bouquets ---");
$this->output->writeln("-------------------------");
foreach ($bouquets as $bouquet) {
$this->output->writeln($bouquet->render());
}
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Unit\Output;
use PHPUnit\Framework\TestCase;
use Solaing\FlowerBouquets\Aggregates\FlowerBouquetContainer;
use Solaing\FlowerBouquets\Output\GenerateBouquetCollection;
use Solaing\FlowerBouquets\Tests\Factories\BouquetDesignFactory;
use Solaing\FlowerBouquets\Tests\Factories\FlowerFactory;
final class BouquetCollectionHasBeenGeneratedProperlyTest extends TestCase
{
public final function test_bouquet_collection_is_empty_when_the_container_does_not_have_bouquet_designs() {
$container = new FlowerBouquetContainer();
$collection = GenerateBouquetCollection::fromContainer($container);
$this->assertEmpty($collection);
}
public final function test_bouquet_has_the_same_design_name_and_size() {
$bouquetDesign = BouquetDesignFactory::make();
$container = new FlowerBouquetContainer;
$container->addBouquetDesign($bouquetDesign);
$collection = GenerateBouquetCollection::fromContainer($container);
$bouquet = $collection[0];
$this->assertEquals($bouquetDesign->name(), $bouquet->name());
$this->assertEquals($bouquetDesign->bouquetSize(), $bouquet->flowerSize());
}
public final function test_bouquet_is_created_with_bouquet_design_and_exactly_same_flowers() {
$flower1 = FlowerFactory::make("a", "S", 10);
$flower2 = FlowerFactory::make("b", "S", 15);
$flower3 = FlowerFactory::make("c", "S", 10);
$flowers = [ $flower1, $flower2, $flower3 ];
$bouquetDesign = BouquetDesignFactory::make($flowers, 35);
$container = new FlowerBouquetContainer;
$container->addFlower($flower1);
$container->addFlower($flower2);
$container->addFlower($flower3);
$container->addBouquetDesign($bouquetDesign);
$collection = GenerateBouquetCollection::fromContainer($container);
$bouquet = $collection[0];
$this->assertEquals($flowers, $bouquet->flowers());
$this->assertEquals(0, $bouquet->totalFlowersLeft());
}
public final function test_bouquet_collection_is_created_with_bouquet_design_and_exactly_same_flowers() {
$flower1 = FlowerFactory::make("a", "S", 10);
$flower2 = FlowerFactory::make("b", "S", 15);
$flower3 = FlowerFactory::make("c", "S", 10);
$flowers = [ $flower1, $flower2, $flower3 ];
$bouquetDesign = BouquetDesignFactory::make($flowers, 35);
$container = new FlowerBouquetContainer;
$container->addFlower($flower1);
$container->addFlower($flower2);
$container->addFlower($flower3);
$container->addBouquetDesign($bouquetDesign);
$collection = GenerateBouquetCollection::fromContainer($container);
$bouquet = $collection[0];
$this->assertEquals($flowers, $bouquet->flowers());
$this->assertEquals(0, $bouquet->totalFlowersLeft());
}
public final function test_bouquet_collection_is_refilled_with_flowers_not_included_in_the_design() {
$flower1 = FlowerFactory::make("a", "S", 10);
$flower2 = FlowerFactory::make("b", "S", 15);
$flower3 = FlowerFactory::make("c", "S", 5);
$flower4 = FlowerFactory::make("z", "S", 5);
$flowers = [ $flower1, $flower2, $flower3 ];
$bouquetDesign = BouquetDesignFactory::make($flowers, 35);
$container = (new FlowerBouquetContainer);
$container->addFlower($flower1);
$container->addFlower($flower2);
$container->addFlower($flower3);
$container->addFlower($flower4);
$container->addBouquetDesign($bouquetDesign);
$collection = GenerateBouquetCollection::fromContainer($container);
$bouquet = $collection[0];
$this->assertEquals([ $flower1, $flower2, $flower3, $flower4 ], $bouquet->flowers());
$this->assertEquals(0, $bouquet->totalFlowersLeft());
}
public final function test_bouquet_is_refilled_but_still_some_flowers_left() {
$flower1 = FlowerFactory::make("a", "S", 10);
$flower2 = FlowerFactory::make("b", "S", 15);
$flower3 = FlowerFactory::make("c", "S", 5);
$flower4 = FlowerFactory::make("z", "S", 2);
$flowers = [ $flower1, $flower2, $flower3 ];
$bouquetDesign = BouquetDesignFactory::make($flowers, 35);
$container = (new FlowerBouquetContainer);
$container->addFlower($flower1);
$container->addFlower($flower2);
$container->addFlower($flower3);
$container->addFlower($flower4);
$container->addBouquetDesign($bouquetDesign);
$collection = GenerateBouquetCollection::fromContainer($container);
$bouquet = $collection[0];
$this->assertEquals(3, $bouquet->totalFlowersLeft());
}
public final function test_bouquet_is_refilled_with_any_flower_from_design() {
$flower1 = FlowerFactory::make("a", "S", 10);
$flower2 = FlowerFactory::make("b", "S", 15);
$flower3 = FlowerFactory::make("c", "S", 5);
$flower4 = FlowerFactory::make("z", "S", 2);
$flowers = [ $flower1, $flower2 ];
$bouquetDesign = BouquetDesignFactory::make($flowers, 35);
$container = (new FlowerBouquetContainer);
$container->addFlower($flower3);
$container->addFlower($flower4);
$container->addBouquetDesign($bouquetDesign);
$collection = GenerateBouquetCollection::fromContainer($container);
$bouquet = $collection[0];
$this->assertEquals([ $flower3, $flower4 ], $bouquet->flowers());
$this->assertEquals(28, $bouquet->totalFlowersLeft());
}
public final function test_bouquet_collection_from_multiple_bouquet_designs() {
$flower1 = FlowerFactory::make("a", "S", 10);
$flower2 = FlowerFactory::make("b", "S", 15);
$flower3 = FlowerFactory::make("c", "S", 5);
$flower4 = FlowerFactory::make("z", "S", 2);
$flower5 = FlowerFactory::make("i", "S", 8);
$bouquetDesign1 = BouquetDesignFactory::make([ $flower1, $flower3 ], 15);
$bouquetDesign2 = BouquetDesignFactory::make([ $flower2, $flower4 ], 25);
$container = (new FlowerBouquetContainer);
$container->addFlower($flower1);
$container->addFlower($flower2);
$container->addFlower($flower3);
$container->addFlower($flower4);
$container->addFlower($flower5);
$container->addBouquetDesign($bouquetDesign1);
$container->addBouquetDesign($bouquetDesign2);
$collection = GenerateBouquetCollection::fromContainer($container);
$bouquet1 = $collection[0];
$this->assertEquals([ $flower1, $flower3 ], $bouquet1->flowers());
$this->assertEquals(0, $bouquet1->totalFlowersLeft());
$bouquet2 = $collection[1];
$this->assertEquals([ $flower2, $flower4, $flower5 ], $bouquet2->flowers());
$this->assertEquals(0, $bouquet2->totalFlowersLeft());
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Entities;
final class BouquetDesign
{
private $name;
private $bouquetSize;
private $flowers;
private $totalFlowers;
public function __construct(BouquetName $name, BouquetSize $bouquetSize, array $flowers, int $totalFlowers)
{
$this->name = $name;
$this->bouquetSize = $bouquetSize;
$this->flowers = $flowers;
$this->totalFlowers = $totalFlowers;
}
public static function fromLine(string $stringLine): self
{
$chars = str_split($stringLine);
$name = new BouquetName($chars[0]);
$flowerSize = new BouquetSize($chars[1]);
$total = self::extractLastNumberOccurrence($chars);
$numOfDigitsInTotal = strlen((string)$total);
$flowerCharsSize = sizeof($chars) - 2 - $numOfDigitsInTotal;
$flowers = self::extractFlowers(
array_slice($chars, 2, $flowerCharsSize),
$flowerSize
);
return new self($name, $flowerSize, $flowers, $total);
}
private static function extractFlowers(array $chars, BouquetSize $flowerSize): array
{
$flowers = [];
while (sizeof($chars) > 0) {
$flowerQuantity = self::extractFirstNumberOccurrence($chars);
$chars = array_slice($chars, strlen((string)$flowerQuantity));
$flowerSpecie = array_shift($chars);
$flowers[] = new Flower(
new FlowerSpecie($flowerSpecie),
$flowerSize,
$flowerQuantity
);
}
return $flowers;
}
public function name(): string
{
return (string)$this->name;
}
public function bouquetSize(): string
{
return (string)$this->bouquetSize;
}
/**
* @return Flower[]
*/
public function flowers(): array
{
return $this->flowers;
}
public function totalFlowers(): int
{
return $this->totalFlowers;
}
private static function extractFirstNumberOccurrence(array $chars): int
{
$total = "";
foreach ($chars as $char) {
if (!is_numeric($char)) {
break;
}
$total = $total . $char;
}
return (int)$total;
}
private static function extractLastNumberOccurrence(array $chars): int
{
$total = "";
foreach (array_reverse($chars) as $char) {
if (!is_numeric($char)) {
break;
}
$total = $char . $total;
}
return (int)$total;
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Unit\Aggregates;
use PHPUnit\Framework\TestCase;
use Solaing\FlowerBouquets\Aggregates\FlowerBouquetContainer;
use Solaing\FlowerBouquets\Tests\Factories\FlowerFactory;
final class FlowersAreExtractedFromTheContainerTest extends TestCase
{
public final function test_flower_is_not_extracted_if_is_not_there() {
$flower1 = FlowerFactory::make("a", "S");
$flower2 = FlowerFactory::make("b", "L");
$container = new FlowerBouquetContainer();
$container->addFlower($flower1);
$container->extractFlower($flower2);
$flowerInContainer = $container->flowers()[0];
$this->assertEquals($flower1->quantity(), $flowerInContainer->quantity());
}
public final function test_flower_quantity_is_less_when_flower_is_extracted() {
$flower1 = FlowerFactory::make("a", "S", 10);
$flower2 = FlowerFactory::make("a", "S", 7);
$container = new FlowerBouquetContainer();
$container->addFlower($flower1);
$container->extractFlower($flower2);
$flowerInContainer = $container->flowers()[0];
$this->assertEquals(3, $flowerInContainer->quantity());
}
public final function test_flower_quantity_cannot_be_less_than_0() {
$flower1 = FlowerFactory::make("a", "S", 10);
$flower2 = FlowerFactory::make("a", "S", 15);
$container = new FlowerBouquetContainer();
$container->addFlower($flower1);
$container->extractFlower($flower2);
$flowerInContainer = $container->flowers()[0];
$this->assertEquals(0, $flowerInContainer->quantity());
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Factories;
use Faker\Factory;
use Solaing\FlowerBouquets\Entities\Flower;
use Solaing\FlowerBouquets\Entities\BouquetSize;
use Solaing\FlowerBouquets\Entities\FlowerSpecie;
final class FlowerFactory
{
public static function make(string $specie = null, string $size = null, int $quantity = null): Flower
{
$faker = Factory::create();
return new Flower(
new FlowerSpecie($specie ?? strtolower($faker->randomLetter)),
new BouquetSize($size ?? $faker->randomElement(["S", "L"])),
$quantity ?? random_int(1, 200)
);
}
public static function withQuantity(int $quantity): Flower
{
return self::make(null, null, $quantity);
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Entities;
use Solaing\FlowerBouquets\Exceptions\InvalidFlowerSpecie;
final class FlowerSpecie
{
private $name;
public function __construct(string $name)
{
if (!preg_match('/^[a-z]$/', $name)) {
throw InvalidFlowerSpecie::fromCharacter($name);
}
$this->name = $name;
}
public function __toString(): string
{
return $this->name;
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Unit\Aggregates;
use PHPUnit\Framework\TestCase;
use Solaing\FlowerBouquets\Exceptions\TooManyFlowersInTheBouquet;
use Solaing\FlowerBouquets\Tests\Factories\BouquetFactory;
use Solaing\FlowerBouquets\Tests\Factories\FlowerFactory;
final class BouquetCanBeCompletelyFilledTest extends TestCase
{
public final function test_bouquet_has_the_same_flowers_if_we_add_empty_collection() {
$bouquet = BouquetFactory::buildWithFlowers([
FlowerFactory::make(null, null, 1),
FlowerFactory::make(null, null, 2),
FlowerFactory::make(null, null, 3)
], 10);
$newBouquet = $bouquet->addMoreFlowers([]);
$this->assertEquals(3, sizeof($newBouquet->flowers()));
}
public final function test_bouquet_has_more_flowers_when_we_add_more() {
$bouquet = BouquetFactory::buildWithFlowers([
FlowerFactory::make(null, null, 1),
FlowerFactory::make(null, null, 1),
FlowerFactory::make(null, null, 2)
], 10);
$newBouquet = $bouquet->addMoreFlowers([
FlowerFactory::make(null, null, 1),
FlowerFactory::make(null, null, 1),
FlowerFactory::make(null, null,3)
]);
$this->assertEquals(6, sizeof($newBouquet->flowers()));
}
public final function test_bouquet_not_allow_to_have_more_flowers_than_total() {
$bouquet = BouquetFactory::buildWithFlowers([
FlowerFactory::make(null, null, 1),
FlowerFactory::make(null, null, 1),
FlowerFactory::make(null, null, 2)
], 10);
$this->expectException(TooManyFlowersInTheBouquet::class);
$newBouquet = $bouquet->addMoreFlowers([
FlowerFactory::make(null, null, 1),
FlowerFactory::make(null, null, 1),
FlowerFactory::make(null, null,25)
]);
}
}<file_sep>#!/usr/bin/php
<?php
require __DIR__ . '/vendor/autoload.php';
use Solaing\FlowerBouquets\GenerateBouquets;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
$input = new ArgvInput();
$input->setStream(fopen(__DIR__.'/resources/' . $input->getFirstArgument(), 'r'));
$output = new ConsoleOutput();
(new GenerateBouquets($input, $output))->exec();
?><file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Stubs;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
use Symfony\Component\Console\Output\OutputInterface;
final class OutputStub implements OutputInterface
{
private $writtenLines = [];
public function write($messages, $newline = false, $options = 0)
{
}
public function writeln($messages, $options = 0)
{
$this->writtenLines[] = $messages;
}
public function setVerbosity($level)
{
}
public function getVerbosity()
{
}
public function isQuiet()
{
}
public function isVerbose()
{
}
public function isVeryVerbose()
{
}
public function isDebug()
{
}
public function setDecorated($decorated)
{
}
public function isDecorated()
{
}
public function setFormatter(OutputFormatterInterface $formatter)
{
}
public function getFormatter()
{
}
public function writtenLines(): array
{
return $this->writtenLines;
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Aggregates;
use Solaing\FlowerBouquets\Entities\BouquetDesign;
use Solaing\FlowerBouquets\Entities\Flower;
use Solaing\FlowerBouquets\Entities\BouquetSize;
use Solaing\FlowerBouquets\Entities\FlowerSpecie;
final class FlowerBouquetContainer
{
/** @var Flower[] */
private $flowers = [];
/** @var BouquetDesign[] */
private $bouquetDesigns = [];
public function addFlower(Flower $flower): void
{
$flowerInContainer = $this->getSameFlowerFromTheContainer($flower);
if ($flowerInContainer === null) {
$this->flowers[] = $flower;
} else {
$newFlowerInContainer = $flowerInContainer->increaseQuantity();
$this->replaceFlowerFromSameSpecie($newFlowerInContainer);
}
}
public function addBouquetDesign(BouquetDesign $bouquetDesign): void
{
$this->bouquetDesigns[] = $bouquetDesign;
}
public function containsFlower(Flower $flower): bool
{
$flower = $this->getSameFlowerFromTheContainer($flower);
return $flower !== null && $flower->quantity() > 0;
}
public function extractFlower(Flower $flower): ?Flower
{
foreach ($this->flowers as $key => $flowerInContainer) {
if ($flowerInContainer->isSameAs($flower)) {
return $this->extractQuantityFromFlower($flowerInContainer, $flower->quantity(), $key);
}
}
return null;
}
/**
* @param int $quantity
* @return Flower[]
*/
public function extractExactQuantityOfFlowers(int $quantity): array
{
$flowersToReturn = [];
$quantityLeft = $quantity;
foreach ($this->flowers as $key => $flowerInContainer) {
if ($quantityLeft === 0) {
break;
}
if ($flowerInContainer->quantity() === 0) {
continue;
}
$quantityToExtract = $this->calculateExactQuantityToExtract($quantityLeft, $flowerInContainer);
$this->extractQuantityFromFlower($flowerInContainer, $quantityToExtract, $key);
$flowersToReturn[] = new Flower(
new FlowerSpecie($flowerInContainer->specie()),
new BouquetSize($flowerInContainer->bouquetSize()),
$quantityToExtract
);
$quantityLeft = max($quantityLeft - $flowerInContainer->quantity(), 0);
}
return $flowersToReturn;
}
private function getSameFlowerFromTheContainer(Flower $flower): ?Flower
{
foreach ($this->flowers as $flowerInContainer) {
if ($flowerInContainer->isSameAs($flower)) {
return $flowerInContainer;
}
}
return null;
}
private function replaceFlowerFromSameSpecie(Flower $flower): void
{
foreach ($this->flowers as $key => $flowerInContainer) {
if ($flowerInContainer->isSameAs($flower)) {
$this->flowers[$key] = $flower;
return;
}
}
}
/**
* @return Flower[]
*/
public function flowers(): array
{
return $this->flowers;
}
public function bouquetDesigns(): array
{
return $this->bouquetDesigns;
}
public function extractQuantityFromFlower(Flower $flowerInContainer, int $quantity, int $key): Flower
{
$flowerWithQuantityExtracted = $flowerInContainer->extractQuantity($quantity);
$this->flowers[$key] = $flowerWithQuantityExtracted;
return $flowerWithQuantityExtracted;
}
public function calculateExactQuantityToExtract(int $quantityLeft, Flower $flowerInContainer): int
{
$quantityToExtract = $quantityLeft;
if ($quantityToExtract > $flowerInContainer->quantity()) {
$quantityToExtract = $flowerInContainer->quantity();
}
return $quantityToExtract;
}
}<file_sep>FROM phpunit/phpunit:latest
MAINTAINER <NAME> <<EMAIL>>
WORKDIR /app
COPY . /app
VOLUME ["/app"]
RUN composer install --no-dev --no-interaction -o<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Exceptions;
final class InvalidBouquetName extends \InvalidArgumentException
{
public static function fromInvalidName(string $name): self
{
return new self("The bouquet name '$name'' is invalid");
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Integration;
use PHPUnit\Framework\TestCase;
use Solaing\FlowerBouquets\GenerateBouquets;
use Solaing\FlowerBouquets\Tests\Stubs\InputStub;
use Solaing\FlowerBouquets\Tests\Stubs\OutputStub;
final class TheFlowerBouquetsAreGeneratedInTheOutputTest extends TestCase
{
private const RESOURCES_DIR_PATH = __DIR__ . '/../../resources';
private $output;
private $input;
public function setUp(): void
{
parent::setUp();
$this->output = new OutputStub();
$this->input = new InputStub();
}
public final function test_the_flower_bouquets_title_is_generated() {
$filePath = self::RESOURCES_DIR_PATH . '/empty_file.txt';
$this->input->setStream(fopen($filePath, 'r'));
(new GenerateBouquets($this->input, $this->output))->exec();
$writtenLines = $this->output->writtenLines();
$this->assertEquals('----- Flower Bouquets ---', $writtenLines[1]);
}
public final function test_the_bouquet_is_rendered_without_flowers() {
$filePath = self::RESOURCES_DIR_PATH . '/bouquet_design.txt';
$this->input->setStream(fopen($filePath, 'r'));
(new GenerateBouquets($this->input, $this->output))->exec();
$writtenLines = $this->output->writtenLines();
$this->assertEquals('AL', $writtenLines[3]);
}
public final function test_any_bouquet_is_rendered_with_only_flowers() {
$filePath = self::RESOURCES_DIR_PATH . '/multiple_flowers.txt';
$this->input->setStream(fopen($filePath, 'r'));
(new GenerateBouquets($this->input, $this->output))->exec();
$writtenLines = $this->output->writtenLines();
$this->assertEquals(3, sizeof($writtenLines));
}
public final function test_multiple_bouquets_are_rendered_with_multiple_designs() {
$filePath = self::RESOURCES_DIR_PATH . '/multiple_bouquet_designs.txt';
$this->input->setStream(fopen($filePath, 'r'));
(new GenerateBouquets($this->input, $this->output))->exec();
$writtenLines = $this->output->writtenLines();
$this->assertEquals('AL', $writtenLines[3]);
$this->assertEquals('AS', $writtenLines[4]);
$this->assertEquals('BL', $writtenLines[5]);
$this->assertEquals('BS', $writtenLines[6]);
$this->assertEquals('CL', $writtenLines[7]);
$this->assertEquals('DL', $writtenLines[8]);
}
public final function test_with_the_sample() {
$filePath = self::RESOURCES_DIR_PATH . '/sample.txt';
$this->input->setStream(fopen($filePath, 'r'));
(new GenerateBouquets($this->input, $this->output))->exec();
$writtenLines = $this->output->writtenLines();
$this->assertStringContainsString('ALa10b15c5', $writtenLines[3]);
$this->assertStringContainsString('ASa10b10c5', $writtenLines[4]);
$this->assertStringContainsString('BLb15c1c5', $writtenLines[5]);
$this->assertStringContainsString('BSb10c5c1', $writtenLines[6]);
$this->assertStringContainsString('CLa20c15c10', $writtenLines[7]);
$this->assertStringContainsString('DLb20c8', $writtenLines[8]);
}
public function tearDown(): void
{
unset($this->output);
parent::tearDown();
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Unit\Aggregates;
use PHPUnit\Framework\TestCase;
use Solaing\FlowerBouquets\Entities\Flower;
use Solaing\FlowerBouquets\Aggregates\FlowerBouquetContainer;
use Solaing\FlowerBouquets\Tests\Factories\BouquetDesignFactory;
use Solaing\FlowerBouquets\Tests\Factories\FlowerFactory;
final class ContainerStoresTheFlowersAndBouquetsTest extends TestCase
{
final public function test_the_container_adds_flowers() {
$flower = FlowerFactory::make();
$container = new FlowerBouquetContainer();
$container->addFlower($flower);
$this->assertEquals($flower, $container->flowers()[0]);
}
final public function test_the_container_adds_bouquet_designs() {
$bouquetDesign = BouquetDesignFactory::make();
$container = new FlowerBouquetContainer();
$container->addBouquetDesign($bouquetDesign);
$this->assertEquals($bouquetDesign, $container->bouquetDesigns()[0]);
}
final public function test_the_container_increases_the_quantity_of_flowers_if_is_there() {
$flower1 = FlowerFactory::make();
$flower2 = FlowerFactory::make($flower1->specie(), $flower1->bouquetSize());
$container = new FlowerBouquetContainer();
$container->addFlower($flower1);
$container->addFlower($flower2);
/** @var Flower $flower */
$flower = $container->flowers()[0];
$this->assertEquals($flower1->quantity() + 1, $flower->quantity());
}
final public function test_the_container_NOT_increase_the_quantity_if_the_specie_is_NOT_there() {
$flower1 = FlowerFactory::make("a");
$flower2 = FlowerFactory::make("b");
$container = new FlowerBouquetContainer();
$container->addFlower($flower1);
$container->addFlower($flower2);
/** @var Flower $flower */
$flower = $container->flowers()[0];
$this->assertEquals($flower1->quantity(), $flower->quantity());
}
final public function test_the_container_NOT_increase_the_quantity_if_the_size_does_not_match() {
$flower1 = FlowerFactory::make("a", "S");
$flower2 = FlowerFactory::make("a", "L");
$container = new FlowerBouquetContainer();
$container->addFlower($flower1);
$container->addFlower($flower2);
/** @var Flower $flower */
$flower = $container->flowers()[0];
$this->assertEquals($flower1->quantity(), $flower->quantity());
}
final public function test_container_knows_if_a_flower_exists() {
$flower1 = FlowerFactory::make();
$container = new FlowerBouquetContainer();
$container->addFlower($flower1);
$this->assertTrue($container->containsFlower($flower1));
}
final public function test_container_knows_if_a_flower_NOT_exists() {
$flower1 = FlowerFactory::make();
$container = new FlowerBouquetContainer();
$this->assertFalse($container->containsFlower($flower1));
}
final public function test_container_knows_when_there_are_no_more_flowers_left() {
$flower1 = FlowerFactory::make("a", "S", 0);
$container = new FlowerBouquetContainer();
$container->addFlower($flower1);
$this->assertFalse($container->containsFlower($flower1));
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Factories;
use Faker\Factory;
use Solaing\FlowerBouquets\Entities\BouquetDesign;
use Solaing\FlowerBouquets\Entities\BouquetName;
use Solaing\FlowerBouquets\Entities\BouquetSize;
final class BouquetDesignFactory
{
public static function make(array $flowers = null, int $quantity = null): BouquetDesign
{
$faker = Factory::create();
return new BouquetDesign(
new BouquetName(strtoupper($faker->randomLetter)),
new BouquetSize($faker->randomElement(['S', 'L'])),
$flowers ?? self::generateFlowers(),
$quantity ?? random_int(1, 200)
);
}
private static function generateFlowers() {
$flowers = [];
$numOfInstances = random_int(1, 5);
while ($numOfInstances > 0) {
$flowers[] = FlowerFactory::make();
--$numOfInstances;
}
return $flowers;
}
}<file_sep># Flower Bouquets
This is a console application that generates a collection of flower bouquets based on a set of bouquet design and a set
of flower species.
This application was implemented for a company code challenge.
## Installation
### Locally
You just need to run `composer` to install the dependencies.
```php
composer install
```
### Using Docker
You just need to build a new docker container using the Dockerfile included in the root folder of the project.
```bash
docker build .
```
Please check the Docker documentation if you want to know more about it -> https://docs.docker.com/engine/reference/commandline/build/
## Usage
This application can be executed using the `run.php` file and including the input stream that the application is going to
consume in the `/resources` folder. You need to include your input in file and pass the filename as an argument when you execute the PHP file through the console.
Please take a look into this folder, you will find some examples about the input format.
### About the source code
On the other hand, you can see that the class `\Solaing\FlowerBouquets\GenerateBouquets` has injected a `\Symfony\Component\Console\Input\StreamableInputInterface` and a
`\Symfony\Component\Console\Output\OutputInterface`.
It makes this code completely customizable with any kind of input or output that implements those interfaces.
I suggest you to take a look into the [Symfony Console](https://symfony.com/doc/current/components/console.html) package to get some ideas of how you can run this class.
## Running the application
Dont' forget to add your input file before you run the application ;)
### Locally
Simply run in the root folder using the php binary.
```php
php -f run.php <YOUR INPUT FILE>.txt
```
### Using Docker
Same idea but we need to execute the command in the container and redirect the std output.
```php
docker exec -it <CONTAINER ID OR NAME> bash -c "php -f run.php <YOUR INPUT FILE>.txt 2>&1"
```
## Running Tests
This application is completely tested to be sure everything works fine and to give the reader some help to understand
the implementation.
### Locally
Simply run the PHPUnit binary located in the `vendor` folder.
```php
vendor/bin/phpunit
```
### Using Docker
Same idea but we need to execute the command in the container and redirect the std output.
```php
docker exec -it <CONTAINER ID OR NAME> bash -c "vendor/bin/phpunit 2>&1"
```<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Exceptions;
use InvalidArgumentException;
final class InvalidFlowerSpecie extends InvalidArgumentException
{
public static function fromCharacter(string $specie): self
{
return new self("The flower specie '$specie'' is invalid");
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Unit\Entities;
use PHPUnit\Framework\TestCase;
use Solaing\FlowerBouquets\Entities\BouquetDesign;
use Solaing\FlowerBouquets\Entities\Flower;
final class BouquetDesignIsGeneratedFromStringLineTest extends TestCase
{
public final function test_bouquet_design_contains_the_correct_name()
{
$bouquetDesign = BouquetDesign::fromLine("AS3a4b6k20");
$this->assertEquals("A", $bouquetDesign->name());
}
public final function test_bouquet_design_contains_the_correct_flower_size()
{
$bouquetDesign = BouquetDesign::fromLine("AS3a4b6k20");
$this->assertEquals("S", $bouquetDesign->bouquetSize());
}
public final function test_bouquet_design_contains_the_correct_total()
{
$bouquetDesign = BouquetDesign::fromLine("AS3a4b6k345667");
$this->assertEquals(345667, $bouquetDesign->totalFlowers());
}
public final function test_bouquet_design_contains_the_correct_flower()
{
$bouquetDesign = BouquetDesign::fromLine("AS3a20");
/** @var Flower $flower */
$flower = $bouquetDesign->flowers()[0];
$this->assertEquals("a", $flower->specie());
$this->assertEquals("S", $flower->bouquetSize());
$this->assertEquals(3, $flower->quantity());
}
public final function test_bouquet_design_contains_the_correct_number_of_flowers()
{
$bouquetDesign = BouquetDesign::fromLine("AS3a4b6k20");
$flowers = $bouquetDesign->flowers();
/** @var Flower $flower */
$flower = $flowers[0];
$this->assertEquals("a", $flower->specie());
$this->assertEquals("S", $flower->bouquetSize());
$this->assertEquals(3, $flower->quantity());
$flower = $flowers[1];
$this->assertEquals("b", $flower->specie());
$this->assertEquals("S", $flower->bouquetSize());
$this->assertEquals(4, $flower->quantity());
$flower = $flowers[2];
$this->assertEquals("k", $flower->specie());
$this->assertEquals("S", $flower->bouquetSize());
$this->assertEquals(6, $flower->quantity());
}
public final function test_bouquet_design_contains_flowers_with_more_than_one_digit_in_the_quantity()
{
$bouquetDesign = BouquetDesign::fromLine("AS30a44b6k20");
$flowers = $bouquetDesign->flowers();
/** @var Flower $flower */
$flower = $flowers[0];
$this->assertEquals(30, $flower->quantity());
$flower = $flowers[1];
$this->assertEquals(44, $flower->quantity());
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Entities;
use Solaing\FlowerBouquets\Exceptions\InvalidBouquetSize;
final class BouquetSize
{
private $size;
/**
* @param string $size
*
* @throws InvalidBouquetSize
*/
public function __construct(string $size)
{
if (!preg_match('/^(S|L)$/', $size)) {
throw InvalidBouquetSize::fromCharacter($size);
}
$this->size = $size;
}
public function __toString(): string
{
return $this->size;
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Aggregates;
use Solaing\FlowerBouquets\Entities\BouquetName;
use Solaing\FlowerBouquets\Entities\Flower;
use Solaing\FlowerBouquets\Entities\BouquetSize;
use Solaing\FlowerBouquets\Exceptions\TooManyFlowersInTheBouquet;
final class Bouquet
{
private $name;
private $flowerSize;
/** @var Flower[] */
private $flowers;
/**
* @var int
*/
private $totalFlowers;
public function __construct(BouquetName $name, BouquetSize $flowerSize, array $flowers, int $totalFlowers)
{
$this->name = $name;
$this->flowerSize = $flowerSize;
$this->flowers = $flowers;
$this->totalFlowers = $totalFlowers;
}
public function name(): string
{
return (string)$this->name;
}
public function flowerSize(): BouquetSize
{
return $this->flowerSize;
}
public function flowers(): array
{
return $this->flowers;
}
public function totalFlowersLeft(): int
{
$totalQuantityOfFlowers = $this->getTotalQuantityOfFlowers($this->flowers);
return max($this->totalFlowers - $totalQuantityOfFlowers, 0);
}
/**
* @param array $flowers
* @return $this
*
* @throws TooManyFlowersInTheBouquet
*/
public function addMoreFlowers(array $flowers): self
{
$totalQuantityOfFlowers = $this->mergeTotalQuantityOfFlowers($flowers);
if ($totalQuantityOfFlowers > $this->totalFlowers) {
throw TooManyFlowersInTheBouquet::withQuantities(
$this->name(),
$this->totalFlowers,
$totalQuantityOfFlowers
);
}
$newBouquet = clone $this;
$newBouquet->flowers = array_merge($newBouquet->flowers, $flowers);
return $newBouquet;
}
public function render(): string
{
$output = $this->name . $this->flowerSize();
foreach ($this->flowers as $flower) {
$output .= $flower->render();
}
return $output;
}
private function getTotalQuantityOfFlowers(array $flowers): int
{
if (sizeof($flowers) === 0) {
return 0;
}
return array_reduce($flowers, function ($totalFlowers, Flower $flower) {
return $totalFlowers + $flower->quantity();
});
}
public function mergeTotalQuantityOfFlowers(array $flowers): int
{
return $this->getTotalQuantityOfFlowers($this->flowers) + $this->getTotalQuantityOfFlowers($flowers);
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Stubs;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\StreamableInputInterface;
final class InputStub implements StreamableInputInterface
{
private $stream;
public function setStream($stream)
{
$this->stream = $stream;
}
public function getStream()
{
return $this->stream;
}
public function getFirstArgument()
{
}
public function hasParameterOption($values, $onlyParams = false)
{
}
public function getParameterOption($values, $default = false, $onlyParams = false)
{
}
public function bind(InputDefinition $definition)
{
}
public function validate()
{
}
public function getArguments()
{
}
public function getArgument($name)
{
}
public function setArgument($name, $value)
{
}
public function hasArgument($name)
{
}
public function getOptions()
{
}
public function getOption($name)
{
}
public function setOption($name, $value)
{
}
public function hasOption($name)
{
}
public function isInteractive()
{
}
public function setInteractive($interactive)
{
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Unit\Input;
use PHPUnit\Framework\TestCase;
use Solaing\FlowerBouquets\Input\GenerateFlowerBouquetContainer;
final class FlowerBouquetContainerIsBeingGeneratedFromFileTest extends TestCase
{
private const RESOURCES_DIR_PATH = __DIR__ . '/../../../resources';
public final function test_container_is_not_filled_when_there_is_an_empty_line() {
$streamResource = fopen(self::RESOURCES_DIR_PATH . '/empty_file.txt', 'r');
$container = GenerateFlowerBouquetContainer::fromResource($streamResource);
$this->assertEmpty($container->flowers());
$this->assertEmpty($container->bouquetDesigns());
}
public final function test_container_is_filled_with_a_flower() {
$streamResource = fopen(self::RESOURCES_DIR_PATH . '/one_flower.txt', 'r');
$container = GenerateFlowerBouquetContainer::fromResource($streamResource);
$this->assertEquals(1, sizeof($container->flowers()));
}
public final function test_container_is_filled_with_a_multiple_flowers() {
$streamResource = fopen(self::RESOURCES_DIR_PATH . '/multiple_flowers.txt', 'r');
$container = GenerateFlowerBouquetContainer::fromResource($streamResource);
$this->assertEquals(5, sizeof($container->flowers()));
}
public final function test_container_is_filled_with_a_the_wrong_flowers() {
$streamResource = fopen(self::RESOURCES_DIR_PATH . '/wrong_flowers.txt', 'r');
$container = GenerateFlowerBouquetContainer::fromResource($streamResource);
$this->assertEquals(3, sizeof($container->flowers()));
}
public final function test_container_is_filled_with_a_bouquet_design() {
$streamResource = fopen(self::RESOURCES_DIR_PATH . '/bouquet_design.txt', 'r');
$container = GenerateFlowerBouquetContainer::fromResource($streamResource);
$this->assertEquals(1, sizeof($container->bouquetDesigns()));
}
public final function test_container_is_filled_with_multiple_bouquet_designs() {
$streamResource = fopen(self::RESOURCES_DIR_PATH . '/multiple_bouquet_designs.txt', 'r');
$container = GenerateFlowerBouquetContainer::fromResource($streamResource);
$this->assertEquals(6, sizeof($container->bouquetDesigns()));
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Input;
use Solaing\FlowerBouquets\Entities\BouquetDesign;
use Solaing\FlowerBouquets\Entities\Flower;
use Solaing\FlowerBouquets\Aggregates\FlowerBouquetContainer;
final class GenerateFlowerBouquetContainer
{
private function __construct()
{
}
public static function fromResource($streamResource): FlowerBouquetContainer
{
$container = new FlowerBouquetContainer();
while (!feof($streamResource)) {
$stringLine = trim((string)fgetss($streamResource));
if (self::isEmptyLine($stringLine)) {
continue;
}
if (self::isFormattedForFlower($stringLine)) {
$container->addFlower(Flower::fromLine($stringLine));
continue;
}
if (self::isFormattedForBouquetDesign($stringLine)) {
$container->addBouquetDesign(BouquetDesign::fromLine($stringLine));
}
}
fclose($streamResource);
return $container;
}
private static function isEmptyLine(string $line): bool
{
return empty($line);
}
private static function isFormattedForFlower(string $line): bool
{
return (bool)preg_match('/^[a-z](S|L)$/', $line);
}
private static function isFormattedForBouquetDesign(string $line): bool
{
return (bool)preg_match('/^[A-Z](S|L)(.*)([0-9]+)$/', $line);
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Unit\Aggregates;
use PHPUnit\Framework\TestCase;
use Solaing\FlowerBouquets\Tests\Factories\BouquetFactory;
use Solaing\FlowerBouquets\Tests\Factories\FlowerFactory;
final class BouquetIsRenderedWithCorrectFormatTest extends TestCase
{
final public function test_when_bouquet_has_no_flowers() {
$bouquet = BouquetFactory::buildWithNameAndSize('A', 'S');
$output = $bouquet->render();
$this->assertEquals('AS', $output);
}
final public function test_when_bouquet_has_some_flowers() {
$flowers = [
FlowerFactory::make('a', 'S', 5),
FlowerFactory::make('b', 'S', 7),
FlowerFactory::make('c', 'S', 9),
];
$bouquet = BouquetFactory::build('A', 'S', $flowers, 30);
$output = $bouquet->render();
$this->assertEquals('ASa5b7c9', $output);
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Entities;
use Solaing\FlowerBouquets\Exceptions\InvalidBouquetName;
final class BouquetName
{
private $name;
/**
* @param string $name
*
* @throws InvalidBouquetName
*/
public function __construct(string $name)
{
if (!preg_match('/^[A-Z]$/', $name)) {
throw InvalidBouquetName::fromInvalidName($name);
}
$this->name = $name;
}
public function __toString(): string
{
return $this->name;
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Output;
use Solaing\FlowerBouquets\Aggregates\Bouquet;
use Solaing\FlowerBouquets\Entities\BouquetDesign;
use Solaing\FlowerBouquets\Entities\BouquetName;
use Solaing\FlowerBouquets\Aggregates\FlowerBouquetContainer;
use Solaing\FlowerBouquets\Entities\BouquetSize;
final class GenerateBouquetCollection
{
private function __construct()
{
}
/**
* @param FlowerBouquetContainer $container
* @return Bouquet[]
*/
public static function fromContainer(FlowerBouquetContainer $container): array
{
/** @var Bouquet[] $bouquets */
$bouquets = [];
/** @var BouquetDesign[] $bouquetDesigns */
$bouquetDesigns = $container->bouquetDesigns();
foreach ($bouquetDesigns as $bouquetDesign) {
$bouquets[] = self::generateBouquet($bouquetDesign, $container);
}
foreach ($bouquets as $key => $bouquet) {
$totalFlowersLeft = $bouquet->totalFlowersLeft();
if ($totalFlowersLeft > 0) {
$bouquets[$key] = self::refillBouquet($container, $totalFlowersLeft, $bouquet);
}
}
return $bouquets;
}
private static function generateBouquet(BouquetDesign $bouquetDesign, FlowerBouquetContainer $container): Bouquet
{
$flowersInBouquet = [];
foreach ($bouquetDesign->flowers() as $flower) {
if (null === $container->extractFlower($flower)) {
continue;
}
$flowersInBouquet[] = $flower;
}
return new Bouquet(
new BouquetName($bouquetDesign->name()),
new BouquetSize($bouquetDesign->bouquetSize()),
$flowersInBouquet,
$bouquetDesign->totalFlowers()
);
}
private static function refillBouquet(FlowerBouquetContainer $container, int $totalFlowersLeft, Bouquet $bouquet): Bouquet
{
$flowersFromContainer = $container->extractExactQuantityOfFlowers($totalFlowersLeft);
return $bouquet->addMoreFlowers($flowersFromContainer);
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Unit\Aggregates;
use PHPUnit\Framework\TestCase;
use Solaing\FlowerBouquets\Tests\Factories\BouquetFactory;
use Solaing\FlowerBouquets\Tests\Factories\FlowerFactory;
final class BouquetControlsTheNumFlowersTest extends TestCase
{
public final function test_when_there_are_no_flowers() {
$bouquet = BouquetFactory::buildWithFlowers([], 10);
$this->assertEquals(10, $bouquet->totalFlowersLeft());
}
public final function test_when_the_are_some_flowers_left() {
$bouquet = BouquetFactory::buildWithFlowers([
FlowerFactory::make("a", "S", 2),
FlowerFactory::make("b", "S", 1),
FlowerFactory::make("s", "S", 3)
], 10);
$this->assertEquals(4, $bouquet->totalFlowersLeft());
}
public final function test_when_there_are_no_flowers_left() {
$bouquet = BouquetFactory::buildWithFlowers([
FlowerFactory::make("a", "S", 2),
FlowerFactory::make("b", "S", 1),
FlowerFactory::make("s", "S", 7)
], 10);
$this->assertEquals(0, $bouquet->totalFlowersLeft());
}
public final function test_cannot_be_less_than_0_flowers_left() {
$bouquet = BouquetFactory::buildWithFlowers([
FlowerFactory::make("a", "S", 2),
FlowerFactory::make("b", "S", 4),
FlowerFactory::make("s", "S", 7)
], 10);
$this->assertEquals(0, $bouquet->totalFlowersLeft());
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Entities;
final class Flower
{
private $specie;
private $bouquetSize;
private $quantity;
public function __construct(FlowerSpecie $specie, BouquetSize $size, int $quantity)
{
$this->specie = $specie;
$this->bouquetSize = $size;
$this->quantity = $quantity;
}
public static function fromLine(string $stringLine): self
{
$chars = str_split($stringLine);
return new self(new FlowerSpecie($chars[0]), new BouquetSize($chars[1]), 1);
}
public function increaseQuantity(): self {
$newFlower = clone $this;
++$newFlower->quantity;
return $newFlower;
}
public function extractQuantity(int $quantity): self {
$newFlower = clone $this;
if ($newFlower->quantity() < $quantity) {
$newFlower->quantity = 0;
} else {
$newFlower->quantity = $newFlower->quantity - $quantity;
}
return $newFlower;
}
public function specie(): string
{
return (string)$this->specie;
}
public function bouquetSize(): string
{
return (string)$this->bouquetSize;
}
public function quantity(): int
{
return $this->quantity;
}
public function isSameAs(Flower $flower): bool
{
return $this->specie() === $flower->specie() && $this->bouquetSize() === $flower->bouquetSize();
}
public function render(): string
{
return $this->specie() . $this->quantity();
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Exceptions;
final class TooManyFlowersInTheBouquet extends \InvalidArgumentException
{
public static function withQuantities(string $bouquetName, int $expected, int $actual): self
{
return new self("The Bouquet $bouquetName can contain only $expected flowers, but received $actual.");
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Unit\Entities;
use PHPUnit\Framework\TestCase;
use Solaing\FlowerBouquets\Entities\Flower;
use Solaing\FlowerBouquets\Exceptions\InvalidBouquetSize;
use Solaing\FlowerBouquets\Exceptions\InvalidFlowerSpecie;
final class FlowerIsGeneratedFromStringLineTest extends TestCase
{
final public function test_flower_is_generated_with_the_proper_format() {
$flower = Flower::fromLine("aL");
$this->assertEquals("a", $flower->specie());
$this->assertEquals("L", $flower->bouquetSize());
$this->assertEquals(1, $flower->quantity());
}
final public function test_flower_is_not_generated_with_the_wrong_size() {
$this->expectException(InvalidBouquetSize::class);
Flower::fromLine("aK");
}
final public function test_flower_is_not_generated_with_the_wrong_specie() {
$this->expectException(InvalidFlowerSpecie::class);
Flower::fromLine("WL");
}
}<file_sep><?php
declare(strict_types=1);
namespace Solaing\FlowerBouquets\Tests\Unit\Aggregates;
use PHPUnit\Framework\TestCase;
use Solaing\FlowerBouquets\Aggregates\FlowerBouquetContainer;
use Solaing\FlowerBouquets\Tests\Factories\FlowerFactory;
final class ContainerExtractsExactQuantityOfFlowersTest extends TestCase
{
public final function test_when_the_bouquet_has_no_flowers() {
$container = new FlowerBouquetContainer();
$this->assertEmpty($container->extractExactQuantityOfFlowers(10));
}
public final function test_when_flower_has_more_quantity() {
$container = new FlowerBouquetContainer();
$flower = FlowerFactory::withQuantity(15);
$container->addFlower($flower);
$flowers = $container->extractExactQuantityOfFlowers(10);
$this->assertEquals(1, sizeof($flowers));
$flowerInContainer = $container->flowers()[0];
$this->assertEquals(5, $flowerInContainer->quantity());
}
public final function test_when_flower_has_less_quantity() {
$container = new FlowerBouquetContainer();
$flower = FlowerFactory::withQuantity(3);
$container->addFlower($flower);
$flowers = $container->extractExactQuantityOfFlowers(10);
$this->assertEquals(1, sizeof($flowers));
$flowerInContainer = $container->flowers()[0];
$this->assertEquals(0, $flowerInContainer->quantity());
}
public final function test_flowers_with_quantity_0_are_not_included() {
$container = new FlowerBouquetContainer();
$flower1 = FlowerFactory::withQuantity(0);
$flower2 = FlowerFactory::withQuantity(5);
$container->addFlower($flower1);
$container->addFlower($flower2);
$flowers = $container->extractExactQuantityOfFlowers(10);
$this->assertEquals(1, sizeof($flowers));
}
public final function test_extracted_flower_has_the_quantity_requested() {
$container = new FlowerBouquetContainer();
$flower1 = FlowerFactory::withQuantity(10);
$container->addFlower($flower1);
$flowers = $container->extractExactQuantityOfFlowers(5);
$flowerExtracted = $flowers[0];
$this->assertEquals(5, $flowerExtracted->quantity());
}
} | 1ab8ca77b494296062408ff47784e86bf8cfbf6c | [
"Markdown",
"Dockerfile",
"PHP"
] | 33 | PHP | dsola/flower_bouquets | 603d6cc07ab79790a2ad7a114836938dc174052c | 2712fb7979c3077e8959187e52dffdeae3715f4d | |
refs/heads/master | <file_sep>import math
class Weather:
def __init__(self, main='s'):
self.main = main<file_sep>
def getAPIdata():
return APIKEY, CITY
APIKEY = '<KEY>'
CITY = 'Tijuana'
<file_sep>import os
from time import sleep
def getImages(path):
for root, directories, f in os.walk(path):
for file in f:
if ('.jpg' in file or '.png' in file or '.jpeg' in file):
files.append(os.path.join(root, file))
return files
files = []
<file_sep># smartSlideshow
This is a program that checks if the current day is a holiday. If so it fetches wallpapers from unsplash related and sets a slideshow with them. Otherwise gets the current weather and sets wallpapers related.
<file_sep>from time import sleep
from selenium import webdriver
from Weather import *
from driverPrefs import *
from fileManager import *
import datetime
import holidays
import requests
import json
import random
import API
import wget
imageCount = 4
search = ''
imagesPath = '/home/godys/Pictures/Unsplash/'
images = []
#Erase Previous Images
images = getImages(imagesPath)
if len(images) > 0:
for image in images:
if (os.path.exists(image)): os.remove(image)
#Set Browser Config
ch_options = getPrefs()
drive = None
#Set API variables
current_weather = Weather()
response = {}
API_KEY, CITY = API.getAPIdata()
#Search for Today's Events
mx_holidays = holidays.Mexico()
today = str(datetime.datetime.today()).split()[0]
today_holiday = mx_holidays.get(today)
if (today_holiday): #If event exists
search = today_holiday
search.replace(' ', '-')
else: #Otherwise get the current weather
mainPage = ''
req = requests.get("http://api.openweathermap.org/data/2.5/weather?q={}&appid={}".format(CITY, API_KEY))
response = json.loads(req.content)
current_weather.main = response["weather"][0]["description"]
current_weather.main.replace(' ', '-')
search = current_weather.main
#Launch the browser
drive = webdriver.PhantomJS('/home/godys/Documents/phantomjs/bin/phantomjs')
drive.maximize_window()
mainPage = 'https://unsplash.com/s/photos/'+search+'?orientation=landscape'
#Pick 5 random images from the results and download them
for i in range(imageCount):
drive.get(mainPage)
images = drive.find_elements_by_class_name('_2Mc8_')
download_link = images[random.randint(0,len(images)-1)].get_attribute('href')+'/download?force=true&w=2400'
session = requests.Session()
cookies = drive.get_cookies()
for cookie in cookies:
session.cookies.set(cookie['name'], cookie['value'])
res = session.get(download_link)
open('/home/godys/Pictures/Unsplash/image'+str(i)+'.jpg', 'wb').write(res.content)
print(res.content)
sleep(1)
drive.quit()
#Get every image exact path
images = getImages(imagesPath)
#Every two minutes change the background
while True:
for image in images:
os.system('/usr/bin/gsettings set org.gnome.desktop.background picture-uri '+image)
sleep(120)<file_sep>from selenium import webdriver
def getPrefs():
return ch_options
ch_options = webdriver.chrome.options.Options()
prefs = {
'profile.default_content_setting_values.automatic_downloads': 1,
"download.default_directory" : "/home/godys/Pictures/Unsplash"
}
ch_options.add_experimental_option("prefs", prefs) | 548f0a265ddff2199a6a3de98218209bf348c504 | [
"Markdown",
"Python"
] | 6 | Python | Godys05/smartSlideshow | 397220995a45f60f3cbae31653f943622b3ccb2f | d611707ac5276ee4917ec3d5f37584f603d33a19 | |
refs/heads/develop | <repo_name>ianpaschal/aurora<file_sep>/tests/core/Entity.test.ts
import { Component, Entity, System } from "../../src";
import uuid from "uuid";
let instance: Entity;
const config = {
uuid: uuid(),
type: "foo",
name: "FooBar",
components: [
{ type: "foo", data: { isFoo: true } }
]
};
beforeEach( () => {
instance = new Entity( config );
});
// Constructor
describe( "Entity.constructor( config )", () => {
it( "should copy the config's name if it exists.", () => {
expect( instance.name ).toEqual( config.name );
});
it( "should copy the config's type if it exists.", () => {
expect( instance.type ).toEqual( config.type );
});
it( "should copy the config's UUID if it exists.", () => {
expect( instance.uuid ).toEqual( config.uuid );
});
it( "should instantiate components defined in config.", () => {
expect( instance.hasComponent( "foo" ) ).toBe( true );
});
});
// Getters
describe( "Entity.uuid", () => {
it ( "should always be defined.", () => {
expect( instance.uuid ).toBeDefined();
});
});
describe( "Entity.json", () => {
it( "should be a formatted JSON string representing the entity.", () => {
expect( JSON.parse( instance.json ) ).toEqual({
"destroy": false,
"dirty": true,
"uuid": config.uuid,
"type": config.type,
"name": config.name,
"components": [
{
"data": { "isFoo": true },
"type": "foo",
"uuid": instance.getComponent( "foo" ).uuid
}
]
});
});
});
describe( "Entity.componentTypes", () => {
it( "should return an array of component types.", () => {
expect( instance.componentTypes ).toEqual( [ "foo" ] );
});
});
// Other
describe( "Entity.addComponent( component )", () => {
let component: Component;
let length: number;
beforeEach( () => {
component = new Component();
length = instance.components.length;
instance.addComponent( component );
});
it( "should add the component if it doesn't exist already.", () => {
expect( instance.components.length ).toEqual( length + 1 );
});
it( "should throw an error if that component is already added.", () => {
expect( () => {
instance.addComponent( component );
}).toThrowError();
});
});
describe( "Entity.clone()", () => {
let clone: Entity;
beforeEach( () => {
clone = instance.clone();
});
it( "should not clone the UUID.", () => {
expect( clone.uuid ).not.toEqual( instance.uuid );
});
it( "should clone the type.", () => {
expect( clone.type ).toEqual( instance.type );
});
it( "should clone the data.", () => {
for( let i = 0; i < instance.components.length; i++ ) {
const original = instance.components[ i ];
expect( clone.components[ i ].uuid ).not.toEqual( original.uuid );
expect( clone.components[ i ].type ).toEqual( original.type );
expect( clone.components[ i ].data ).toEqual( original.data );
}
});
});
describe( "Entity.copy( entity )", () => {
let source: Entity;
beforeEach( () => {
source = new Entity({
uuid: uuid(),
type: "foo",
components: []
});
instance.copy( source );
});
it( "should not copy the UUID.", () => {
expect( instance.uuid ).not.toEqual( source.uuid );
});
it( "should copy the type.", () => {
expect( instance.type ).toEqual( source.type );
});
it( "should copy the data.", () => {
for( let i = 0; i < source.components.length; i++ ) {
const original = source.components[ i ];
expect( instance.components[ i ].uuid ).not.toEqual( original.uuid );
expect( instance.components[ i ].type ).toEqual( original.type );
expect( instance.components[ i ].data ).toEqual( original.data );
}
});
});
describe( "Entity.getComponentData( type )", () => {
it( "should return the component data if it exists.", () => {
expect( instance.getComponentData( "foo" ) ).toEqual({ isFoo: true });
});
it( "should throw an error if no component of that type exists.", () => {
expect( () => {
instance.getComponentData( "bar" );
}).toThrowError();
});
});
describe( "Entity.isWatchableBy( system )", () => {
let systemFoo: System;
let systemBar: System;
beforeEach( () => {
systemFoo = new System({
componentTypes: [ "foo" ],
name: "foo-system",
onUpdate( t ) {}
});
systemBar = new System({
componentTypes: [ "bar" ],
name: "bar-system",
onUpdate( t ) {}
});
});
test( "should return true if the entity has all required components.", () => {
expect( instance.isWatchableBy( systemFoo ) ).toBe( true );
});
test( "should return false if the entity is missing a component.", () => {
expect( instance.isWatchableBy( systemBar ) ).toBe( false );
});
});
describe( "Entity.removeComponent( type )", () => {
it( "should remove the component if it exists.", () => {
const length = instance.components.length;
instance.removeComponent( "foo" );
expect( instance.components.length ).toEqual( length - 1 );
});
it ( "should return the entity's component array.", () => {
expect( instance.removeComponent( "foo" ) ).toEqual( [] );
});
it( "should throw an error if no component of that type exists.", () => {
expect( () => {
instance.removeComponent( "bar" );
}).toThrowError();
});
});
describe( "Entity.setComponentData( key, data )", () => {
it( "should merge data into existing components with the given key.", () => {
const data = {
additionalProp: 7
};
instance.setComponentData( "foo", data );
const component = instance.getComponent( "foo" );
expect( Object.keys( component.data ) ).toContain( "additionalProp" );
console.log( "data:", component.data );
expect( component.data.additionalProp ).toEqual( data.additionalProp );
});
it( "should throw an error for components which are invalid/missing.", () => {
expect( () => {
instance.setComponentData( "bar", {});
}).toThrowError();
});
});
<file_sep>/dist/utils/interfaces.d.ts
import Entity from "../core/Entity";
/**
* @module utils
*/
export interface ComponentConfig {
data?: {} | [];
type?: string;
uuid?: string;
}
export interface EntityConfig {
components?: any[];
name?: string;
type?: string;
uuid?: string;
}
export interface SystemConfig {
componentTypes: string[];
fixed?: boolean;
name: string;
onAddEntity?: (entity: Entity) => void;
onInit?: () => void;
onRemoveEntity?: (entity: Entity) => void;
onUpdate: (delta: number) => void;
step?: number;
methods?: {};
}
<file_sep>/tests/integration.test.ts
import { Engine, Entity, System, State } from "../src";
let engine: Engine;
let system: System;
let entityA: Entity;
let entityB: Entity;
beforeEach( () => {
engine = new Engine();
system = new System({
componentTypes: [ "foo" ],
name: "foo-system",
onUpdate( t ) {}
});
entityA = new Entity({
components: [
{ type: "foo" }
]
});
entityB = new Entity({
components: [
{ type: "bar" }
]
});
engine.addSystem( system );
engine.addEntity( entityA );
engine.addEntity( entityB );
});
describe( "A state created from the engine", () => {
let state: State;
beforeEach( () => {
engine.start();
state = new State( engine, true );
});
it( "should have all entities added.", () => {
expect( state.entities.length ).toBe( 2 );
});
// TODO: Ensure data is copied, not referenced
it( "should have the correct timestamp.", () => {
expect( state.timestamp ).toBeGreaterThan( 0 );
});
});
describe( "A system added to the engine", () => {
it( "should automatically watch compatible entities.", () => {
expect( system.isWatchingEntity( entityA ) ).toBe( true );
});
it( "should not automatically watch incompatible entities.", () => {
expect( system.isWatchingEntity( entityB ) ).toBe( false );
});
it( "should throw an error if attempting to modify component watch list.", () => {
expect( () => {
system.watchComponentType( "bar" );
}).toThrowError();
});
});
<file_sep>/dist/index.d.ts
export { default as Component } from "./core/Component";
export { default as Engine } from "./core/Engine";
export { default as Entity } from "./core/Entity";
export { default as State } from "./core/State";
export { default as System } from "./core/System";
export { default as capitalize } from "./utils/capitalize";
export { default as copy } from "./utils/copy";
export { default as getItem } from "./utils/getItem";
export { default as hasItem } from "./utils/hasItem";
<file_sep>/src/utils/interfaces.ts
// Aurora is distributed under the MIT license.
import Entity from "../core/Entity"; // Typing
/**
* @module utils
*/
export interface ComponentConfig {
data?: {}|[];
type?: string;
uuid?: string;
}
export interface EntityConfig {
components?: any[];
name?: string,
type?: string,
uuid?: string,
}
export interface SystemConfig {
componentTypes: string[]
fixed?: boolean,
name: string,
onAddEntity?: ( entity: Entity ) => void,
onInit?: () => void,
onRemoveEntity?: ( entity: Entity ) => void,
onUpdate: ( delta: number ) => void,
step?: number,
methods?: {}
}
<file_sep>/dist/core/System.d.ts
import Engine from "./Engine";
import Entity from "./Entity";
import { SystemConfig } from "../utils/interfaces";
/**
* @module core
* @classdesc Class representing a system.
*/
export default class System {
private _accumulator;
private _componentTypes;
private _engine;
private _entityUUIDs;
private _fixed;
private _frozen;
private _methods;
private _name;
private _onAddEntity;
private _onInit;
private _onRemoveEntity;
private _onUpdate;
private _step;
/**
* @description Create a System.
* @param {Object} config - Configuration object
* @param {string} config.name - System name
* @param {boolean} config.fixed - Fixed step size or update as often as possible
* @param {number} config.step - Step size in milliseconds (only used if `fixed` is `false`)
* @param {array} config.componentTypes - Types to watch
* @param {Function} config.onInit - Function to run when first connecting the system to the
* engine
* @param {Function} config.onAddEntity - Function to run on an entity when adding it to the
* system's watchlist
* @param {Function} config.onRemoveEntity - Function to run on an entity when removing it from
* the system's watchlist
* @param {Function} config.onUpdate - Function to run each time the engine updates the main loop
*/
constructor(config: SystemConfig);
/**
* @description Get the accumulated time of the system.
* @readonly
* @returns {number} - Time in milliseconds
*/
readonly accumulator: number;
/**
* @description Get whether or not the system uses a fixed step.
* @readonly
* @returns {boolean} - True if the system uses a fixed step
*/
readonly fixed: boolean;
/**
* @description Get the step size of the system in milliseconds.
* @readonly
* @returns {number} - Time in milliseconds
*/
readonly step: number;
/**
* @description Get the entity's name.
* @readonly
* @returns {string} - Name string
*/
readonly name: string;
/**
* @description Get all of the component types the system is watching.
* @readonly
* @returns {string[]} - Array of component types
*/
readonly watchedComponentTypes: string[];
/**
* @description Get all of the entity UUIDs the system is watching.
* @readonly
* @returns {string[]} - Array of UUID strings
*/
readonly watchedEntityUUIDs: string[];
/**
* @description Add an extra method to the system. Cannot be modified after the system is
* registered with the engine.
* @param {string} key - Method identifier
* @param {function} fn - Method to be called by user in the future
*/
addMethod(key: string, fn: Function): void;
/**
* @description Check if the system can watch a given entity.
* @readonly
* @param {Entity} entity - Entity to check
* @returns {boolean} - True if the given entity is watchable
*/
canWatch(entity: Entity): boolean;
/**
* @description Call a user-added method from outside the system. Cannot be modified after the
* system is registered with the engine.
* @param {string} key - Method identifier
* @param {any} payload - Any data which should be passed to the method
* @returns {any} - Any data which the method returns
*/
dispatch(key: string, payload?: any): any;
/**
* @description Initialize the system (as a part of linking to the engine). After linking the
* engine, the system will run its stored init hook method. Cannot be modified after the system is
* registered with the engine.
* @param {Engine} engine - Engine instance to link to
*/
init(engine: Engine): void;
/**
* @description Check if the system is watching a given component type.
* @readonly
* @param {Entity} entity - Component type to check
* @returns {boolean} - True if the given component type is being watched
*/
isWatchingComponentType(componentType: string): boolean;
/**
* @description Check if the system is watching a given entity.
* @readonly
* @param {Entity} entity - Entity instance to check
* @returns {boolean} - True if the given entity instance is being watched
*/
isWatchingEntity(entity: Entity): boolean;
/**
* @description Remove a user-added method from the system. Cannot be modified after the system is
* registered with the
* engine.
* @param {string} key - Method identifier
*/
removeMethod(key: string): void;
/**
* @description Remove a component type to the system's watch list. Cannot be modified after the
* system is registered
* with the engine.
* @param {string} componentType - Component type to stop watching
* @returns {array} - Array of watched component types
*/
unwatchComponentType(componentType: string): string[];
/**
* @description Remove an entity UUID to the system's watch list.
* @param {Entity} entity - Entity instance to stop watching
* @returns {array} - Array of watched entity UUIDs
*/
unwatchEntity(entity: Entity): string[];
/**
* @description Update the system with a given amount of time to simulate. The system will run its
* stored update function using either a fixed step or variable step (specified at creation) and
* the supplied delta time. Cannot be modified after the system is registered with the engine.
* @param {number} delta - Time in milliseconds to simulate
*/
update(delta: number): void;
/**
* @description Add a single component type to the system's watch list. Cannot be modified after
* the system is registered with the engine.
* @param {string} componentType - Component type to watch
* @returns {array} - Array of watched component types
*/
watchComponentType(componentType: string): string[];
/**
* @description Watch an entity by adding its UUID to to the system. After adding, the system will
* run the entity through the internal add function to do any additional processing.
* @param {Entity} entity - Entity instance to watch
* @returns {array} - Array of watched entity UUIDs
*/
watchEntity(entity: Entity): string[];
}
<file_sep>/dist/utils/hasItem.d.ts
/**
* @module utils
*/
export default function hasItem(target: any, array: any, prop: any): boolean;
<file_sep>/dist/core/Entity.d.ts
import Component from "./Component";
import System from "./System";
import { EntityConfig } from "../utils/interfaces";
/**
* @module core
* @classdesc Class representing an entity.
*/
export default class Entity {
private _components;
private _destroy;
private _dirty;
private _name;
private _type;
private _uuid;
/**
* @description Create an entity. An object can be used when loading a previously created entity
* from disk, or creating an entity to be used as an assembly to clone into new entity instances.
* @param {Object} [config] - Configuration object
* @param {string} [config.uuid] - Entity UUID
* @param {string} [config.type] - Entity type
* @param {string} [config.name] - Entity name (typically also called "unit type" in-game)
* @param {Array} [config.components] - Array of component data objects to generate component
* instances from
*/
constructor(config?: EntityConfig);
/**
* @description Get all of the entity's component instances.
* @readonly
* @returns {Component[]} - Array of component instances
*/
readonly components: Component[];
/**
* @description Get all of the entity's component types.
* @readonly
* @returns {string[]} - Array of component types
*/
readonly componentTypes: string[];
dirty: boolean;
destroy: boolean;
/**
* @description Get the entity's data as a pure object (as compared to a class instance).
* @readonly
* @returns {Object} - Entity data as an object
*/
readonly flattened: any;
/**
* @description Get the entity's data as a JSON string.
* @readonly
* @returns {string} - JSON string
*/
readonly json: string;
/**
* @description Get the entity's name.
* @readonly
* @returns {string} - Name string
*/
readonly name: string;
/**
* @description Get the entity's type.
* @readonly
* @returns {string} - Type string
*/
readonly type: string;
/**
* @description Get the entity's UUID.
* @readonly
* @returns {string} - UUID string
*/
readonly uuid: string;
/**
* @description Add a component instance to the entity. This method should only be called
* internally, and never after the entity has been registered.
* @private
* @param {Component} component - The component to add
* @returns {Component[]} - Updated array of components, or null if the component already existed
*/
addComponent(component: Component): Component[];
/**
* @description Clone the entity.
* @returns {Entity} - New Entity instance
*/
clone(): Entity;
/**
* @description Copy another entity (such as an assembly) into the entity, replacing all
* components.
* @param {Entity} source - Entity to copy
*/
copy(source: any): void;
/**
* @description Get a component instance by type from the entity.
* @readonly
* @param {string} type - Component type
* @returns {Component} - Requested component instance
*/
getComponent(type: string): Component;
/**
* @description Get data by component type from the entity. This is basically a shorthand for
* .getComponent.getData();
* @readonly
* @param {string} type - Component type
* @returns {any} - Requested component data
*/
getComponentData(type: string): any;
/**
* @description Check if a component is present within the entity.
* @readonly
* @param {string} type - Component type
* @returns {boolean} - True if the component is present
*/
hasComponent(type: string): boolean;
/**
* @description Check if the entity is watchable by a given system.
* @readonly
* @param {System} system - System instance
* @returns {boolean} - True if the entity is watchable
*/
isWatchableBy(system: System): boolean;
/**
* @description Remove a component instance from the entity. This method should only be called
* internally, and never after the entity has been registered.
* @private
* @param {string} type - Component type
* @returns {Component[]} - Array of component instances
*/
removeComponent(type: string): Component[];
/**
* @description Overwrite the data for a component of the given type within the entity.
* @param {string} type - Component type
* @param {Object} data - Data object
*/
setComponentData(type: string, data: {}): void;
}
<file_sep>/CHANGELOG.md
# Changelog
## 2.2.0
- **ADDED:** Use `Entity.dirty` to keep track of entities which have had their component data changed. `Entity.setComponentData()` will automatically set that entity as dirty, while `Engine.cleanEntities()` will set all entities as no longer dirty. When you call that is up to you.
- **ADDED:** Use `Entity.flattened` to get an entity and all of its components as a pure object (vs. class instance). This property is now used internally by `Entity.json` as well.
- **ADDED:** In addition to specifying component type strings to define which components must be present on an entity to be watchable by a system, it is now possible to supply objects to define sets of components which are valid. See the documentation for details.
## 2.1.3
- **FIXED:** In system methods, `this` is now bound to the system instead of the method. This allows the methods to use system properties such as `this.entityUUIDs`.
## 2.1.2
- Patched security vulnerability by updating `merge` to version `1.2.1`.
## 2.1.1
- Patched security vulnerability by removing `parcel-bundler` from dependencies.
- **FIXED:** `eslint --fix` now actually runs on files (it did not previously).
## 2.1.0
- Total overhaul of Aurora with two major focuses:
- Use TypeScript.
- Be more of a framework and less of a boilerplate.
<file_sep>/dist/utils/copy.d.ts
/**
* @module utils
*/
export default function copy(obj: any): any;
<file_sep>/dist/core/Component.d.ts
import { ComponentConfig } from "../utils/interfaces";
/**
* @module core
* @classdesc Class representing a component.
*/
export default class Component {
private _data;
private _type;
private _uuid;
/**
* @description Create a Component.
* @param {Object} [config] - Configuration object
* @param {string} [config.uuid] - Component UUID
* @param {string} [config.type] - Component type
* @param {Object} [config.data] - Object containing data for the component
*/
constructor(config?: ComponentConfig);
/**
* @description Get the component's data.
* @readonly
* @returns {Object} - The component's data
*/
/**
* @description Set the component's data. Note: This method differs from `.mergeData()` in that it
* completely overwrites any existing data within the component.
* @param {Object} data - Data object to apply
* @returns {Object} - The component's updated updated data object
*/
data: any;
/**
* @description Get the component's data as a JSON string.
* @readonly
* @returns {string} - The component's data as a JSON string
*/
readonly json: string;
/**
* @description Get the component's type.
* @readonly
* @returns {string} - The component's type
*/
/**
* @description Set the component's type.
* @param {string} type - New type for the component
*/
type: string;
/**
* @description Get the component's UUID.
* @readonly
* @returns {String} - The component's UUID
*/
readonly uuid: string;
/**
* @description Clone the component.
* @returns {Component} - New component instance with the same data
*/
clone(): Component;
/**
* @description Copy another component's data, resetting existing data.
* @param {Component} source - Component to copy from
*/
copy(source: Component): void;
/**
* @description Merge a data object into this component.
* @param {Object} data - JSON data to apply to the component
* @returns {(Object|Array)} - Updated data object/array
*/
mergeData(data: any): any;
}
<file_sep>/tests/core/Engine.test.ts
import { Engine, Entity, System } from "../../src";
let instance: Engine;
beforeEach( () => {
instance = new Engine();
});
// Constructor
describe( "Engine.constructor()", () => {
it( "should create an empty assemblies array.", () => {
expect( instance.assemblies ).toBeDefined();
expect( Array.isArray( instance.assemblies ) ).toBe( true );
expect( instance.assemblies.length ).toBe( 0 );
});
it( "should create an empty entities array.", () => {
expect( instance.entities ).toBeDefined();
expect( Array.isArray( instance.entities ) ).toBe( true );
expect( instance.entities.length ).toBe( 0 );
});
it( "should create an empty systems array.", () => {
expect( instance.systems ).toBeDefined();
expect( Array.isArray( instance.systems ) ).toBe( true );
expect( instance.systems.length ).toBe( 0 );
});
it( "should set last tick time as null.", () => {
expect( instance.lastTickTime ).toBeDefined();
expect( instance.lastTickTime ).toBe( null );
});
it( "should not have an .onUpdateStart() handler.", () => {
expect( instance.onTickStart ).not.toBeDefined();
});
it( "should not have an .onUpdateComplete() handler.", () => {
expect( instance.onTickComplete ).not.toBeDefined();
});
});
// Adders
describe( "Engine.addAssembly( type )", () => {
let assembly: Entity;
beforeEach( () => {
assembly = new Entity({
type: "foo"
});
instance.addAssembly( assembly );
});
it( "should add the assembly to the engine.", () => {
expect( instance.assemblies.length ).toBe( 1 );
});
it( "should throw an error if adding a duplicate assembly.", () => {
expect( () => {
instance.addAssembly( assembly );
}).toThrowError();
});
});
describe( "Engine.addEntity( entity )", () => {
let entity: Entity;
beforeEach( () => {
entity = new Entity();
instance.addEntity( entity );
});
it( "should add the entity to the engine.", () => {
expect( instance.entities.length ).toBe( 1 );
});
it( "should throw an error if adding a duplicate entity.", () => {
expect( () => {
instance.addEntity( entity );
}).toThrowError();
});
});
describe( "Engine.addSystem( system )", () => {
let system: System;
beforeEach( () => {
system = new System({
name: "foo",
componentTypes: [ "bar" ],
onUpdate: function() {}
});
instance.addSystem( system );
});
it( "should add the system to the engine.", () => {
expect( instance.systems.length ).toBe( 1 );
});
it( "should throw an error if adding a duplicate system.", () => {
expect( () => {
instance.addSystem( system );
}).toThrowError();
});
});
// Getters
describe( "Engine.getAssembly( type )", () => {
it( "should retrive the correct assembly instance by type.", () => {
const assembly = new Entity();
instance.addAssembly( assembly );
expect( instance.getAssembly( assembly.type ) ).toBe( assembly );
});
it( "should throw an error for invalid/missing types.", () => {
expect( () => {
instance.getAssembly( "bar" );
}).toThrowError();
});
});
describe( "Engine.getEntity( entity )", () => {
it( "should retrive the correct entity instance by its UUID.", () => {
const entity = new Entity();
instance.addEntity( entity );
expect( instance.getEntity( entity.uuid ) ).toBe( entity );
});
it( "should throw an error for invalid/missing UUIDs.", () => {
expect( () => {
instance.getEntity( "bar" );
}).toThrowError();
});
});
describe( "Engine.getSystem( name )", () => {
it( "should retrive the correct system instance by name.", () => {
const system = new System({
name: "foo",
componentTypes: [ "bar" ],
onUpdate: function() {}
});
instance.addSystem( system );
expect( instance.getSystem( system.name ) ).toBe( system );
});
it( "should throw an error for invalid/missing names.", () => {
expect( () => {
instance.getSystem( "bar" );
}).toThrowError();
});
});
// Checkers
describe( "Engine.hasAssembly( type )", () => {
it( "should identify if an assembly has been added or not.", () => {
const assembly = new Entity({
type: "foo"
});
instance.addAssembly( assembly );
expect( instance.hasAssembly( assembly.type ) ).toBe( true );
expect( instance.hasAssembly( "bar" ) ).toBe( false );
});
});
describe( "Engine.hasEntity( uuid )", () => {
it( "should identify if an entity has been added or not.", () => {
const entity = new Entity();
instance.addEntity( entity );
expect( instance.hasEntity( entity.uuid ) ).toBe( true );
expect( instance.hasEntity( "bar" ) ).toBe( false );
});
});
describe( "Engine.hasSystem( name )", () => {
it( "should identify if a system has been added or not.", () => {
const system = new System({
name: "foo",
componentTypes: [ "foo" ],
onUpdate: function() {}
});
instance.addSystem( system );
expect( instance.hasSystem( system.name ) ).toBe( true );
expect( instance.hasSystem( "bar" ) ).toBe( false );
});
});
// Other
describe( "Engine.start()", () => {
let tickSpy;
beforeEach( () => {
tickSpy = jest.spyOn( Engine.prototype, "tick" );
});
it( ".should set the engine as running and trigger .tick().", () => {
instance.start();
expect( instance.running ).toBe( true );
});
it( "should only call .tick() once when no callback exists.", () => {
expect( instance.onTickComplete ).not.toBeDefined();
instance.start();
expect( tickSpy ).toHaveBeenCalledTimes( 1 );
});
afterEach( () => {
tickSpy.mockClear();
});
});
describe( "Engine.stop()", () => {
it( "should set the engine as not running.", () => {
instance.stop();
expect( instance.running ).toBe( false );
});
});
describe( "Engine.tick()", () => {
let handler;
beforeEach( () => {
handler = jest.fn();
});
it( "should call .onTickStart() if it's defined.", () => {
instance.onTickStart = handler;
instance.start();
expect( instance.onTickStart ).toHaveBeenCalledTimes( 1 );
});
it( "should call .onTickComplete() if it's defined.", () => {
instance.onTickComplete = handler;
instance.start();
expect( instance.onTickComplete ).toHaveBeenCalledTimes( 1 );
});
});
<file_sep>/dist/utils/capitalize.d.ts
/**
* @module utils
*/
export default function capitalize(str: any): any;
<file_sep>/tests/core/System.test.ts
import { Engine, Entity, System } from "../../src";
let instance: System;
let entityA: Entity;
let entityB: Entity;
const mockMethod = jest.fn();
const mockOnInit = jest.fn();
mockOnInit.mockReturnValue( true );
mockMethod.mockReturnValue( true );
const config = {
name: "foo-system",
step: 100,
componentTypes: [ "foo", "bar" ],
fixed: true,
onUpdate( delta: number ) {},
onInit: mockOnInit,
methods: {
"foo": mockMethod
}
};
beforeEach( () => {
instance = new System( config );
entityA = new Entity({
components: [
{ type: "foo" },
{ type: "bar" }
]
});
entityB = new Entity({
components: [
{ type: "foo" }
]
});
});
// Constructor
describe( "System.constructor( config )", () => {
it( "should set name from the config.", () => {
expect( instance.name ).toBe( config.name );
});
it( "should set step size from the config.", () => {
expect( instance.step ).toBe( config.step );
});
it ( "should set fixed step from config.", () => {
expect( instance.fixed ).toBe( config.fixed );
});
it( "should watch the config's component list.", () => {
expect( instance.isWatchingComponentType( "foo" ) ).toBe( true );
expect( instance.isWatchingComponentType( "bar" ) ).toBe( true );
});
it( "should have at least one watched component type.", () => {
expect( instance.watchedComponentTypes.length ).toBeGreaterThan( 0 );
});
});
// Other
describe( "System.canWatch( entity )", () => {
it( "should return true if all system component types are present.", () => {
expect( instance.canWatch( entityA ) ).toBe( true );
});
it ( "should return false if any system component types are missing.", () => {
expect( instance.canWatch( entityB ) ).toBe( false );
});
});
describe( "System.dispatch( key )", () => {
it( "should call the the user-defined method once.", () => {
instance.dispatch( "foo" );
expect( mockMethod.mock.calls.length ).toBe( 1 );
});
});
describe( "System.init()", () => {
// TODO: Test if it doesn't exist
it( "should call its ._onInit handler function if it exists.", () => {
instance.init( new Engine() );
expect( mockOnInit.mock.calls.length ).toBe( 1 );
});
});
describe( "System.isWatchingComponentType( type )", () => {
it( "should identify if an assembly has been added or not.", () => {
expect( instance.isWatchingComponentType( "foo" ) ).toBe( true );
expect( instance.isWatchingComponentType( "not-present" ) ).toBe( false );
});
});
describe( "System.removeMethod( key )", () => {
it( "should remove the method with the given key if it exists.", () => {
instance.removeMethod( "foo" );
expect( () => {
instance.dispatch( "foo", {});
}).toThrowError();
});
it( "should throw an error if no method for that key exists.", () => {
expect( () => {
instance.removeMethod( "bar" );
}).toThrowError();
});
});
describe( "System.unwatchComponentType( type )", () => {
it( "should remove the component type if it exists.", () => {
const originalLength = instance.watchedComponentTypes.length;
expect( () => {
instance.unwatchComponentType( "foo" );
}).not.toThrowError();
expect( instance.watchedComponentTypes.length ).toBe( originalLength - 1 );
});
it( "should throw an error if less than one type is left.", () => {
instance.unwatchComponentType( "foo" );
expect( () => {
instance.unwatchComponentType( "bar" );
}).toThrowError();
});
it( "should throw an error if that component type does not exist.", () => {
expect( () => {
instance.unwatchComponentType( "not-present" );
}).toThrow();
});
});
describe( "System.unwatchEntity", () => {
it( "should removable the entity with the given UUID.", () => {
instance.watchEntity( entityA );
const originalLength = instance.watchedEntityUUIDs.length;
expect( () => {
instance.unwatchEntity( entityA );
}).not.toThrowError();
expect( instance.watchedEntityUUIDs.length ).toBe( originalLength - 1 );
});
it( "should throw an error if that entity is not being watched.", () => {
expect( () => {
instance.unwatchEntity( new Entity() );
}).toThrowError();
});
});
describe( "System.update()", () => {
it( "should save left over time in the accumulator.", () => {
instance.update( 105 );
expect( instance.accumulator ).toBe( 5 );
});
});
describe( "System.watchComponentType( type )", () => {
it( "should watch the component type.", () => {
instance.watchComponentType( "new-type" );
expect( instance.watchedComponentTypes ).toContain( "new-type" );
});
it( "should throw an error if watching a duplicate type.", () => {
expect( () => {
instance.watchComponentType( "foo" );
}).toThrowError();
});
});
describe( "System.watchEntity( entity )", () => {
let entity: Entity;
beforeEach( () => {
entity = new Entity();
});
it( "should watch the entity.", () => {
const originalLength = instance.watchedEntityUUIDs.length;
instance.watchEntity( entity );
expect( instance.watchedEntityUUIDs ).toContain( entity.uuid );
});
it( "should throw an error if watching a duplicate type.", () => {
instance.watchEntity( entity );
expect( () => {
instance.watchEntity( entity );
}).toThrowError();
});
});
<file_sep>/src/core/State.ts
// Aurora is distributed under the MIT license.
import Engine from "./Engine"; // Typing
import Entity from "./Entity"; // Typing
/**
* @module core
* @classdesc Class representing a state.
*/
export default class State {
private _timestamp: number;
private _entities: any[];
/**
* @description Create a state instance from an engine.
* @param {Engine} engine - Engine instance
*/
constructor( engine: Engine, complete: boolean = false ) {
this._timestamp = engine.lastTickTime;
this._entities = [];
engine.entities.forEach( ( entity ) => {
// If not performing a full state capture and the entity is not dirty, skip it
if ( !complete && !entity.dirty ) {
return;
}
// Otherwise, flatten it to a JSON object and push it to the array
this._entities.push( entity.flattened );
});
return this;
}
get flattened(): Object {
return {
timestamp: this._timestamp,
entities: this._entities
};
}
/**
* @description Get the state's entities.
* @readonly
* @returns {Entity[]} - Array of entity instances
*/
get entities(): Entity[] {
return this._entities;
}
/**
* @description Get the state's timestamp in milliseconds.
* @readonly
* @returns {number} - Timestamp in milliseconds
*/
get timestamp(): number {
return this._timestamp;
}
get json(): string {
return JSON.stringify( this.flattened, null, 4 );
}
}
<file_sep>/tests/utils/capitalize.test.ts
import { capitalize } from "../../src";
describe( "capitalize", () => {
const str = "interloper";
it( "should capitalize the first character of the string.", () => {
expect( capitalize( str ) ).toEqual( "Interloper" );
});
it( "should return a new string.", () => {
expect( capitalize( str ) ).not.toBe( str );
});
});
<file_sep>/dist/core/State.d.ts
import Engine from "./Engine";
import Entity from "./Entity";
/**
* @module core
* @classdesc Class representing a state.
*/
export default class State {
private _timestamp;
private _entities;
/**
* @description Create a state instance from an engine.
* @param {Engine} engine - Engine instance
*/
constructor(engine: Engine, complete?: boolean);
readonly flattened: Object;
/**
* @description Get the state's entities.
* @readonly
* @returns {Entity[]} - Array of entity instances
*/
readonly entities: Entity[];
/**
* @description Get the state's timestamp in milliseconds.
* @readonly
* @returns {number} - Timestamp in milliseconds
*/
readonly timestamp: number;
readonly json: string;
}
<file_sep>/src/core/Engine.ts
// Aurora is distributed under the MIT license.
import present from "present";
import Entity from "./Entity";
import System from "./System";
import getItem from "../utils/getItem";
import hasItem from "../utils/hasItem";
/**
* @module core
* @classdesc Core singleton representing an instance of the Aurora engine. The engine is
* responsible for the creation and registration of entities, as well as initialization and running
* of systems containing game logic.
*/
export default class Engine {
private _assemblies: Entity[];
private _entities: Entity[];
private _lastTickTime: number;
private _onTickComplete: Function; // Hook called when update is complete
private _onTickStart: Function; // Hook called when update starts
private _running: boolean; // Whether or not the engine is running
private _systems: System[];
/**
* @description Create an instance of the Aurora engine.
*/
constructor() {
// TODO: Build from JSON in the case of loading a save
console.log( "Aurora: Initializing a new engine." );
// These are the things which are actually saved per game
this._assemblies = [];
this._entities = [];
this._systems = [];
// The heart of the engine
this._running = false;
this._lastTickTime = null;
this._onTickStart = undefined;
this._onTickComplete = undefined;
return this;
}
/**
* @description Get all of the engine's assemblies.
* @readonly
* @returns {Entity[]} - Array of assembly (entity) instances
*/
get assemblies(): Entity[] {
return this._assemblies;
}
/**
* @description Get all of the engine's entities.
* @readonly
* @returns {Entity[]} - Array of entity instances
*/
get entities(): Entity[] {
return this._entities;
}
/**
* @description Get the function currently set to execute after every tick.
* @readonly
* @returns {Function} - Function currently set to execute
*/
get onTickComplete(): Function {
return this._onTickComplete;
}
/**
* @description Get the function currently set to execute before every tick.
* @readonly
* @returns {Function} - Function currently set to execute
*/
get onTickStart(): Function {
return this._onTickStart;
}
/**
* @description Get whether or not the engine is currently running.
* @readonly
* @returns {boolean} - True if the engine is running
*/
get running(): boolean {
return this._running;
}
/**
* @description Get all of the engine's systems.
* @readonly
* @returns {System[]} - Array of system instances
*/
get systems(): System[] {
return this._systems;
}
/**
* @description Get the timestamp of the engine's last tick.
* @readonly
* @returns {number} - Timestamp in milliseconds
*/
get lastTickTime() {
return this._lastTickTime;
}
/**
* @description Set a function to execute after every update tick.
* @param {Function} fn - Function to execute
*/
set onTickComplete( fn: Function ) {
this._onTickComplete = fn;
}
/**
* @description Set a function to execute before every update tick.
* @param {Function} fn - Function to execute
*/
set onTickStart( fn: Function ) {
this._onTickStart = fn;
}
/**
* @description Add an assembly (entity) instance to the engine.
* @param {Entity} assembly - Assembly instance
* @returns {Entity[]} - Array of assembly (entity) instances
*/
addAssembly( assembly: Entity ): Entity[] {
// Validate
if ( this.hasAssembly( assembly.type ) ) {
throw Error( "Assembly of that type has already been added!" );
}
// Freeze entity's structure
Object.seal( assembly );
this._assemblies.push( assembly );
return this._assemblies;
}
/**
* @description Add an entity instance to the engine. This will check which systems should watch
* it, and add it to those systems (running the entity through each system's onAdd hook. After
* being added and initialized, entities are immutable (although their component data is not).
* @param {Entity} entity - Entity instance
* @returns {Entity[]} - Array of entity instances
*/
addEntity( entity: Entity ): Entity[] {
// Validate
if ( this.hasEntity( entity.uuid ) ) {
throw Error( "Entity with that UUID has already been added!" );
}
// Freeze entity's structure
Object.seal( entity );
this._entities.push( entity );
// Check all systems to see if they should be watching this entity
this._systems.forEach( ( system ) => {
if ( entity.isWatchableBy( system ) ) {
system.watchEntity( entity );
}
});
return this._entities;
}
/**
* @description Add a system instance to the engine.
*
* This will run the system's onInit hook. After being added and initialized, systems are
* immutable and are updated every game tick.
* @param {System} system - System instance
* @returns {System[]} - Array of system instances
*/
addSystem( system: System ): System[] {
// Validate
if ( this.hasSystem( system.name ) ) {
throw Error( "System with that name has already been added!" );
}
// Add it and start it
this._systems.push( system );
system.init( this );
// Freeze entity's structure
Object.freeze( system );
return this._systems;
}
/**
* @description Get an assembly (entity) instance by type from the engine.
* @readonly
* @param {string} type - Assembly type
* @returns {Entity} - Requested assembly (entity) instance
*/
getAssembly( type: string ): Entity {
if ( !this.hasAssembly( type ) ) {
throw Error( "No assembly of that type found!" );
}
return getItem( type, this._assemblies, "type" );
}
/**
* @description Get an entity instance by UUID from the engine.
* @readonly
* @param {string} uuid - Entity UUID
* @returns {Entity} - Requested entity instance
*/
getEntity( uuid: string ): Entity {
if ( !this.hasEntity( uuid ) ) {
throw Error( "No enitity with that UUID found!" );
}
return getItem( uuid, this._entities, "uuid" );
}
/**
* @description Get a system instance by name from the engine.
* @readonly
* @param {string} name - System name
* @returns {System} - Requested system instance
*/
getSystem( name: string ): System {
if ( !this.hasSystem( name ) ) {
throw Error( "No system with that name found!" );
}
return getItem( name, this._systems, "name" );
}
/**
* @description Check if an assembly is present within the engine.
* @readonly
* @param {string} name - Assembly name
* @returns {boolean} - True if the assembly is present
*/
hasAssembly( type: string ): boolean {
return hasItem( type, this._assemblies, "type" );
}
/**
* @description Check if a system is present within the engine.
* @readonly
* @param {string} name - System name
* @returns {boolean} - True if the entity is present
*/
hasEntity( uuid: string ): boolean {
return hasItem( uuid, this._entities, "uuid" );
}
/**
* @description Check if a system is present within the engine.
* @readonly
* @param {string} name - System name
* @returns {boolean} - True if the system is present
*/
hasSystem( name: string ): boolean {
return hasItem( name, this._systems, "name" );
}
/**
* @description Start the execution of the update loop.
*/
start(): void {
// Always reset in case engine was stopped and restarted
this._lastTickTime = present();
// Start ticking!
this._running = true;
this.tick();
}
/**
* @description Stop the execution of the update loop.
*/
stop(): void {
this._running = false;
}
/**
* @description Perform one tick and update all systems.
*
* It is up to the user to decide how often to call this function. Typically on the client-side
* this would be called in requestAnimationFrame() and on the server-side this would simply be
* tied to a very fast setInterval() function (perhaps 10 ms).
*/
tick(): void {
if ( this._running ) {
const now = present();
const delta = now - this._lastTickTime;
this._lastTickTime = now;
// Run any pre-update behavior
if ( this._onTickStart ) {
this._onTickStart();
}
// Perform the update on every system
this._systems.forEach( ( system ) => {
system.update( delta );
});
// Run any post-update behavior
if ( this._onTickComplete ) {
this._onTickComplete();
}
}
}
/**
* @description Set all entities to "clean".
*
* When this function is invoked is up to the developer. In some cases it makes sense to invoke it
* at the beginning of each tick, in other cases after all entities are sent from a server to the
* clients (for example).
*/
cleanEntities() {
this._entities.forEach( ( entity ) => {
entity.dirty = false;
});
}
}
<file_sep>/src/core/System.ts
// Aurora is distributed under the MIT license.
import Engine from "./Engine"; // Typing
import Entity from "./Entity"; // Typing
import { SystemConfig } from "../utils/interfaces"; // Typing
/**
* @module core
* @classdesc Class representing a system.
*/
export default class System {
private _accumulator: number;
private _componentTypes: string[];
private _engine: Engine;
private _entityUUIDs: string[];
private _fixed: boolean;
private _frozen: boolean;
private _methods: {};
private _name: string;
private _onAddEntity: ( entity: Entity ) => void;
private _onInit: () => void;
private _onRemoveEntity: ( entity: Entity ) => void;
private _onUpdate: ( delta: number ) => void;
private _step: number;
/**
* @description Create a System.
* @param {Object} config - Configuration object
* @param {string} config.name - System name
* @param {boolean} config.fixed - Fixed step size or update as often as possible
* @param {number} config.step - Step size in milliseconds (only used if `fixed` is `false`)
* @param {array} config.componentTypes - Types to watch
* @param {Function} config.onInit - Function to run when first connecting the system to the
* engine
* @param {Function} config.onAddEntity - Function to run on an entity when adding it to the
* system's watchlist
* @param {Function} config.onRemoveEntity - Function to run on an entity when removing it from
* the system's watchlist
* @param {Function} config.onUpdate - Function to run each time the engine updates the main loop
*/
constructor( config: SystemConfig ) {
// Define defaults
this._accumulator = 0;
this._componentTypes = [];
this._engine = undefined;
this._entityUUIDs = [];
this._fixed = false;
this._frozen = false;
this._methods = {};
this._name = "no-name";
this._onAddEntity = ( entity: Entity ) => {};
this._onInit = () => {};
this._onRemoveEntity = ( entity: Entity ) => {};
this._onUpdate = ( delta: number ) => {};
this._step = 100;
// Apply config values
Object.keys( config ).forEach( ( key ) => {
// Handle component types and methods slightly differently, otherwise simply overwite props
// with config values
const specialCases = [ "componentTypes", "methods", "entityUUIDs" ];
// If not a special case
if ( specialCases.indexOf( key ) > -1 ) {
switch( key ) {
case "methods":
Object.keys( config.methods ).forEach( ( key ) => {
this.addMethod( key, config.methods[ key ] );
});
break;
case "componentTypes":
Object.keys( config.componentTypes ).forEach( ( key ) => {
this.watchComponentType( config.componentTypes[ key ] );
});
break;
}
} else {
this[ "_" + key ] = config[ key ];
}
});
}
/**
* @description Get the accumulated time of the system.
* @readonly
* @returns {number} - Time in milliseconds
*/
get accumulator(): number {
return this._accumulator;
}
/**
* @description Get whether or not the system uses a fixed step.
* @readonly
* @returns {boolean} - True if the system uses a fixed step
*/
get fixed(): boolean {
return this._fixed;
}
/**
* @description Get the step size of the system in milliseconds.
* @readonly
* @returns {number} - Time in milliseconds
*/
get step(): number {
return this._step;
}
/**
* @description Get the entity's name.
* @readonly
* @returns {string} - Name string
*/
get name(): string {
return this._name;
}
/**
* @description Get all of the component types the system is watching.
* @readonly
* @returns {string[]} - Array of component types
*/
get watchedComponentTypes(): string[] {
return this._componentTypes;
}
/**
* @description Get all of the entity UUIDs the system is watching.
* @readonly
* @returns {string[]} - Array of UUID strings
*/
get watchedEntityUUIDs(): string[] {
return this._entityUUIDs;
}
/**
* @description Add an extra method to the system. Cannot be modified after the system is
* registered with the engine.
* @param {string} key - Method identifier
* @param {function} fn - Method to be called by user in the future
*/
addMethod( key: string, fn: Function ): void {
// TODO: Error handling
this._methods[ key ] = fn.bind( this );
}
/**
* @description Check if the system can watch a given entity.
* @readonly
* @param {Entity} entity - Entity to check
* @returns {boolean} - True if the given entity is watchable
*/
canWatch( entity: Entity ): boolean {
// TODO: Error handling
// Faster to loop through search criteria vs. all components on entity
for ( const type of this._componentTypes ) {
// Return early if any required component is missing on entity
if ( !entity.hasComponent( type ) ) {
return false;
}
}
return true;
}
/**
* @description Call a user-added method from outside the system. Cannot be modified after the
* system is registered with the engine.
* @param {string} key - Method identifier
* @param {any} payload - Any data which should be passed to the method
* @returns {any} - Any data which the method returns
*/
dispatch( key: string, payload?: any ): any {
if ( !this._methods[ key ] ) {
throw Error( `Method ${ key } does not exist!` );
}
return this._methods[ key ]( payload );
}
/**
* @description Initialize the system (as a part of linking to the engine). After linking the
* engine, the system will run its stored init hook method. Cannot be modified after the system is
* registered with the engine.
* @param {Engine} engine - Engine instance to link to
*/
init( engine: Engine ): void {
console.log( "Initializing a new system: " + this._name + "." );
this._engine = engine;
// Run the actual init behavior:
if ( this._onInit ) {
this._onInit();
}
// Freeze the system to make it immutable:
this._frozen = true;
}
/**
* @description Check if the system is watching a given component type.
* @readonly
* @param {Entity} entity - Component type to check
* @returns {boolean} - True if the given component type is being watched
*/
isWatchingComponentType( componentType: string ): boolean {
if ( this._componentTypes.indexOf( componentType ) > -1 ) {
return true;
}
return false;
}
/**
* @description Check if the system is watching a given entity.
* @readonly
* @param {Entity} entity - Entity instance to check
* @returns {boolean} - True if the given entity instance is being watched
*/
isWatchingEntity( entity: Entity ): boolean {
if ( this._entityUUIDs.indexOf( entity.uuid ) > -1 ) {
return true;
}
return false;
}
/**
* @description Remove a user-added method from the system. Cannot be modified after the system is
* registered with the
* engine.
* @param {string} key - Method identifier
*/
removeMethod( key: string ): void {
if ( !this._methods[ key ] ) {
throw Error( `Method ${ key } does not exist!` );
}
delete this._methods[ key ];
}
/**
* @description Remove a component type to the system's watch list. Cannot be modified after the
* system is registered
* with the engine.
* @param {string} componentType - Component type to stop watching
* @returns {array} - Array of watched component types
*/
unwatchComponentType( componentType: string ): string[] {
const index = this._componentTypes.indexOf( componentType );
if ( this._componentTypes.length < 2 ) {
throw Error( "Cannot remove component type, this system will be left with 0." );
}
if ( index == -1 ) {
throw Error( "Component type not found on system." );
}
this._componentTypes.splice( index, 1 );
return this._componentTypes;
}
/**
* @description Remove an entity UUID to the system's watch list.
* @param {Entity} entity - Entity instance to stop watching
* @returns {array} - Array of watched entity UUIDs
*/
unwatchEntity( entity: Entity ): string[] {
const index = this._entityUUIDs.indexOf( entity.uuid );
if ( index < 0 ) {
throw Error( `Could not unwatch entity ${ entity.uuid }; not watched.` );
}
this._entityUUIDs.splice( index, 1 );
return this._entityUUIDs;
}
/**
* @description Update the system with a given amount of time to simulate. The system will run its
* stored update function using either a fixed step or variable step (specified at creation) and
* the supplied delta time. Cannot be modified after the system is registered with the engine.
* @param {number} delta - Time in milliseconds to simulate
*/
update( delta: number ): void {
if ( this._fixed ) {
// Add time to the accumulator & simulate if greater than the step size:
this._accumulator += delta;
while ( this._accumulator >= this._step ) {
this._onUpdate( this._step );
this._accumulator -= this._step;
}
} else {
this._onUpdate( delta );
}
}
/**
* @description Add a single component type to the system's watch list. Cannot be modified after
* the system is registered with the engine.
* @param {string} componentType - Component type to watch
* @returns {array} - Array of watched component types
*/
watchComponentType( componentType: string ): string[] {
// Early return if frozen; this avoids updating the entity watch list during
// execution.
if ( this._frozen ) {
throw Error( "Cannot modify watchedComponentTypes after adding to engine." );
}
// Check if this component type is already present
if ( this._componentTypes.indexOf( componentType ) > -1 ) {
throw Error( `Component type ${ componentType } is already being watched!` );
}
// If not, add it to the system
this._componentTypes.push( componentType );
return this._componentTypes;
}
/**
* @description Watch an entity by adding its UUID to to the system. After adding, the system will
* run the entity through the internal add function to do any additional processing.
* @param {Entity} entity - Entity instance to watch
* @returns {array} - Array of watched entity UUIDs
*/
watchEntity( entity: Entity ): string[] {
// Check if this entity is already being watched
if ( this._entityUUIDs.indexOf( entity.uuid ) >= 0 ) {
throw Error( `Entity ${ entity.uuid } is already being watched!` );
}
this._entityUUIDs.push( entity.uuid );
this._onAddEntity( entity );
return this._entityUUIDs;
}
}
<file_sep>/src/utils/hasItem.ts
// Aurora is distributed under the MIT license.
/**
* @module utils
*/
export default function hasItem( target, array, prop ) {
const match = array.find( ( item ) => {
return item[ prop ] === target;
});
if ( !match ) {
return false;
}
return true;
}
<file_sep>/dist/utils/getItem.d.ts
/**
* @module utils
*/
export default function getItem(target: any, array: any, prop: any): any;
<file_sep>/dist/core/Engine.d.ts
import Entity from "./Entity";
import System from "./System";
/**
* @module core
* @classdesc Core singleton representing an instance of the Aurora engine. The engine is
* responsible for the creation and registration of entities, as well as initialization and running
* of systems containing game logic.
*/
export default class Engine {
private _assemblies;
private _entities;
private _lastTickTime;
private _onTickComplete;
private _onTickStart;
private _running;
private _systems;
/**
* @description Create an instance of the Aurora engine.
*/
constructor();
/**
* @description Get all of the engine's assemblies.
* @readonly
* @returns {Entity[]} - Array of assembly (entity) instances
*/
readonly assemblies: Entity[];
/**
* @description Get all of the engine's entities.
* @readonly
* @returns {Entity[]} - Array of entity instances
*/
readonly entities: Entity[];
/**
* @description Get the function currently set to execute after every tick.
* @readonly
* @returns {Function} - Function currently set to execute
*/
/**
* @description Set a function to execute after every update tick.
* @param {Function} fn - Function to execute
*/
onTickComplete: Function;
/**
* @description Get the function currently set to execute before every tick.
* @readonly
* @returns {Function} - Function currently set to execute
*/
/**
* @description Set a function to execute before every update tick.
* @param {Function} fn - Function to execute
*/
onTickStart: Function;
/**
* @description Get whether or not the engine is currently running.
* @readonly
* @returns {boolean} - True if the engine is running
*/
readonly running: boolean;
/**
* @description Get all of the engine's systems.
* @readonly
* @returns {System[]} - Array of system instances
*/
readonly systems: System[];
/**
* @description Get the timestamp of the engine's last tick.
* @readonly
* @returns {number} - Timestamp in milliseconds
*/
readonly lastTickTime: number;
/**
* @description Add an assembly (entity) instance to the engine.
* @param {Entity} assembly - Assembly instance
* @returns {Entity[]} - Array of assembly (entity) instances
*/
addAssembly(assembly: Entity): Entity[];
/**
* @description Add an entity instance to the engine. This will check which systems should watch
* it, and add it to those systems (running the entity through each system's onAdd hook. After
* being added and initialized, entities are immutable (although their component data is not).
* @param {Entity} entity - Entity instance
* @returns {Entity[]} - Array of entity instances
*/
addEntity(entity: Entity): Entity[];
/**
* @description Add a system instance to the engine.
*
* This will run the system's onInit hook. After being added and initialized, systems are
* immutable and are updated every game tick.
* @param {System} system - System instance
* @returns {System[]} - Array of system instances
*/
addSystem(system: System): System[];
/**
* @description Get an assembly (entity) instance by type from the engine.
* @readonly
* @param {string} type - Assembly type
* @returns {Entity} - Requested assembly (entity) instance
*/
getAssembly(type: string): Entity;
/**
* @description Get an entity instance by UUID from the engine.
* @readonly
* @param {string} uuid - Entity UUID
* @returns {Entity} - Requested entity instance
*/
getEntity(uuid: string): Entity;
/**
* @description Get a system instance by name from the engine.
* @readonly
* @param {string} name - System name
* @returns {System} - Requested system instance
*/
getSystem(name: string): System;
/**
* @description Check if an assembly is present within the engine.
* @readonly
* @param {string} name - Assembly name
* @returns {boolean} - True if the assembly is present
*/
hasAssembly(type: string): boolean;
/**
* @description Check if a system is present within the engine.
* @readonly
* @param {string} name - System name
* @returns {boolean} - True if the entity is present
*/
hasEntity(uuid: string): boolean;
/**
* @description Check if a system is present within the engine.
* @readonly
* @param {string} name - System name
* @returns {boolean} - True if the system is present
*/
hasSystem(name: string): boolean;
/**
* @description Start the execution of the update loop.
*/
start(): void;
/**
* @description Stop the execution of the update loop.
*/
stop(): void;
/**
* @description Perform one tick and update all systems.
*
* It is up to the user to decide how often to call this function. Typically on the client-side
* this would be called in requestAnimationFrame() and on the server-side this would simply be
* tied to a very fast setInterval() function (perhaps 10 ms).
*/
tick(): void;
/**
* @description Set all entities to "clean".
*
* When this function is invoked is up to the developer. In some cases it makes sense to invoke it
* at the beginning of each tick, in other cases after all entities are sent from a server to the
* clients (for example).
*/
cleanEntities(): void;
}
<file_sep>/src/core/Component.ts
// Aurora is distributed under the MIT license.
import uuid from "uuid";
import copy from "../utils/copy";
import merge from "deepmerge";
import { ComponentConfig } from "../utils/interfaces"; // Typing
/**
* @module core
* @classdesc Class representing a component.
*/
export default class Component {
private _data: any;
private _type: string;
private _uuid: string;
/**
* @description Create a Component.
* @param {Object} [config] - Configuration object
* @param {string} [config.uuid] - Component UUID
* @param {string} [config.type] - Component type
* @param {Object} [config.data] - Object containing data for the component
*/
constructor( config?: ComponentConfig ) {
// Define defaults
this._uuid = uuid();
this._type = "noname";
this._data = {}; // NOTE: Some components use an array
// Apply config values
if ( config ) {
Object.keys( config ).forEach( ( key ) => {
// Handle data slightly differently, otherwise simply overwite props with config values
if ( key === "data" ) {
this._data = copy( config.data );
} else {
this[ "_" + key ] = config[ key ];
}
});
}
}
// Expose properties
/**
* @description Get the component's data.
* @readonly
* @returns {Object} - The component's data
*/
get data(): any {
return this._data;
}
/**
* @description Set the component's data. Note: This method differs from `.mergeData()` in that it
* completely overwrites any existing data within the component.
* @param {Object} data - Data object to apply
* @returns {Object} - The component's updated updated data object
*/
set data( data: any ) {
this._data = copy( data );
}
/**
* @description Get the component's data as a JSON string.
* @readonly
* @returns {string} - The component's data as a JSON string
*/
get json() {
return JSON.stringify({
data: this._data,
type: this._type,
uuid: this._uuid
}, null, 4 );
}
/**
* @description Get the component's type.
* @readonly
* @returns {string} - The component's type
*/
get type(): string {
return this._type;
}
/**
* @description Set the component's type.
* @param {string} type - New type for the component
*/
set type( type: string ) {
this._type = type;
}
/**
* @description Get the component's UUID.
* @readonly
* @returns {String} - The component's UUID
*/
get uuid(): string {
return this._uuid;
}
// Where is the set uuid() method? Doesn't exist! Don't change the UUID!
// Other
/**
* @description Clone the component.
* @returns {Component} - New component instance with the same data
*/
clone(): Component {
const clone = new Component();
clone.copy( this );
return clone;
}
/**
* @description Copy another component's data, resetting existing data.
* @param {Component} source - Component to copy from
*/
copy( source: Component ): void {
// Don't copy the UUID, only the type and data
this._type = source.type;
this._data = copy( source.data );
}
/**
* @description Merge a data object into this component.
* @param {Object} data - JSON data to apply to the component
* @returns {(Object|Array)} - Updated data object/array
*/
mergeData( data: any ): any {
this._data = merge( this._data, data );
return this._data;
}
}
<file_sep>/README.md
<p>
<img src="https://github.com/ianpaschal/aurora/blob/develop/logo.svg" />
</p>
<p>
<a href="https://www.npmjs.com/package/aurora">
<img src="https://img.shields.io/npm/v/aurora.svg" />
</a>
<a href="https://www.npmjs.com/package/aurora">
<img src="https://img.shields.io/npm/dt/aurora.svg" />
</a>
<a href="https://github.com/ianpaschal/aurora/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/ianpaschal/aurora.svg" />
</a>
<a href="https://github.com/ianpaschal/aurora/issues">
<img src="https://img.shields.io/github/issues-raw/ianpaschal/aurora.svg" />
</a>
<a href="https://codeclimate.com/github/ianpaschal/aurora">
<img src="https://img.shields.io/travis/ianpaschal/aurora.svg?" />
</a>
<a href="https://codeclimate.com/github/ianpaschal/aurora">
<img src="https://img.shields.io/codeclimate/maintainability/ianpaschal/aurora.svg?" />
</a>
<a href="https://codeclimate.com/github/ianpaschal/aurora">
<img src="https://img.shields.io/codeclimate/coverage/ianpaschal/aurora.svg?" />
</a>
</p>
Aurora is a small entity-component-system game engine for real-time-strategy games. It's also _sort of_ a mod API, but more on that later...
> Aurora is being developed alongside its intended use case, [Forge](https://github.com/ianpaschal/forge), and still churns quite a bit. There's also lots of test code present which requires refactoring and possible removal, but the basic architecture is stable and usable.
Aurora is based on four basic classes:
- `Engine`
- `Entity`
- `Component`
- `System`
In a nutshell:
- Components are JSON data with some useful helper methods.
- Entities are are arrays of components with some useful helper methods.
- Systems are pre-defined functions which are run each simulation loop and act on a subset of entities who have instances of the relevant components.
- The engine:
- Tells all systems to update each game loop
- Handles the creation and destruction of entities and components
- Handles the loading of assets using `Three.js` (geometries, materials, etc.)
The [wiki](https://github.com/ianpaschal/aurora/wiki) contains more detailed information about the architecture and usage of Aurora and extensive documentation of the different classes and methods available can be found in [`/docs`](https://github.com/ianpaschal/aurora/tree/master/docs) or at [ianpaschal.github.io/aurora](https://ianpaschal.github.io/aurora).
## Mod API
> "I read something above that said Aurora is '_sort of_ a mod API'."
That's correct. With Aurora, there's not really a distinction between core content and mods. Because all entities are both represented and saved as JSON (plus whatever other image assets or sounds), it's easy to add new units to the game without actually having to `eval()` any Javascript. This is especially useful for modded multiplayer where the required mods can be safely sent to all players in the game.
Obviously this exempts "systems" from being added as _they_ are the actual executable functions which process a world's entities, but exchanging those should eventually be possible as well as the users' discretion.
Read more on the [wiki](https://github.com/ianpaschal/aurora/wiki).
## License
Aurora is licensed under the MIT license.
<file_sep>/tests/core/Component.test.ts
import { Component } from "../../src";
import uuid from "uuid";
let instance: Component;
beforeEach( () => {
instance = new Component();
});
// Constructor
describe( "Component.constructor()", () => {
// TODO: it should generate a valid UUID
it( "should set type as 'noname'.", () => {
expect( instance.type ).toBe( "noname" );
});
it( "should create an empty data object.", () => {
expect( instance.data ).toEqual({});
});
});
describe( "Component.constructor( config )", () => {
let config;
beforeEach( () => {
config = {
uuid: uuid(),
type: "foo",
data: {}
};
instance = new Component( config );
});
it( "should copy the config's uuid if it exists.", () => {
expect( instance.uuid ).toEqual( config.uuid );
});
it( "should copy the config's type if it exists.", () => {
expect( instance.type ).toEqual( config.type );
});
it( "should copy, not reference, the config's type if it exists.", () => {
// Make sure to clone the original data, not reference it:
expect( instance.data ).not.toBe( config.data );
expect( instance.data ).toEqual( config.data );
});
});
// Getters
describe( "Component.json", () => {
it( "should return the correct JSON, without underscores.", () => {
expect( instance.json ).toEqual( JSON.stringify({
data: instance.data,
type: instance.type,
uuid: instance.uuid
}, null, 4 ) );
});
});
// Setters
describe( "Component.data = ", () => {
it( "should copy, not reference, the new data, replacing everything.", () => {
const data = {
foo: "bar"
};
instance.data = data;
expect( instance.data ).toEqual( data );
});
});
describe( "Component.type = ", () => {
it( "should set the type accordingly.", () => {
const type = "foo";
instance.type = type;
expect( instance.type ).toEqual( type );
});
});
// Other
describe( "Component.clone()", () => {
let clone: Component;
beforeEach( () => {
clone = instance.clone();
});
it( "should not clone the UUID.", () => {
expect( clone.uuid ).not.toEqual( instance.uuid );
});
it( "should clone the type.", () => {
expect( clone.type ).toEqual( instance.type );
});
it( "should clone the data.", () => {
// Ensure data is a copy, not a reference
expect( clone.data ).not.toBe( instance.data );
expect( clone.data ).toEqual( instance.data );
});
});
describe( "Component.copy( component )", () => {
let source: Component;
beforeEach( () => {
source = new Component({
uuid: uuid(),
type: "foo",
data: {
foo: 5
}
});
instance.copy( source );
});
it( "should not copy the UUID.", () => {
expect( instance.uuid ).not.toEqual( source.uuid );
});
it( "should copy the type.", () => {
expect( instance.type ).toEqual( source.type );
});
it( "should copy the data.", () => {
// Ensure data is a copy, not a reference
expect( instance.data ).not.toBe( source.data );
expect( instance.data ).toEqual( source.data );
});
});
describe( "Component.mergeData( data )", () => {
// TODO: Refine the tests for copying vs. overwriting data
it( "should add missing data to the instance.", () => {
instance.data = {
foo: true
};
instance.mergeData({
bar: 5
});
expect( instance.data ).toEqual({
foo: true,
bar: 5
});
});
it( "should overwrite existing data on the instance.", () => {
instance.data = {
foo: true
};
instance.mergeData({
foo: false
});
expect( instance.data ).toEqual({
foo: false
});
});
});
<file_sep>/src/utils/copy.ts
// Aurora is distributed under the MIT license.
/**
* @module utils
*/
export default function copy( obj ) {
return JSON.parse( JSON.stringify( obj ) );
}
<file_sep>/src/utils/capitalize.ts
// Aurora is distributed under the MIT license.
/**
* @module utils
*/
export default function capitalize( str ) {
// TODO: Capitalize per word
return str.charAt( 0 ).toUpperCase() + str.slice( 1 );
}
| afec6ab246d0f361030f4e753670b859e13f5cb1 | [
"Markdown",
"TypeScript"
] | 27 | TypeScript | ianpaschal/aurora | 0a27dd640d8a5cc9470587b44f874f5facaab22e | b2f1823ce74b94e514a33f13c6178f8de568991f | |
refs/heads/master | <repo_name>zuniphp/uri<file_sep>/README.md
# uri
Zuni Uri
<file_sep>/src/Zuni/Uri/ControllerToNamespaces.php
<?php
/*
* @package ZuniPHP
* @author <NAME> <<EMAIL>>
* @link http://zuniphp.github.io
* @copyright 2016
*
*/
namespace Zuni\Uri;
use Zuni\Contract\Uri\GetSegment as IGetSegment;
use Zuni\Contract\GetArr as IGetArr;
use Zuni\Filter\Preserve\AlnumUnderscoreHyphen;
use Zuni\Uri;
class ControllerToNamespaces implements IGetSegment
{
private $controller;
public function __construct()
{
self::_prepare();
}
public function getSegment()
{
return $this->controller;
}
private function _prepare()
{
$position = new Uri\Position(0);
$controller = $position->getSegment();
$this->controller = self::_getCapitalize($controller);
return $this;
}
private function _getCapitalize($controller)
{
$explodeFile = explode('_', $controller);
$prepareFile = array();
foreach ($explodeFile as $f)
{
$prepareFile[] = ucfirst($f);
}
$controller = implode('\\', $prepareFile);
return $controller;
}
}
<file_sep>/src/Zuni/Uri/Factory/Spt.php
<?php
namespace Zuni\Uri\Factory;
use Zuni\Contract\Create;
use Zuni\Uri\Full as UriFull;
use Zuni\Uri\Spt as UriSpt;
class Spt implements Create
{
public static function create()
{
return new UriSpt(new UriFull());
}
}
<file_sep>/src/Zuni/Uri/Full.php
<?php
/*
* @package ZuniPHP
* @author <NAME> <<EMAIL>>
* @link http://zuniphp.github.io
* @copyright 2016
*
*/
namespace Zuni\Uri;
use Zuni\Contract\Uri\GetSegment as IGetSegment;
class Full implements IGetSegment
{
private $_param = 'uri';
public function getSegment()
{
return self::_getUri();
}
private function _isUri()
{
return (array_key_exists($this->_param, $_GET));
}
private function _getUri()
{
if(!self::_isUri())
{
return NULL;
}
return $_GET[$this->_param];
}
}
<file_sep>/src/Zuni/Uri/Position.php
<?php
/*
* @package ZuniPHP
* @author <NAME> <<EMAIL>>
* @link http://zuniphp.github.io
* @copyright 2016
*
*/
namespace Zuni\Uri;
use Zuni\Contract\Uri\GetSegment as IGetSegment;
use Zuni\Contract\GetArr as IGetArr;
use Zuni\Filter\Preserve\AlnumUnderscoreHyphen;
use Zuni\Uri;
class Position implements IGetSegment
{
private $num;
private $filter;
private $explode;
public function __construct($num)
{
if(!is_int($num))
{
throw new \Exception("'argument requires number'\n");
}
$this->num = $num;
$this->filter = new AlnumUnderscoreHyphen();
$this->explode = new Uri\Spt(new Uri\Full());
}
public function getSegment()
{
$e = $this->explode->getArr();
$a = array_merge($e, array('index'));
$isAction = (array_key_exists(1, $e));
$e = ($isAction)? $e: $a;
if(!array_key_exists($this->num, $e))
{
return NULL;
}
$search = array('-');
$segment = $this->filter->filter($e[$this->num]);
return str_replace( $search, '_', $segment);
}
}
<file_sep>/src/Zuni/Uri/Spt.php
<?php
/*
* @package ZuniPHP
* @author <NAME> <<EMAIL>>
* @link http://zuniphp.github.io
* @copyright 2016
*
*/
namespace Zuni\Uri;
use Zuni\Contract\GetArr as IGetArr;
use Zuni\Contract\Uri\GetSegment as IGetSegment;
use Zuni\Registry\Container;
class Spt implements IGetArr
{
private $uri;
public function __construct(IGetSegment $uri)
{
$this->uri = $uri;
}
public function getArr()
{
if(!$this->uri->getSegment())
{
$container = Container::getInstance();
$index = strtolower($container->get('startController'));
return array( $index, 'index');
}
return explode('/', rtrim($this->uri->getSegment(), '/'));
}
}
| b8bec261346390afa238be0627be59040f9208b8 | [
"Markdown",
"PHP"
] | 6 | Markdown | zuniphp/uri | 6ddfa6359137d431a3328ddb5645a99567895873 | 9a482d05c0176646cec93773d8fe928b784eaaaa | |
refs/heads/master | <file_sep>from datetime import datetime
import time, threading
from pynput.mouse import Button, Controller
from pynput.keyboard import Key, Listener
isRun = False
timeSkip = 600
# 每n秒执行一次
def timer(n):
global isRun
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
mouseCtr()
time.sleep(n)
if isRun:
timer(n)
def mouseCtr():
'''
控制鼠标
'''
# 读鼠标坐标
mouse = Controller()
# 点击鼠标
mouse.click(Button.left)
def on_release(key):
global isRun
# print('{0} release'.format(key))
if key == Key.esc:
# Stop listener
isRun = False
return False
if key == Key.f12:
# Stop listener
isRun = not isRun
if isRun:
startT()
# print(not isRun)
def setKetBordListern():
# 连接事件以及释放
with Listener(on_release=on_release) as listener:
listener.join()
def startT():
t = threading.Thread(target=timer, args=(timeSkip,))
t.start()
def main():
t = threading.Thread(target=setKetBordListern)
t.start()
main()<file_sep># A-auto-mouseclick-script
sometimes useful for training networks in colab if you are not there
| 54dd59bb4a8d562cddb19a937c3b0134de808aa0 | [
"Markdown",
"Python"
] | 2 | Python | BonhomieStriker/A-auto-mouseclick-script | 30433002875222dd631b9d02f250722dce9995f6 | fa392f844fa9a5337d3d6bd4699ae5058914b377 | |
refs/heads/master | <repo_name>raju080/MyGP-Database<file_sep>/DML.sql
INSERT INTO INTERNET_OFFER (OFFER_ID, PRICE, VALIDITY, REWARD_POINTS, DATA_AMOUNT) VALUES
(100, 56, 30, 0, 115),
(101, 31, 3, 25, 252),
(102, 10, 7, 0, 10),
(103, 101, 7, 0, 300);
INSERT INTO TALK_TIME_OFFER (OFFER_ID, PRICE, VALIDITY, REWARD_POINTS, TALK_TIME) VALUES
(200, 140, 7, 0, 250),
(201, 30, 1, 0, 50);
INSERT INTO SMS_OFFER (OFFER_ID, PRICE, VALIDITY, REWARD_POINTS, SMS_AMOUNT) VALUES
(300, 10, 2, 0, 20);
INSERT INTO PACKAGE (PACKAGE_ID, PACKAGE_NAME, CALL_RATE, SMS_RATE, data_rate, FNF_LIMIT) VALUES
(10, 'BONDHU', .275, .50, 1.5, 18),
(11, 'NISHCHINTO', .22, .50, 1.4, 0),
(12, 'DJUICE', .22, .50, 1.6, 13);
INSERT INTO STAR VALUES (1, 'PLATINUM_PLUS', 400, 180);
INSERT INTO STAR VALUES (2, 'PLATINUM', 300, 180);
INSERT INTO STAR VALUES (3, 'GOLD', 250, 180);
INSERT INTO STAR VALUES (4, 'SILVER', 200, 180);
INSERT INTO USERS VALUES
(01755840785, 13.4, 10, 185, 0, 'RAJU', 0, 0, 10, NULL, NULL),
(01787571129, 20.9, 50, 200, 0, 'TUSHAR', 5, 10, 11, 3, NULL),
(01787571128, 1000, 50, 200, 0, 'MARCHANT', 5, 10, 11, null, NULL);
<file_sep>/main.sql
CREATE DATABASE MYGP;
CREATE SCHEMA IF NOT EXISTS MYGP_SCHEMA;
drop schema MYGP_SCHEMA cascade;
DO $$
BEGIN
CALL PURCHASE_INTERNET_OFFER(103, 1787571128);
end;
$$;
| 297663d297343716b4b9647344b37c744d1507b3 | [
"SQL"
] | 2 | SQL | raju080/MyGP-Database | 0f119d936e531f44983b6f9e8d2b8e2575f8bba3 | ba85d44849d6089f121bb9b8aaa98381db1898c1 | |
refs/heads/master | <file_sep># minidb-ui
## 运行
```bash
npm install
npm start
```
## 网络接口
1. 运行SQL语句
`POST: /api/runsql`
附带data为字符串,即所要运行的SQL语句。
期望返回结果为json格式,字段如下:
| 字段 | 类型 | 说明 |
| ----------- | -------- | ------------------------------------------------------------ |
| status | boolean | SQL执行成功返回true,反正false。 |
| message | string | SQL执行的反馈信息。<br/><br/>e.g.<br/>查询语句执行之后,可返回message为"10000 rows returned." |
| totalTime | string | 执行本次SQL语句所用时间。<br><br>e.g.<br>"0.34s" |
| time | string | 执行本次SQL语句的时间点。<br/><br/>e.g.<br/>"16:49" |
| curDatabase | string | 执行本次SQL语句后当前数据库的名字。 |
| columns | string[] | 执行本次SQL语句查询到的数据列。如果不是查询语句,则返回空数组[]。<br/> <br/>e.g.<br/>['id', 'name', 'age'] |
| data | any[] | 执行本次SQL语句查询到的数据。如果不是查询语句或查询结果为空,则返回空数组[]。<br/><br/>e.g.<br/>[<br/> { id: 1, name: 'zhang', age: 20 },<br/> { id: 2, name: 'asfdasdf', age: 23 },<br/> { id: 3, name: 'ljk', age: 20 },<br/>] |
2. 获取当前数据库名字
`GET: /api/curdb`
无参数。
期望返回结果为json格式,字段如下:
| 字段 | 类型 | 说明 |
| ------ | ------- | ------------------------------------------------------------ |
| status | boolean | 如果至少存在一个数据库,则返回true,反之返回false。 |
| res | string | 如果至少存在一个数据库,则返回当前所在数据库名字。<br>若当前没有指定的数据库或status为false,则返回"(Please use a database!)"。 |
注:SQL语句运行并不需要指定数据库名字,因为始终有一个默认选定的数据库上下文。该接口的目的就是获取该上下文的名字,显示在界面最上方。<file_sep>import { Ace } from 'ace-builds';
import axios, { AxiosResponse } from 'axios';
const axiosIns = axios.create();
const isMock = true;
interface IRunSQLRes {
/**
* SQL执行成功返回true,反正false。
*/
status: boolean;
/**
* SQL执行的反馈信息。
*
* e.g.
* 查询语句执行之后,可返回message为 "10000 rows returned."
*/
message: string;
/**
* 执行本次SQL语句所用时间。
*
* e.g.
* "0.34s"
*/
totalTime: string;
/**
* 执行本次SQL语句的时间。
*
* e.g.
* "16:49"
*/
time: string;
/**
* 执行本次SQL语句后当前数据库的名字。
*/
curDatabase: string;
/**
* 执行本次SQL语句查询到的数据列。如果不是查询语句,则返回空数组[]。
*
* e.g.
* ['id', 'name', 'age']
*/
columns: string[];
/**
* 执行本次SQL语句查询到的数据。如果不是查询语句或查询结果为空,则返回空数组[]。
*
* e.g.
* [
* { id: 1, name: 'zhang', age: 20 },
* { id: 2, name: 'asfdasdf', age: 23 },
* { id: 3, name: 'ljk', age: 20 },
* ]
*/
data: any[];
/**
* 本次SQL语句的语法错误出现位置。如果没有语法错误,则为null。
*/
error: Required<Ace.Annotation> | null;
}
export const runSQL = (sql: string) => {
if(!isMock) {
return axiosIns.post<any, AxiosResponse<IRunSQLRes[]>>('/api/runsql', {
command: sql
});
}
return new Promise<{ data: IRunSQLRes[] }>((resolve, reject) => {
setTimeout(() => {
resolve({
data: [{
status: true,
message: '3000000 rows returned.',
totalTime: '0.53s',
time: '16:34',
curDatabase: 'student',
columns: ['id', 'name', 'age', 'home', 'phone', 'phone1', 'phone2', 'phone3', 'phone4', 'phone5'],
data: Array.from({length: 300000}, (_, item) => ({
key: item,
id: item,
name: '' + item + item + item,
age: item * 2,
home: '' + item + item + item,
phone: '' + item + item + item,
phone1: '' + item + item + item,
phone2: '' + item + item + item,
phone3: '' + item + item + item,
phone4: '' + item + item + item,
phone5: '' + item + item + item,
})),
error: {
row: 1,
column: 2,
text: 'error in asdf',
type: "error"
}
}, {
status: false,
message: '200000 rows returned.',
totalTime: '0.5345s',
time: '16:34',
curDatabase: 'student',
columns: ['id', 'name', 'age', 'home', 'phone', 'phone1', 'phone2', 'phone3', 'phone4', 'phone5'],
data: Array.from({length: 300000}, (_, item) => ({
key: item,
id: item,
name: '' + item + item + item,
age: item * 2,
home: '' + item + item + item,
phone: '' + item + item + item,
phone1: '' + item + item + item,
phone2: '' + item + item + item,
phone3: '' + item + item + item,
phone4: '' + item + item + item,
phone5: '' + item + item + item,
})),
error: {
row: 2,
column: 3,
text: 'error in asdf',
type: "error"
}
}]
})
}, 0);
});
};
interface ICurDatabaseRes {
/**
* 如果至少存在一个数据库,则返回true,反之返回false。
*/
status: boolean;
/**
* 如果至少存在一个数据库,则返回第一个找到的数据库的名字,反之返回空字符串。
*/
res: string;
}
export const getCurDatabase = () => {
if(!isMock) {
return axiosIns.get<any, AxiosResponse<ICurDatabaseRes>>('/api/curdb');
}
return new Promise<any>((resolve, reject) => {
setTimeout(() => {
resolve({
data: {
status: true,
res: '(Please use a database!)'
}
})
}, 100);
});
} | fd385e82e42eb492bea795a584f1d6bf5c98b4dc | [
"Markdown",
"TypeScript"
] | 2 | Markdown | Crawler995/minidb-ui | e98fca4f048c16e9d62ebe7aa0f16f0b80591b71 | 5b604ad91d89fe47eb32cb2c9ad3ea8deaa32847 | |
refs/heads/master | <file_sep>package com.noos.databrain.pages;
import org.springframework.stereotype.Component;
@Component
public class TestPage extends AbstractPage {
public void openPage(String url) {
System.out.println(s);
}
}
<file_sep><?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.social</groupId>
<artifactId>MultiDriver</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<browser>chrome</browser>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.48.2</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.9</version>
<scope>test</scope>
</dependency>
<!-- Log4j dependency -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18</version>
<configuration>
<systemProperties>
<property>
<name>runOn</name>
<value>local</value>
</property>
<property>
<name>browser</name>
<value>${browser}</value>
</property>
</systemProperties>
<suiteXmlFiles>
<suiteXmlFile>.\src\test\java\com\noos\databrain\tests\Suite.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
<name>MultiDriver</name>
</project><file_sep>local_ff_dir = E:\\ffprofile<file_sep>package com.noos.databrain.browsers;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public interface Browser {
public DesiredCapabilities setCaps(String runOn);
public WebDriver getDriver();
}
<file_sep>
package com.noos.databrain.browsers;
public class Tloc {
}
<file_sep>package com.noos.databrain.tests;
import com.noos.databrain.browsers.DriverManager;
import com.noos.databrain.pages.BrowserThread;
import com.noos.databrain.steps.Steps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@ContextConfiguration(locations = {"classpath:spring-config.xml"})
public class T1Control extends AbstractTestNGSpringContextTests {
@Autowired
DriverManager man;
@Autowired
Steps step;
@Test(invocationCount = 1)
public void test1() throws InterruptedException {
System.out.println("START MAIN 1");
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) applicationContext.getBean("taskExecutor");
String[] bros = {"chrome"};
broExecutor(bros, taskExecutor);
taskExecutor.shutdown();
System.out.println("FINISH MAIN");
}
public void broExecutor(String[] bros, ThreadPoolTaskExecutor task) {
for (String bro : bros) {
BrowserThread bt = (BrowserThread) applicationContext.getBean("browserThread");
bt.setName(bro);
task.execute(bt);
}
}
@AfterClass
public void quitDriver1() {
step.openPage("https://www.google.com.ua/");
System.out.println("get in main");
man.quitDriver();
}
@BeforeClass
public void initDriver() {
man.initDefDriver();
}
private void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ex) {
}
}
}
<file_sep>package com.noos.databrain.pages;
import org.springframework.stereotype.Component;
@Component
//@Scope("prototype")
public class AbstractPage {
// public WebDriver driver;
//
// public void initDriver() {
// driver = LocalDriver.getDriver();
// }
public static String s;
public void setS(String s) {
AbstractPage.s = s;
}
}
<file_sep>package com.noos.databrain.steps;
import com.noos.databrain.pages.TestPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Steps {
@Autowired
TestPage page;
public void openPage(String url) {
page.openPage(url);
}
}
<file_sep>
package com.noos.databrain.multidriver;
public class Times {
public static long ms = 1000;
}
| 6c1889e16ce393250c7740500867fa57ad920c49 | [
"Java",
"Maven POM",
"INI"
] | 9 | Java | KonstJobs/MultiDriver | a780bc96228fef25a9d19ba44b054cf341a0ec6e | bfa1bc5f1898cec614c30c3f4f49c9d03700daf0 | |
refs/heads/main | <repo_name>hsevket/React<file_sep>/README.md
# React
ReactProjects
<file_sep>/src/Cube.js
import { useState } from "react";
const colors = ["white", "red", "blue", "green", "yellow", "orange"];
const rand = () => Math.floor(Math.random() * 6);
const Cube = () => {
const [myColor, setColor] = useState(colors[rand()]);
return (
<button
type="button"
onClick={() => setColor(colors[rand()])}
className="cube"
style={{ backgroundColor: myColor }}
>
{" "}
</button>
);
};
export default Cube;
<file_sep>/src/App.js
import "./App.css";
import Cube from './Cube'
// const colors = ["white", "red", "blue", "green", "yellow", "orange"];
// const rand = () => Math.floor(Math.random() * 6);
function App() {
const cubes = [1, 2, 3, 4, 5, 6, 7, 8, 9];
return (
<div className="App">
<div className="container">
{cubes.map((x) => (
<Cube key={x} />
))}
</div>
</div>
);
}
export default App;
| f2b3bd87d2e3b67eb807868eca7ed3ab3d00b4b7 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | hsevket/React | b458f1e7b60476c5cdb42e376a657c13d449f7a9 | 161ddebf57027d0b522100ff4198c9dc8bb3f4e1 | |
refs/heads/master | <repo_name>zakywtf/mini-e-wallet-pretest-<file_sep>/src/lib/signupHandler.js
import bcrypt from '<PASSWORD>js'
import users from '../schema/users'
import userBalanceModel from '../model/userBalanceModel';
const USERBALANCE = new userBalanceModel()
const signup = async(body) => {
const {username, password} = body
body.password = <PASSWORD>.hashSync(username+password+process.env.SALT, 10);
body.level=2
let userData = new users(body)
// console.log(body);
var data = await userData.save()
console.log({data});
await USERBALANCE.saveInitBalance(data.id)
return true
}
module.exports ={
signup
}<file_sep>/src/model/balanceBankModel.js
import Models from '../classes/classModel';
import balance_bank from '../schema/balance_bank';
class balanceBankModel extends Models{
constructor(){
super(balance_bank)
}
}
module.exports=balanceBankModel<file_sep>/src/model/balanceBankHistoryModel.js
import Models from '../classes/classModel';
import balance_bank_history from '../schema/balance_bank_history';
class balanceBankHistoryModel extends Models{
constructor(){
super(balance_bank_history)
}
async saveHistory(balance_bank_id, balance_before, balance_after, activity, tipe, ip, location, user_agent, author){
console.log({balance_bank_id, balance_before, balance_after, activity, tipe, ip, location, user_agent, author});
var history = await this.model.create({
balance_bank_id,
balance_before,
balance_after,
activity,
tipe,
ip,
location,
user_agent,
author
})
// console.log({history});
return history
}
}
module.exports=balanceBankHistoryModel<file_sep>/src/controller/logout.js
import {Router} from 'express'
import {decode, deleteSession} from '../lib/sessionHandler';
import handleRequest from '../lib/ctrlHandler'
let router = Router()
router.route('/')
.post(
async (req,res) =>{
handleRequest(req,res,async(body)=>{
var dc = await decode(req.headers['token'])
var udata = dc.payload.payload
return await deleteSession(udata)
})
}
)
module.exports=router<file_sep>/README.md
# express.js
1. npm install --save
2. npm run debug >> /dev/null
3. import file "tes_privyid.postman_collection.json" di postmant collection untuk melakukan tes
step tes di postman
1. signup
2. signin
3. logout
4. create balance bank terlebih dahulu
5. user topup
6. user transfer
<file_sep>/src/schema/user_balance.js
let mongoose = require('mongoose')
let Schema = mongoose.Schema
const user_balance = mongoose.Schema({
user_id:{type: Schema.Types.ObjectId, autopopulate:{ select: 'username level' }, ref:'users'},
balance: { type: Number, default:0},
balance_achieve: {type:Number, default:0}
})
user_balance.plugin(require('mongoose-autopopulate'))
module.exports = mongoose.model('user_balance', user_balance);<file_sep>/src/schema/users.js
let mongoose = require('mongoose')
const users = mongoose.Schema({
username: { type: String, required: true,},
password: { type: String, required: true },
level: String,
createAt: {type:Date, default:Date.now}
})
users.index({username:1},{unique:true})
module.exports = mongoose.model('users', users);<file_sep>/src/lib/masterCache.js
import fetch from 'node-fetch';
import balanceBankModel from '../model/balanceBankModel';
import balanceBankHistoryModel from '../model/balanceBankHistoryModel';
import userBalance from '../model/userBalanceModel';
import userBalanceHistory from '../model/userBalanceHistoryModel';
const BALANCEBANKMODEL = new balanceBankModel()
const BALANCEBANKHISTORYMODEL = new balanceBankHistoryModel()
const USERBALANCE = new userBalance()
const USERBALANCEHISTORY = new userBalanceHistory()
const BALANCEBANKLIST = {}
const USERBALANCELIST = {}
const getData=async(url)=>await fetch(url).then(resp=>resp.json()).then(json=>json).catch(error=>error);
const getGeoLocation = async(ip, userAgent) => {
try {
return await getData(`https://ipapi.co/${ip}/json/`);
} catch (error) {
throw error;
}
}
const loadBalanceBank = async() => {
const data = await BALANCEBANKMODEL.getAll()
await Promise.all(data.map((v)=>{
BALANCEBANKLIST[`${v.id}`]=v._doc
}))
}
const loadUserBalance = async() => {
const datas = await USERBALANCE.getAll()
await Promise.all(datas.map((v)=>{
USERBALANCELIST[`${v._doc.user_id.id}`]={id:v.id, balance:v._doc.balance, balance_achieve:v._doc.balance_achieve}
}))
}
const saveBalanceBank=async(id, balance)=>{
let data = await BALANCEBANKMODEL.getById(id)
// console.log({data});
data.balance = balance
data.save()
}
const updateUserBalanceTransfer=async(id, balance)=>{
let data = await USERBALANCE.getById(id)
// console.log({data});
data.balance += balance
data.save()
}
const updateUserBalanceTopup=async(userId, topup)=>{
const user_balance = USERBALANCELIST[`${userId}`]
if(user_balance){
user_balance.balance += topup
user_balance.balance_achieve += topup
let data = await USERBALANCE.getById(user_balance.id)
data.balance = user_balance.balance
data.balance_achieve = user_balance.balance_achieve
data.save()
}
}
const processTopup=async(bankId, topup, tipe, ip, user_agent, userId)=>{
const bank = BALANCEBANKLIST[`${bankId}`]
if(bank){
const min = topup * -1
const balance_before = bank.balance
bank.balance += min
const balance_after = bank.balance
const activity = "Topup"
const location = await getGeoLocation(ip)
await saveBalanceBank(bankId, bank.balance)
await updateUserBalanceTopup(userId, topup)
return await BALANCEBANKHISTORYMODEL.saveHistory(bankId, balance_before, balance_after, activity, tipe, ip, location.city, user_agent.source, user_agent.platform)
}
}
const processTransfer=async(userId, transfer, tipe, ip, user_agent)=>{
const user_balance = USERBALANCELIST[`${userId}`]
if(user_balance){
const min = transfer * -1
const balance_before = user_balance.balance
user_balance.balance += min
const balance_after = user_balance.balance
const activity = "Transfer"
const location = await getGeoLocation(ip)
const balanceId = user_balance.id
await updateUserBalanceTransfer(balanceId, min)
return await USERBALANCEHISTORY.saveHistory(balanceId, balance_before, balance_after, activity, tipe, ip, location.city, user_agent.source, user_agent.platform)
}
}
console.log({BALANCEBANKLIST, USERBALANCELIST});
module.exports={
loadBalanceBank,
loadUserBalance,
processTopup,
processTransfer
}<file_sep>/src/model/userBalanceModel.js
import Models from '../classes/classModel';
import user_balance from '../schema/user_balance';
class userBalanceModel extends Models{
constructor(){
super(user_balance)
}
async saveInitBalance(user_id){
const doc = await this.model.create({
user_id
})
await doc.save()
return doc;
}
}
module.exports=userBalanceModel<file_sep>/src/schema/balance_bank.js
let mongoose = require('mongoose')
const balance_bank = mongoose.Schema({
balance: { type: Number, default:0},
balance_achieve: {type:Number, default:0},
code:String,
enable:{type:Boolean, default:true},
})
module.exports = mongoose.model('balance_bank', balance_bank);<file_sep>/src/model/userModel.js
import Models from '../classes/classModel';
import users from '../schema/users';
class userModel extends Models{
constructor(){
super(users)
}
async getAll(){
var udata = this.udata.payload
console.log({udata:this.udata.payload});
// if(udata.role != this.role)throw Error('You do not have access!')
return await this.model.find({},this.getProjection())
}
getProjection(){
return 'username level'
}
}
module.exports=userModel<file_sep>/src/schema/user_balance_history.js
let mongoose = require('mongoose')
let Schema = mongoose.Schema
const user_balance_history = mongoose.Schema({
user_balance_id:{type: Schema.Types.ObjectId, autopopulate:true, ref:'user_balance'},
balance_before: { type: Number, default:0},
balance_after: {type:Number, default:0},
activity:String,
tipe:{type:String, enum:['credit', 'debit']},
ip:String,
location:String,
user_agent:String,
author:String
})
user_balance_history.plugin(require('mongoose-autopopulate'))
module.exports = mongoose.model('user_balance_history', user_balance_history); | 6226bedbe791c0ebe6b714c04ced6138e08a0829 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | zakywtf/mini-e-wallet-pretest- | 449ceaec2dc5cca41ca5a4ab8eafb9dba189852c | d1f411d6561ab1c5a35feb974c051d5878807fb9 | |
refs/heads/master | <file_sep>require 'omniauth/strategies/plato'
describe OmniAuth::Strategies::Plato do
subject { OmniAuth::Strategies::Plato.new({}) }
describe "client options" do
it "has correct site" do
subject.options.client_options.site.should eq("http://subscriptions.teachtci.com")
end
it "has correct authorize url" do
subject.options.client_options.authorize_url.should eq("http://subscriptions.teachtci.com/oauth/authorize")
end
end
describe "name" do
context "teacher" do
it "should return first and last name from raw_info if available" do
subject.stub!(:raw_info).and_return({ "user" => { "teacher" => {"first_name" => "John", "last_name" => "Kelly" }}})
subject.info.should == {:name => "<NAME>", :user_type => "teacher", :customer_number => nil}
end
end
context "coordinator" do
it "should return first and last name from raw_info if available" do
subject.stub!(:raw_info).and_return({ "user" => { "coordinator" => {"first_name" => "John", "last_name" => "Kelly" }}})
subject.info.should == {:name => "<NAME>", :user_type => "coordinator", :customer_number => nil}
end
end
context "admin" do
it "should return first and last name from raw_info if available" do
subject.stub!(:raw_info).and_return({ "user" => { "admin" => {"first_name" => "John", "last_name" => "Kelly" }}})
subject.info.should == {:name => "<NAME>", :user_type => "admin", :customer_number => nil}
end
end
end
describe "uid" do
context "teacher" do
it "should return uid from raw_info if available" do
subject.stub!(:raw_info).and_return({ "user" => { "teacher" => {"id" => "9" }}})
subject.uid.should == "9"
end
end
context "coordinator" do
it "should return uid from raw_info if available" do
subject.stub!(:raw_info).and_return({ "user" => { "coordinator" => {"id" => "9"}}})
subject.uid.should == "9"
end
end
context "admin" do
it "should return uid from raw_info if available" do
subject.stub!(:raw_info).and_return({ "user" => { "admin" => {"id" => "9" }}})
subject.uid.should == "9"
end
end
end
describe "customer_number" do
it "should return the customer number from the raw_info" do
subject.stub!(:raw_info).and_return({ "user" => { "teacher" => { "id" => "9" }}, "customer_number" => "QWERTY12345" })
subject.info[:customer_number].should == "QWERTY12345"
end
end
end<file_sep>require 'omniauth-oauth2'
module OmniAuth
module Strategies
class Plato < OmniAuth::Strategies::OAuth2
option :name, :plato
option :client_options, {
:site => "http://subscriptions.teachtci.com",
:authorize_url => "http://subscriptions.teachtci.com/oauth/authorize"
}
uid { raw_info["user"][staffer_type]["id"] }
info do
{
:name => "#{staffer["first_name"]} #{staffer["last_name"]}",
:user_type => staffer_type,
:customer_number => raw_info["customer_number"]
}
end
def staffer
raw_info["user"][staffer_type]
end
def raw_info
@raw_info ||= access_token.get('/api/v1/user.json').parsed
end
def staffer_type
raw_info["user"].keys.detect{|key| staffer_types.include?(key) }
end
private
def staffer_types
%w[teacher coordinator admin sysadmin]
end
end
end
end | c7680699142437ee98abf228d493b257e1a1f8dd | [
"Ruby"
] | 2 | Ruby | johnkelly/omniauth-plato | d03a8c742119026bc2a166957aad7ed489e22363 | 7e3366ee5dfe2eaaf3ab2f5c3d8c6818a2fd5225 | |
refs/heads/master | <repo_name>asheplyakov/gzipsplit<file_sep>/test/test_ab.sh
#!/bin/sh
set -e
rm -f s_*.gz
./gzipsplit test/ab.img
if [ ! -f s_0.gz ]; then
echo "file s_0.gz is not found" >&2
exit 1
fi
if [ ! -f s_1.gz ]; then
echo "file s_1.gz is not found" >&2
exit 1
fi
if [ -f s_2.gz ]; then
echo "extra file s_2.gz has been found" >&2
fi
zcat s_0.gz > s_0.txt
if ! cmp -s s_0.txt test/a.txt; then
echo "1st file does not match expected test/a.txt" >&2
exit 1
fi
zcat s_1.gz > s_1.txt
if ! cmp -s s_1.txt test/b.txt; then
echo "1st file does not match expected test/b.txt" >&2
exit 1
fi
exit 0
<file_sep>/gzipsplit.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void switch_file(FILE **current, int *count) {
char buf[sizeof("s_1234567890.gz")];
memset(buf, 0, sizeof(buf));
if (*current) {
if (fflush(*current) != 0)
exit(2);
if (fclose(*current) != 0)
exit(3);
*current = NULL;
}
sprintf(buf, "s_%d.gz", *count);
++(*count);
*current = fopen(buf, "w");
if (!*current)
exit(5);
}
static int can_be_flg(char c) {
const char flg_mask = 0x1f;
if ((c & ~flg_mask) == 0)
return 1;
else
return 0;
}
static void process(FILE *in) {
int count = 0;
FILE* current = NULL;
int c1, c2, c3, c4;
size_t off = 0;
while (1) {
c1 = c2 = c3 = c4 = EOF;
c1 = fgetc(in);
if (c1 == EOF)
break;
off++;
if (!current) {
printf("writing file #1\n");
switch_file(¤t, &count);
if (fputc(c1, current) == EOF)
exit(11);
continue;
}
if ((char)c1 == '\x1F') {
c2 = fgetc(in);
if (c2 == EOF) {
if (fputc(c1, current) == EOF)
exit(11);
break;
}
off++;
if ((char)c2 == '\x8B') {
c3 = getc(in);
if (c3 == EOF) {
if (fputc(c1, current) == EOF)
exit(11);
if (fputc(c2, current) == EOF)
exit(11);
break;
}
off++;
if ((char)c3 == '\x08') {
c4 = getc(in);
if (c4 == EOF) {
if (fputc(c1, current) == EOF)
exit(11);
if (fputc(c2, current) == EOF)
exit(11);
if (fputc(c3, current) == EOF)
exit(11);
break;
}
off++;
if (can_be_flg((char)c4)) {
printf("writing file #%d\n", count + 1);
switch_file(¤t, &count);
}
if (fputc(c1, current) == EOF)
exit(11);
if (fputc(c2, current) == EOF)
exit(11);
if (fputc(c3, current) == EOF)
exit(11);
if (fputc(c4, current) == EOF)
exit(11);
} else {
/* c3 != '\x08' */
if (fputc(c1, current) == EOF)
exit(11);
if (fputc(c2, current) == EOF)
exit(11);
if (fputc(c3, current) == EOF)
exit(11);
}
} else {
/* c2 != '\x8B' */
if (fputc(c1, current) == EOF)
exit(11);
if (fputc(c2, current) == EOF)
exit(11);
}
} else {
/* c1 != '\x1F' */
if (fputc(c1, current) == EOF)
exit(11);
}
}
if (current) {
fflush(current);
fclose(current);
current = NULL;
}
}
int main(int argc, char **argv) {
FILE* in;
in = fopen(argv[1], "r");
if (!in) {
exit(7);
}
process(in);
fclose(in);
return 0;
}
<file_sep>/README.md
# Split concatenated gzip archives
## What?
Some Linux distributions (in particular [ALT Linux](http://www.altlinux.org))
use tricky initramfs images which consist of concatenated gzip archives.
This little program helps to split such initramfs images into individual
gzip files.
## Usage
```bash
$ gzipsplit /path/to/full.cz
writing file #1
writing file #2
writing file #3
```
The output will be written to files `s_N.gz` (with N = 0, 1, 2 in
this example). This naming is hard coded, sorry.
## Building
```bash
$ make check
```
<file_sep>/Makefile
CFLAGS ?= -O2 -g -Wall
gzipsplit: gzipsplit.c Makefile
$(CC) $(CFLAGS) -o $@ $<
check: gzipsplit test/ab.img
./test/test_ab.sh
test/ab.img: test/a.txt test/b.txt
gzip -c < test/a.txt > [email protected]
gzip -c < test/b.txt >> [email protected]
mv [email protected] $@
clean:
@rm -f gzipsplit
.PHONY: clean
| ec2bd2dae772d8d96e1f194b8ce608a38c8f454b | [
"Markdown",
"C",
"Makefile",
"Shell"
] | 4 | Shell | asheplyakov/gzipsplit | 65030061f517c39561261530aa41698e68800531 | 5aff019a9be8a58de2bc26da24373abf61ff097d | |
refs/heads/master | <repo_name>nguyenphuocdai/cv-deploy<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ServiceWorkerModule } from '@angular/service-worker';
import { AppComponent } from './app.component';
import { environment } from '../environments/environment';
import { AppRoutingModule } from './app-routing.module';
import { HeaderComponent } from './shared/header.component';
import { AboutComponent } from './component/about/about.component';
import { SkillComponent } from './component/skill/skill.component';
import { EducationComponent } from './component/education/education.component';
import { PortofioComponent } from './component/portofio/portofio.component';
import { ContactComponent } from './component/contact/contact.component';
import { ExperienceComponent } from './component/experience/experience.component';
import { NgCircleProgressModule } from 'ng-circle-progress';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
AboutComponent,
SkillComponent,
EducationComponent,
PortofioComponent,
ContactComponent,
ExperienceComponent
],
imports: [
BrowserModule,
ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production }),
AppRoutingModule,
NgCircleProgressModule.forRoot({
radius: 100,
outerStrokeWidth: 16,
innerStrokeWidth: 8,
outerStrokeColor: '#78C000',
innerStrokeColor: '#C7E596',
animationDuration: 300,
}),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { AboutComponent } from './component/about/about.component';
import { SkillComponent } from './component/skill/skill.component';
import { ExperienceComponent } from './component/experience/experience.component';
import { PortofioComponent } from './component/portofio/portofio.component';
import { EducationComponent } from './component/education/education.component';
import { ContactComponent } from './component/contact/contact.component';
const routes: Routes = [
{ path: '', redirectTo: '/about', pathMatch: 'full' },
{ path: 'about', component: AboutComponent },
{ path: 'skill', component: SkillComponent },
{ path: 'experience', component: ExperienceComponent },
{ path: 'portfolio', component: PortofioComponent },
{ path: 'education', component: EducationComponent },
{ path: 'contact', component: ContactComponent },
];
@NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [ RouterModule ],
declarations: []
})
export class AppRoutingModule { }
| cb3da4e7ccd15ef9dcde4e817f3389b324229ded | [
"TypeScript"
] | 2 | TypeScript | nguyenphuocdai/cv-deploy | b91bd55657a2825ef0088a649fe1ab8cf591d5ee | c33331cd491fb79be0cd6cced9963c410851be7b | |
refs/heads/master | <repo_name>kostenk0/CookBook<file_sep>/README.md
cd CookBook\client
<br/>
npm i
<br/>
npm run all
<file_sep>/client/src/Components/Header.js
import React from 'react';
import { Link } from 'react-router-dom';
import { Navbar, Nav, Form } from 'react-bootstrap'
const Header = () => {
return (
<Navbar bg="light" variant="light" sticky="top">
<Navbar.Brand href="#home">Книга рецептів</Navbar.Brand>
<Nav className="mr-auto">
</Nav>
<Form inline>
<Nav.Link ><Link to="/search" style={{ color: 'grey' }}>Пошук</Link></Nav.Link>
<Nav.Link ><Link to="/add" style={{ color: 'grey' }}>Додати</Link></Nav.Link>
</Form>
</Navbar>
);
}
export default Header;<file_sep>/client/src/Components/RecipeShort.js
import React from 'react';
import { Link } from 'react-router-dom';
import { Card, Button } from 'react-bootstrap'
const RecipeShort = (props) => {
if (props.Recipes !== null) {
return (
props.Recipes.map(Recipe => {
return (
<Card border="info" style={{ margin: '20px' }}>
<Card.Body>
<Card.Title>{Recipe.title}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">
{Recipe.ingredients.map((el, index) => {
return <li key={el.name + el.amount}>
{el.name + " " + el.amount}
</li>
})}
</Card.Subtitle>
<Card.Text>
{Recipe.description.slice(0, 100)}...
</Card.Text>
<Link to="/details"><Button variant="light" onClick={() => props.clickRecipe(Recipe.id)}>Детальніше</Button></Link>
</Card.Body>
</Card>
);
})
);
}
return (
<p>Відсутні рецепти</p>
)
}
export default RecipeShort; | 7baf0ba7130463ced37bcf7fa25a711258513224 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | kostenk0/CookBook | 4b974e1a23eb1194148a14156f11c7a42afd17bf | afb1f47aa360fec000d2975756f084a832e82676 | |
refs/heads/master | <file_sep>module.exports.AddNameModule = function(name, surname){
return name +' '+ surname;
}<file_sep># lerna-hands-on
Demo on monorepo using Lerna
# Medium article
https://medium.com/@chandola.nimish/monorepos-with-lerna-b1f2dfa3cd2c
<file_sep>var {greet} = require('FormatNameModule');
var {AddNameModule} = require('AddNameModule');
console.log(`${greet()} ${AddNameModule("Nimish", "Chandola")}`);
| 0af4d1e7f7727ce7b285589f405ff70b4d69c8fd | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | NimishChandola/lerna-hands-on | d4798bc8b0e9ff9059b705c7d6b52b7020c11d30 | 4b71b8ced4202b2c038409df9423f9557d80da44 | |
refs/heads/master | <repo_name>paynerc/signal-2019-voip-ios<file_sep>/VoiceDialerSDKTester/VoiceDialerSDKTester/View Controllers/ViewController.swift
//
// ViewController.swift
// VoiceDialerSDKTester
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import VoiceDialerSDK
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
get{
return .portrait
}
}
@IBAction func placeCall(_ sender: Any) {
// Set up your Twilio Function using twilio-function-access-token.js
// and invoke it to generate a token
// e.g. https://YOUR_TWILIO_FUNCTION.twil.io/voiceaccesstoken?identity=Alice&apiKeySecret=SECRET&appSid=AP_SID&apiKeySid=SK_API_KEY_SID
VoiceDialer.placeCall(identity: "ACME Support",
accessToken: "ACCESS_TOKEN",
callParameters: ["orderID" : "12345",
"name": "Alice"],
delegate: self)
}
}
extension ViewController: VoiceDialerDelegate {
func callStateDidChange(state: CallState, error: Error?) {
print("callStateDidChange: \(state.rawValue), error: \(error != nil ? error!.localizedDescription : "N/A")")
}
func callDidFailToConnect(error: Error) {
print("callDidFailToConnect: \(error.localizedDescription)")
}
func callWillHangup() {
print("Hangup button pressed")
}
func callWillMute() {
print("Mute button pressed")
}
func callWillUmute() {
print("Unmute button pressed")
}
func callWillHold() {
print("Hold button pressed")
}
func callWillResume() {
print("Unhold button pressed")
}
}
<file_sep>/VoiceDialerSDK/VoiceDialerSDK/View Controllers/InCallViewController.swift
//
// InCallViewController.swift
// VoiceDialerSDK
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class InCallViewController: UIViewController {
@IBOutlet weak var contactImageContainer: UIView!
@IBOutlet weak var identityLabel: UILabel!
@IBOutlet weak var stateLabel: UILabel!
@IBOutlet weak var muteButton: RoundButton!
@IBOutlet weak var hangupButton: RoundButton!
// MARK: - Instance properties
weak var callController: CallController?
override func viewDidLoad() {
super.viewDidLoad()
view.layer.cornerRadius = 10.0
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = CGSize.init(width: 2, height: 2)
view.layer.shadowRadius = 3.5
view.layer.shadowOpacity = 0.4
contactImageContainer.makeRound()
if let callController = callController {
identityLabel.text = callController.identity
muteButton.isSelected = callController.isMuted
}
let recognizerDoubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTap))
recognizerDoubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(recognizerDoubleTap)
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
get{
return .portrait
}
}
@IBAction func muteButtonPressed(_ sender: Any) {
guard let callController = callController else {
return
}
callController.isMuted = !callController.isMuted
muteButton.isSelected = callController.isMuted
}
@IBAction func hangupButtonPressed(_ sender: Any) {
guard let callController = callController else {
return
}
callController.hangupCall()
}
@objc func doubleTap() {
guard let callController = callController else {
return
}
callController.displayDialerView()
}
}
<file_sep>/VoiceDialerSDK/VoiceDialerSDK/UI Resources/Custom Controls/RoundButton.swift
//
// RoundButton.swift
// VoiceDialerSDK
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
// TODO:
// - Make @IBDesignable
// - Add properties and mark as @IBInspectable for
// gap
// imageOnTop
// selectedButtonColor
// unselectedButtonColor ?
class RoundButton: UIButton {
override func awakeFromNib() {
makeRound()
centerImageAndText(gap: 5.0, imageOnTop: true)
}
override var bounds: CGRect {
didSet {
makeRound()
centerImageAndText(gap: 5.0, imageOnTop: true)
}
}
override var isSelected: Bool {
didSet {
self.backgroundColor = (isSelected == true ? UIColor.Buttons.Selected : UIColor.Buttons.Unselected)
}
}
// TODO: While this generally works, it doesn't quite do exactly what I want. I would like all the text for all the
// buttons to be aligned. I think we need to do a bit more work in here with the maths to make it so that it
// behaves consistently across all the buttons.
private func centerImageAndText(gap: CGFloat, imageOnTop: Bool) {
guard let imageView = self.imageView,
let titleLabel = self.titleLabel,
let _ = titleLabel.text else { return }
let sign: CGFloat = imageOnTop ? 1 : -1
let imageSize = imageView.frame.size
self.titleEdgeInsets = UIEdgeInsets(top: (imageSize.height + gap) * sign, left: -imageSize.width, bottom: 0, right: 0)
let titleSize = titleLabel.bounds.size;
self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + gap) * sign, left: 0, bottom: 0, right: -titleSize.width)
}
}
<file_sep>/VoiceDialerSDK/VoiceDialerSDK/Helpers/CallState.swift
//
// CallState.swift
// VoiceDialerSDK
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
@objc public enum CallState: Int {
case Connecting
case Ringing
case Connected
case Reconnecting
case Disconnected
}
<file_sep>/VoiceDialerSDK/VoiceDialerSDK/Helpers/CallController.swift
//
// CallController.swift
// VoiceDialerSDK
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import TwilioVoice
class CallController: NSObject {
let overlayWindow: OverlayWindow = OverlayWindow(frame: UIScreen.main.bounds)
var identity: String
var accessToken: String
var callParameters: [String : String]
var delegate: VoiceDialerDelegate?
var isMuted: Bool {
get {
guard let call = call else {
return false
}
return call.isMuted
}
set {
isMuted == false ? delegate?.callWillMute() : delegate?.callWillUmute()
call?.isMuted = newValue
}
}
var isOnHold: Bool {
get {
guard let call = call else {
return false
}
return call.isOnHold
}
set {
isOnHold == false ? delegate?.callWillHold() : delegate?.callWillResume()
call?.isOnHold = newValue
}
}
var isOnSpeaker: Bool = false {
didSet {
do {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(isOnSpeaker == true ? .speaker : .none)
} catch {
}
}
}
var callState: CallState = .Connecting {
didSet {
if let dialerViewController = dialerViewController {
dialerViewController.callState = callState
}
}
}
private var call: TVOCall?
private var connectedAt: Date?
private var timer: Timer?
// View Controllers for the various views
private var dialerViewController: DialerViewController?
private var inCallViewController: InCallViewController?
init(identity: String, accessToken: String, callParameters: [String : String], delegate: VoiceDialerDelegate?) {
self.identity = identity
self.accessToken = accessToken
self.callParameters = callParameters
self.delegate = delegate
super.init()
}
func initiateCall() {
displayDialerView()
let connectOptions = TVOConnectOptions(accessToken: accessToken) { (builder) in
builder.params = self.callParameters
}
call = TwilioVoice.connect(with: connectOptions, delegate: self)
}
func displayDialerView() {
// If we don't have the dialer view, create it
if dialerViewController == nil {
dialerViewController = VoiceDialer.storyboard().instantiateViewController(withIdentifier: "DialerViewController") as? DialerViewController
}
if let dialerViewController = dialerViewController,
let rootViewController = VoiceDialer.sharedInstance.overlayWindow.rootViewController {
let overlayWindow = VoiceDialer.sharedInstance.overlayWindow
dialerViewController.callController = self
overlayWindow.frame = UIScreen.main.bounds
VoiceDialer.sharedInstance.overlayWindow.makeKeyAndVisible()
if rootViewController.presentedViewController != nil {
rootViewController.presentedViewController?.dismiss(animated: true) {
self.inCallViewController = nil
rootViewController.present(dialerViewController, animated: true)
}
} else {
rootViewController.present(dialerViewController, animated: true)
}
}
}
func displayInCallView() {
// If we don't have the in call view, create it
if inCallViewController == nil {
inCallViewController = VoiceDialer.storyboard().instantiateViewController(withIdentifier: "InCallViewController") as? InCallViewController
}
if let inCallViewController = inCallViewController,
let rootViewController = VoiceDialer.sharedInstance.overlayWindow.rootViewController {
let overlayWindow = VoiceDialer.sharedInstance.overlayWindow
inCallViewController.callController = self
let width = UIScreen.main.bounds.width - 20
inCallViewController.view.frame = CGRect(x: 0, y: 0, width: width, height: 100)
let inCallWindowFrame = CGRect(x: 10, y: 40, width: width, height: 100)
VoiceDialer.sharedInstance.overlayWindow.makeKeyAndVisible()
if rootViewController.presentedViewController != nil {
rootViewController.presentedViewController?.dismiss(animated: true) {
overlayWindow.frame = inCallWindowFrame
self.dialerViewController = nil
rootViewController.present(inCallViewController, animated: true)
}
} else {
overlayWindow.frame = inCallWindowFrame
rootViewController.present(inCallViewController, animated: true)
}
}
}
@objc func updateConnectionDuration() {
if let connectedAt = connectedAt {
let elapsed = Date().timeIntervalSince(connectedAt)
let minutes = Int(elapsed) / 60 % 60
let seconds = Int(elapsed) % 60
let stringDuration = String(format:"%02i:%02i", minutes, seconds)
if let dialerViewController = dialerViewController {
if dialerViewController.isViewLoaded {
dialerViewController.stateLabel.text = stringDuration
}
}
if let inCallViewController = inCallViewController {
if inCallViewController.isViewLoaded {
inCallViewController.stateLabel.text = stringDuration
}
}
}
}
// MARK: - Call Actions
func hangupCall() {
delegate?.callWillHangup()
if let call = call,
call.state != .disconnected {
call.disconnect()
} else {
cleanupUI()
}
}
func cleanupUI() {
if let rootViewController = VoiceDialer.sharedInstance.overlayWindow.rootViewController {
let overlayWindow = VoiceDialer.sharedInstance.overlayWindow
// Reset the overlay window's frame so the animation works better
overlayWindow.frame = UIScreen.main.bounds
rootViewController.presentedViewController?.dismiss(animated: true, completion: {
self.dialerViewController = nil
self.inCallViewController = nil
VoiceDialer.sharedInstance.cleanupActiveCall()
})
}
}
}
extension CallController: TVOCallDelegate {
func call(_ call: TVOCall, didFailToConnectWithError error: Error) {
callState = .Disconnected
if let dialerViewController = dialerViewController {
dialerViewController.displayError(message: error.localizedDescription)
}
delegate?.callDidFailToConnect(error: error)
}
func callDidStartRinging(_ call: TVOCall) {
callState = .Ringing
delegate?.callStateDidChange(state: callState, error: nil)
}
func callDidConnect(_ call: TVOCall) {
callState = .Connected
connectedAt = Date()
let timer = Timer(timeInterval: 1.0,
target: self,
selector: #selector(updateConnectionDuration),
userInfo: nil,
repeats: true)
RunLoop.current.add(timer, forMode: .common)
self.timer = timer
delegate?.callStateDidChange(state: callState, error: nil)
displayInCallView()
}
func call(_ call: TVOCall, isReconnectingWithError error: Error) {
callState = .Reconnecting
delegate?.callStateDidChange(state: callState, error: error)
}
func callDidReconnect(_ call: TVOCall) {
callState = .Connected
delegate?.callStateDidChange(state: callState, error: nil)
}
func call(_ call: TVOCall, didDisconnectWithError error: Error?) {
callState = .Disconnected
timer?.invalidate()
timer = nil
if let error = error {
dialerViewController?.displayError(message: error.localizedDescription)
}
delegate?.callStateDidChange(state: callState, error: error)
cleanupUI()
}
}
<file_sep>/README.md
# Signal 2019 Voice Demo - Mobile VoIP contextual Calling
This repository contains an iOS project, a call orchestrator, an access token generator, and a simple JS application that demonstrate Mobile VoIP contextual Calling. It is a fictitious online shopping application (hard coded PNG order form) that Alice uses to call Agent Bob regarding her order.
To set up this demo, you will need a [Twilio](https://twilio.com) account
## TwiML App & Call Orchestration
You can use [twiml-bin-call-orchestrator.xml](twiml-bin-call-orchestrator.xml) as your call orchestrator. Simply create a TwiML bin with contents and point your TwiML App to it
## Access Token
You will need an access token for Alice (Phone App) and for Agent Bob (JS Client). Use [twilio-function-access-token.js](twilio-function-access-token.js) as your access generator. Simply create a new Twilio Function and using a browser, enter the URL with the required params as specified in the file.
## Getting started with iOS App
The `VoiceDialerSDK.framework` and `VoiceDialerSDKTester.app` are written using Swift 5.0 and Xcode 10.2.
### Dependencies
The project uses Carthage to manage the `TwilioVoice.framework` dependency. After cloning this repository, run the `carthage bootstrap` command to fetch the `TwilioVoice.framework` dependency.
### Building
Before compiling the framework and application, be sure to replace the `ACCESS_TOKEN` place holder with a valid access token for your Twilio account. For more information, take a look at Twilio's [Access Token](https://www.twilio.com/docs/voice/voip-sdk/ios/get-started#access-tokens) documentation.
## Getting started with Agent Bob's JS App
Update [quickstart.js](JSClient/quickstart.js) with Agent Bob's access token and save the file. You will now need an http server to that serves Agent Bob's Application. When Agent Bob receives a call, it will show who is calling and the order they are calling about.
<file_sep>/VoiceDialerSDK/VoiceDialerSDK/UI Resources/OverlayWindow.swift
//
// OverlayWindow.swift
// VoiceDialerSDK
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class OverlayWindow: UIWindow {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
backgroundColor = UIColor.clear
windowLevel = .statusBar - 1
rootViewController = UIViewController()
}
}
<file_sep>/VoiceDialerSDK/VoiceDialerSDK/VoiceDialerDelegate.swift
//
// VoiceDialerDelegate.swift
// VoiceDialerSDK
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
@objc public protocol VoiceDialerDelegate: AnyObject {
func callStateDidChange(state: CallState, error: Error?)
func callDidFailToConnect(error: Error)
func callWillHangup()
func callWillMute()
func callWillUmute()
func callWillHold()
func callWillResume()
}
<file_sep>/VoiceDialerSDK/VoiceDialerSDK/VoiceDialer.swift
//
// VoiceDialer.swift
// VoiceDialerSDK
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
@objc public class VoiceDialer: NSObject {
// Singleton creator
static let sharedInstance: VoiceDialer = {
let instance = VoiceDialer()
// Any other initialization as required...
return instance
}()
// MARK: - Instance properties
let overlayWindow: OverlayWindow = OverlayWindow(frame: UIScreen.main.bounds)
var callController: CallController?
@objc public class func placeCall(identity: String,
accessToken: String,
callParameters: [String : String],
delegate: VoiceDialerDelegate?) {
// If we don't have an active call, we can start one...
if sharedInstance.callController != nil {
print("Already in an active call...");
return
}
let callController = CallController(identity: identity,
accessToken: accessToken,
callParameters: callParameters,
delegate: delegate)
callController.initiateCall()
sharedInstance.callController = callController
}
@objc public class func hangupCall() {
guard let callController = sharedInstance.callController else {
return
}
callController.hangupCall()
}
func cleanupActiveCall() {
callController = nil
resetOverlayWindow()
}
private func resetOverlayWindow() {
overlayWindow.frame = UIScreen.main.bounds
overlayWindow.isHidden = true
}
class func storyboard() -> UIStoryboard {
let frameworkBundle = Bundle(for: VoiceDialer.self)
let storyboard = UIStoryboard(name: "Main", bundle: frameworkBundle)
return storyboard
}
}
<file_sep>/VoiceDialerSDK/VoiceDialerSDK/View Controllers/DialerViewController.swift
//
// DialerViewController.swift
// VoiceDialerSDK
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class DialerViewController: UIViewController {
@IBOutlet weak var contactImageContainer: UIView!
@IBOutlet weak var identityLabel: UILabel!
@IBOutlet weak var stateLabel: UILabel!
@IBOutlet weak var muteButton: RoundButton!
@IBOutlet weak var keypadButton: RoundButton!
@IBOutlet weak var speakerButton: RoundButton!
@IBOutlet weak var holdButton: RoundButton!
@IBOutlet weak var hangupButton: RoundButton!
// MARK: - Instance properties
weak var callController: CallController?
var callState: CallState = .Connecting {
didSet {
switch callState {
case .Connecting:
stateLabel.text = "Connecting..."
case .Ringing:
stateLabel.text = "Ringing..."
case .Connected:
stateLabel.text = "Connected..."
muteButton.isEnabled = true
// keypadButton.isEnabled = true
speakerButton.isEnabled = true
holdButton.isEnabled = true
case .Reconnecting:
stateLabel.text = "Reconnecting..."
muteButton.isEnabled = false
keypadButton.isEnabled = false
speakerButton.isEnabled = false
holdButton.isEnabled = false
case .Disconnected:
stateLabel.text = "Disconnected..."
muteButton.isEnabled = false
keypadButton.isEnabled = false
speakerButton.isEnabled = false
holdButton.isEnabled = false
}
}
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
get{
return .portrait
}
}
override func viewDidLoad() {
super.viewDidLoad()
contactImageContainer.makeRound()
muteButton.isEnabled = false
keypadButton.isEnabled = false
speakerButton.isEnabled = false
holdButton.isEnabled = false
if let callController = callController {
callState = callController.callState
identityLabel.text = callController.identity
// Set button states as necessary
muteButton.isSelected = callController.isMuted
holdButton.isSelected = callController.isOnHold
speakerButton.isSelected = callController.isOnSpeaker
}
let recognizerDoubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTap))
recognizerDoubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(recognizerDoubleTap)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIDevice.current.isProximityMonitoringEnabled = true
}
override func viewWillDisappear(_ animated: Bool) {
UIDevice.current.isProximityMonitoringEnabled = false
super.viewWillDisappear(animated)
}
func displayError(message: String) {
let alert = UIAlertController(title: message, message: nil, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { (action) in
self.callController?.cleanupUI()
}
alert.addAction(okAction)
self.present(alert, animated: true)
}
@IBAction func muteButtonPressed(_ sender: Any) {
guard let callController = callController else {
return
}
callController.isMuted = !callController.isMuted
muteButton.isSelected = callController.isMuted
}
@IBAction func keypadButtonPressed(_ sender: Any) {
print("Keypad button pressed!")
}
@IBAction func speakerButtonPressed(_ sender: Any) {
guard let callController = callController else {
return
}
callController.isOnSpeaker = !callController.isOnSpeaker
speakerButton.isSelected = callController.isOnSpeaker
}
@IBAction func holdButtonPressed(_ sender: Any) {
guard let callController = callController else {
return
}
callController.isOnHold = !callController.isOnHold
holdButton.isSelected = callController.isOnHold
}
@IBAction func hangupButtonPressed(_ sender: Any) {
guard let callController = callController else {
return
}
callController.hangupCall()
}
@objc func doubleTap() {
guard let callController = callController else {
return
}
if callState == .Connected {
callController.displayInCallView()
}
}
}
<file_sep>/VoiceDialerSDK/VoiceDialerSDK/UI Resources/Custom Controls/UIViewExtension.swift
//
// UIViewExtension.swift
// VoiceDialerSDK
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
extension UIView {
func makeRound() {
self.layer.cornerRadius = self.bounds.size.width / 2
}
}
<file_sep>/twilio-function-access-token.js
// The following http params are required to generate an access token:
// identity=
// apiKeySecret=
// &appSid=
// apiKeySid=
exports.handler = function(context, event, callback) {
const response = new Twilio.Response();
// Add CORS Headers
let headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Content-Type": "application/json"
};
// Set headers in response
response.setHeaders(headers);
const identity = event.identity;
const apiKeySecret = event.apiKeySecret;
const appSid = event.appSid;
const apiKeySid = event.apiKeySid;
// grab the identity from the URL
if (!identity || !apiKeySecret || !appSid || !apiKeySecret) {
response.setStatusCode(400);
callback(`Sorry, can't do, missing a required param`);
return;
}
const AccessToken = require('twilio').jwt.AccessToken;
const VoiceGrant = AccessToken.VoiceGrant;
// Create an access token which we will sign and return to the client,
// containing the grant we just created
const voiceGrant = new VoiceGrant({
// This is the TwiML app that the client will call out to. This parameter is
// required, even if the client wants to call a PSTN number directly.
outgoingApplicationSid: appSid,
// This would allow push notifications for mobile
//pushCredentialSid: null,
// This client can receive calls
incomingAllow: true
});
// Create an access token which we will sign and return to the client,
// containing the grant we just created
const token = new AccessToken(context.ACCOUNT_SID, apiKeySid, apiKeySecret);
token.addGrant(voiceGrant);
token.identity = identity;
// Include identity and token in a JSON response
response.setBody({
'identity': identity,
'token': token.toJwt()
});
response.setStatusCode(200);
callback(null, response);
}; | bf6d503715c3b093faf5d83b139ca8591fb4cafa | [
"Swift",
"JavaScript",
"Markdown"
] | 12 | Swift | paynerc/signal-2019-voip-ios | 170f14178fccaa84e3bf77be4875337459bbc670 | de4fa39df339922eae6733697e45d37f9210ab8a | |
refs/heads/master | <repo_name>zhouwei199388/CircleMenu<file_sep>/app/src/main/java/zw/com/circlemenu/MainActivity.java
package zw.com.circlemenu;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
/**
* Created by Admin on 2016/9/6.
*/
public class MainActivity extends Activity {
// private String[] mItemTexts = new String[]{"安全中心 ", "特色服务", "投资理财",
// "转账汇款", "我的账户"};
private int[] mItemImgs = new int[]{R.drawable.home_mbank_1_normal,
R.drawable.home_mbank_2_normal, R.drawable.home_mbank_3_normal,
R.drawable.home_mbank_4_normal, R.drawable.home_mbank_5_normal, R.drawable
.home_mbank_2_normal, R.drawable.home_mbank_3_normal,
R.drawable.home_mbank_4_normal, R.drawable.home_mbank_5_normal};
private zw.com.circlemenu.view.CircleMenuLayout mCircleMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCircleMenu = (zw.com.circlemenu.view.CircleMenuLayout) findViewById(R.id.menu_layout);
// mCircleMenu.setMenuItemIconsAndTexts(mItemImgs, mItemTexts);
mCircleMenu.setMenuItemLayoutId(R.layout.item_cirle_menu);
mCircleMenu.setMenuItemIconsAndTexts(mItemImgs);
mCircleMenu.setOnMenuItemClickListener(new zw.com.circlemenu.view.CircleMenuLayout
.OnMenuItemClickListener() {
@Override
public void itemClick(View view, int pos) {
// Toast.makeText(MainActivity.this, mItemTexts[pos], Toast.LENGTH_SHORT).show();
}
@Override
public void itemCenterClick(View view) {
Toast.makeText(MainActivity.this, "center view", Toast.LENGTH_SHORT).show();
}
});
// mCircleMenu.setOnMenuItemClickListener(new CircleMenuLayout.OnMenuItemClickListener() {
// @Override
// public void itemClick(View view, int pos) {
// Toast.makeText(MainActivity.this, mItemTexts[pos], Toast.LENGTH_SHORT).show();
// }
//
// @Override
// public void itemCenterClick(View view) {
// Toast.makeText(MainActivity.this, "center view", Toast.LENGTH_SHORT).show();
// }
// });
}
}
<file_sep>/Behavior/src/main/java/circlemenu/zw/com/myapplication/MainAcitivity.java
package circlemenu.zw.com.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Admin on 2016/9/22.
*/
public class MainAcitivity extends Activity {
private List<String> mList = new ArrayList<>();
private ListView mListView;
private LinearLayout mBehavior;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listview);
mBehavior = (LinearLayout) findViewById(R.id.ll_behavior);
setList();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R
.layout.simple_list_item_1, mList);
mListView.setAdapter(adapter);
}
private void setList() {
for (int i = 0; i < 30; i++) {
mList.add("张三 " + i);
}
}
}
<file_sep>/Behavior/src/main/java/circlemenu/zw/com/myapplication/StackHeadLayout.java
package circlemenu.zw.com.myapplication;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
/**
* Created by Admin on 2016/9/23.
*/
public class StackHeadLayout extends ViewGroup {
public StackHeadLayout(Context context) {
this(context, null);
}
public StackHeadLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public StackHeadLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
}
}
| ac114da509f35d1e09658c22ed84423a03d0e9ef | [
"Java"
] | 3 | Java | zhouwei199388/CircleMenu | 90149fdcf34eb19bd5c3c63dc5d17ede08f867b2 | 3bf033def8513a149f91d9858ac8e14fee784ba4 | |
refs/heads/master | <repo_name>litichevskiydv/DockerHubToTravisCiProxy<file_sep>/DockerHubToTravisCiProxy/Controllers/ProxyController.cs
namespace DockerHubToTravisCiProxy.Controllers
{
using System;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Flurl.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Models;
[Route("[controller]")]
public class ProxyController : Controller
{
private readonly ILogger<ProxyController> _logger;
private readonly TravisCiIntegrationOptions _integrationOptions;
public ProxyController(ILogger<ProxyController> logger, IOptionsSnapshot<TravisCiIntegrationOptions> options)
{
if (logger == null)
throw new ArgumentNullException(nameof(logger));
if(options == null)
throw new ArgumentNullException(nameof(options));
_logger = logger;
_integrationOptions = options.Value;
}
[HttpPost]
public async Task Post([FromBody] DockerRequest request)
{
var body = @"
{
""request"": {
""branch"":""<ImageValidatorBranch>"",
""config"": {
""env"": {
""IMAGE_TAG"": ""<ImageTag>""
}
}
}
}"
.Replace("<ImageValidatorBranch>", _integrationOptions.ImageValidatorBranch)
.Replace("<ImageTag>", request.PushData.Tag);
var labelParts = request.Repository.Dockerfile.Split('\n')
.Single(x => x.StartsWith("LABEL", StringComparison.OrdinalIgnoreCase))
.Split('/')
.Select(x => x.Trim('"'))
.ToArray();
var response =
await $"https://api.travis-ci.org/repo/{labelParts[labelParts.Length - 2]}%2F{labelParts[labelParts.Length - 1]}/requests"
.WithHeader("Accept", "application/json")
.WithHeader("Travis-API-Version", "3")
.WithHeader("Authorization", $"token {_integrationOptions.ApiKey}")
.PostAsync(new StringContent(body, Encoding.UTF8, "application/json"))
.ReceiveJson();
_logger.LogInformation($"Validation build was started for image {request.Repository.RepoName}:{request.PushData.Tag}");
}
}
}
<file_sep>/DockerHubToTravisCiProxy/Dockerfile
FROM microsoft/dotnet:1.1-runtime
LABEL name="DockerHubToTravisCiProxy"
WORKDIR /app
COPY . ./
ENV ASPNETCORE_URLS http://*:80
EXPOSE 80
ENTRYPOINT ["dotnet", "DockerHubToTravisCiProxy.dll"]
<file_sep>/DockerHubToTravisCiProxy/Startup.cs
namespace DockerHubToTravisCiProxy
{
using Controllers;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
[UsedImplicitly(ImplicitUseTargetFlags.WithMembers)]
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", false, true)
.AddEnvironmentVariables("TRAVISCIPROXY_");
Configuration = builder.Build();
}
private IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions()
.Configure<TravisCiIntegrationOptions>(
x =>
{
x.ApiKey = Configuration[nameof(TravisCiIntegrationOptions.ApiKey)];
x.ImageValidatorBranch = Configuration[nameof(TravisCiIntegrationOptions.ImageValidatorBranch)];
});
services.AddMvc()
.AddJsonOptions(x =>
{
x.SerializerSettings.ContractResolver =
new DefaultContractResolver(true)
{
NamingStrategy = new SnakeCaseNamingStrategy(true, true)
};
});
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory
.AddConsole(Configuration.GetSection("Logging"));
app.UseMvc();
}
}
}
<file_sep>/README.md
# DockerHubToTravisCiProxy
Docker Hub webhook that transfers requests to Travis CI
<file_sep>/DockerHubToTravisCiProxy/Controllers/Models/DockerRequest.cs
namespace DockerHubToTravisCiProxy.Controllers.Models
{
using JetBrains.Annotations;
[UsedImplicitly(ImplicitUseTargetFlags.WithMembers)]
public class PushDataDescription
{
public string Tag { get; set; }
}
[UsedImplicitly(ImplicitUseTargetFlags.WithMembers)]
public class RepositoryDescription
{
public string Dockerfile { get; set; }
public string RepoName { get; set; }
}
[UsedImplicitly(ImplicitUseTargetFlags.WithMembers)]
public class DockerRequest
{
public PushDataDescription PushData { get; set; }
public RepositoryDescription Repository { get; set; }
}
}<file_sep>/DockerHubToTravisCiProxy/Controllers/TravisCIIntegrationOptions.cs
namespace DockerHubToTravisCiProxy.Controllers
{
using JetBrains.Annotations;
[UsedImplicitly]
public class TravisCiIntegrationOptions
{
public string ApiKey { get; set; }
public string ImageValidatorBranch { get; set; }
}
} | 786b95bf5e7a3c1882965d4fa539a1cb1f2f00ad | [
"Markdown",
"C#",
"Dockerfile"
] | 6 | C# | litichevskiydv/DockerHubToTravisCiProxy | 07c8914f1d5d0e88abced2eea31c6888efdf7f68 | 4289b2b8c1064123acca87639c22710c51fc5dfc | |
refs/heads/master | <repo_name>TanuhaUA/Mate-hackathon<file_sep>/src/Components/BlogPage/Percentage.js
import React, { Component } from "react";
import StatisticInformation from "./StatisticInformation";
class Percentage extends Component {
render() {
return <div className='blogPage__percentage'>{ StatisticList(this.props.statistic) }</div>;
}
}
export default Percentage;
function StatisticList(statistic) {
let arr = [];
for (let key of Object.keys(statistic)) {
arr.push(
<StatisticInformation key={key} title={key} percent={statistic[key]} />
);
}
return arr;
}
<file_sep>/src/Components/Header/index.js
import React from 'react';
import { NavLink } from 'react-router-dom'
import Logo from '../Logo';
import './style.scss';
class Header extends React.Component {
render() {
return (
<header className="header">
<div className="content">
<span className="content__item logo">
<Logo color="#676767" fontSize="30px"/>
</span>
<nav className="content__item menu">
<ul className="menu__items">
<li className="menu__item"><NavLink exact to="/" activeClassName="active">
<div className="menu__anim">Home</div>
</NavLink></li>
<li className="menu__item"><NavLink to="/about" activeClassName="active">
<div className="menu__anim">About</div>
</NavLink></li>
<li className="menu__item"><NavLink to="/team" activeClassName="active">
<div className="menu__anim">Team</div>
</NavLink></li>
<li className="menu__item"><NavLink to="/services" activeClassName="active">
<div className="menu__anim">Services</div>
</NavLink></li>
<li className="menu__item"><NavLink to="/portfolio" activeClassName="active">
<div className="menu__anim">Portfolio</div>
</NavLink></li>
<li className="menu__item"><NavLink to="/blog" activeClassName="active">
<div className="menu__anim">Blog</div>
</NavLink></li>
<li className="menu__item"><NavLink to="/contact" activeClassName="active">
<div className="menu__anim">Contact</div>
</NavLink></li>
</ul>
</nav>
</div>
</header>
);
}
}
export default Header;<file_sep>/src/Components/OurSkills/Progress/index.js
import React, {Component} from 'react';
class Progress extends Component {
render() {
return (
<div className="our-skills__item">
<div className="our-skills__item-title">
<span className="our-skills__skill">{this.props.skill}</span>
<span className="our-skills__value">{this.props.value}%</span>
</div>
<progress className="our-skills__progress-bar" max="100" value={this.props.value}/>
</div>
)
}
}
export default Progress;<file_sep>/src/Components/OurTeam/index.js
import React, { Component } from 'react';
import SliderInner from './SliderInner';
import Title from '../Title'
import './style.scss';
export class OurTeam extends Component {
state = {
teamList: [],
countClicks: 0
}
componentDidMount() {
fetch('https://tanuhaua.github.io/datas-file-json/bhagaskara/team.json')
.then((response) => {
response.json().then((data) => {
this.setState({
teamList: data
});
const arr = JSON.parse(JSON.stringify(this.state.teamList));
for (let i = 0; i < arr.length; i++) {
let url = 'https://api.github.com/users/' + arr[i].githubName;
fetch(url)
.then((response) => {
response.json().then((data) => {
arr[i].avatar_url = data.avatar_url;
this.setState({
teamList: arr
});
});
});
}
});
});
}
handleClick(i) {
let {countClicks} = this.state;
this.setState({
countClicks: countClicks + i
})
}
setClick() {
this.setState({
countClicks: 0
})
}
render() {
return (
<section id="OurTeam">
<div className="wrap">
<Title title="Our" titlePurple="team" />
<div className="slider">
<div className="slider__controls">
<img
onClick={ () => {this.handleClick(1)} }
className="slider__control"
src="/img/arrow.png"
alt="arrow to switch slider of team mates"
/>
<img
onClick={ () => {this.handleClick(-1)} }
className="slider__control slider__control--reverse"
src="/img/arrow_reverse.png"
alt="arrow to switch slider of team mates"
/>
</div>
<SliderInner setClick={ this.setClick.bind(this) } countClicks={ this.state.countClicks } teamList={ this.state.teamList } />
</div>
</div>
</section>
);
}
}
export default OurTeam<file_sep>/src/Components/Features/FeatureComponent/index.js
import React from 'react';
import './style.scss';
const FeatureComponent = (props) => {
return (
<div className="feature-component__wrapper">
<div className="feature-component">
<div className="feature-component__icon">
<svg width="172" viewBox="0 0 172 186">
<path className="feature-component__hexagon"
d="M1419.57,1583.07q-20.235-12.15-40.87-23.6t-20.24-35.04q0.42-23.6,0-47.19-0.4-23.61,20.24-35.05t40.87-23.59q20.235-12.165,40.46,0t40.87,23.59q20.64,11.445,20.24,35.05-0.42,23.6,0,47.19,0.4,23.6-20.24,35.04t-40.87,23.6Q1439.8,1595.22,1419.57,1583.07Z"
transform="translate(-1354 -1408)"/>
</svg>
<svg className="feature-component__hexagon-inner-svg" width={props.hexagonInnerWidth}
viewBox={props.hexagonInnerViewbox}>
<path className="feature-component__hexagon-inner" d={props.hexagonInnerPath}
transform={props.hexagonInnerTransform}/>
</svg>
</div>
<h2 className="feature-component__headline">{props.headline}</h2>
<p className="feature-component__paragraph">Fusce facilisis velit libero, nec
dignissim lacus sagittis non.
Sed nec porta ante. Pellentesque
habitant morbi tristique senectus et.</p>
</div>
</div>
);
};
export default FeatureComponent;<file_sep>/src/Components/HomePage/index.js
import React from 'react';
import './style.scss';
import '../../Styles/main.scss';
import Logo from '../Logo';
import settings from './img/settings.png';
import bubble from './img/bubble.png';
import paperplane from './img/paperplane.png';
import pen from './img/pen.png';
import photo from './img/photo.png';
import user from './img/user.png';
import { Link } from "react-router-dom";
import Features from "../Features";
class HomePage extends React.Component {
render() {
return (
<div>
<div className="home">
<div className="home__content">
<div className="home__logo">
<Logo color='#fff' fontSize='6rem'/>
</div>
<h1 className="home__title home__title--main">Fusce rutrum pretium lorem sempter nulla</h1>
<p className="home__title home__title--sub"> lorem ipsum furcum pretium lorem septer nulla gu op dunap
sulem
lorem do burta</p>
<div className="home__icon-box">
<Link to="/about" className="home__icon">
<img className="icon__item" src={settings} alt="icon"/>
<p className="home__icon-text">About</p>
</Link>
<Link to="/team" className="home__icon">
<img className="icon__item" src={user} alt="icon"/>
<p className="home__icon-text">Team</p>
</Link>
<Link to="/services" className="home__icon">
<img className="icon__item" src={bubble} alt="icon"/>
<p className="home__icon-text">Services</p>
</Link>
<Link to="/portfolio" className="home__icon">
<img className="icon__item" src={photo} alt="icon"/>
<p className="home__icon-text">Portfolio</p>
</Link>
<Link to="/blog" className="home__icon">
<img className="icon__item" src={pen} alt="icon"/>
<p className="home__icon-text">Blog</p>
</Link>
<Link to="/contact" className="home__icon">
<img className="icon__item" src={paperplane} alt="icon"/>
<p className="home__icon-text">Contact</p>
</Link>
</div>
</div>
</div>
<Features/>
</div>
)
}
}
export default HomePage;
<file_sep>/src/Components/OurTeam/SliderInner.js
import React, { Component } from 'react';
import sizeMe from 'react-sizeme';
import './style.scss';
export class SliderInner extends Component {
state = {
moveOn: 0
}
render() {
let showItemFromTeamList = () => {
let arr = this.props.teamList,
result = [];
if (!arr[arr.length - 1]) return;
if (!arr[arr.length - 1].avatar_url) return;
for (let i = 0; i < arr.length; i++) {
result.push(
<div className="slider__item" key={ i }>
<img className="slider__photo" src={ arr[i].avatar_url } alt="photo of person from team"/>
<h3 className="slider__name">
{ arr[i].fullName }
</h3>
<p className="slider__position">
CEO / Google inc.
</p>
<div>
<a href="#" className="slider__icon">f</a>
<a href="#" className="slider__icon">g</a>
</div>
</div>
);
}
return result;
};
this.state.moveOn = this.props.size.width * this.props.countClicks;
return (
<div className="slider__inner" >
<div className="slider__slides" style={{ transform: `translateX(${ this.state.moveOn }px)` }}>
{ showItemFromTeamList() }
</div>
</div>
);
}
}
export default sizeMe()(SliderInner);
// transform: `translateX(${this.props.size.width * this.props.countClicks}px)` <file_sep>/src/Components/PortfolioPage/index.js
import React from 'react';
import './style.scss';
import PPImagesItem from '../PPImagesItem';
import Title from '../Title';
class PortfolioPage extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: false,
currentAmountOnPage: 6,
filteredData: [],
pressedTab: 'ALL',
}
}
componentDidMount() {
fetch('https://tanuhaua.github.io/datas-file-json/bhagaskara/portfolio.json')
.then(response => response.json().then(response => this.setState({
data: response,
filteredData: response,
isLoading: false,
})
))
}
handleClick() {
const {currentAmountOnPage} = this.state;
if (currentAmountOnPage + 6 > this.state.filteredData.length) {
this.setState({currentAmountOnPage: currentAmountOnPage + (this.state.filteredData.length - currentAmountOnPage)});
} else {
this.setState({currentAmountOnPage: currentAmountOnPage + 6});
}
}
handleClickByFilter(type, event) {
if (this.state.filteredData.length >= 6) {
this.setState({currentAmountOnPage: 6});
} else {
this.setState({currentAmountOnPage: this.state.filteredData.length});
}
let filteredArray = [];
this.state.data.map((item) => {
if (item.type === type) {
filteredArray.push(item);
} else if (type === 'ALL') {
filteredArray = this.state.data;
}
return filteredArray;
});
this.setState({filteredData: filteredArray, pressedTab: type});
}
render() {
const tabsNameArray = [];
const {data: dataArray, currentAmountOnPage} = this.state;
dataArray.forEach((dataArrayItem) => {
if (tabsNameArray.indexOf(dataArrayItem.type) === -1) {
tabsNameArray.push(dataArrayItem.type);
}
});
const addSixItems = () => {
const sixItems = [];
if (dataArray.length && currentAmountOnPage <= dataArray.length) {
for (let i = 0; i < currentAmountOnPage; i++) {
sixItems.push(<PPImagesItem key={i} title={dataArray[i].title} keywords={dataArray[i].keywords}
alt={dataArray[i].title} src={dataArray[i].image}/>);
}
}
return sixItems;
};
return (
<section className="portfolio-page">
<div className="portfolio-page__wrapper">
<Title title="Our" titlePurple="portfolio"/>
<ul className="portfolio-page__tabs">
<li className={'portfolio-page__tabs-item ' + (this.state.pressedTab === 'ALL' ? 'portfolio-page__tabs-item--active' : '')} onClick={(event) => this.handleClickByFilter('ALL', event)}>All</li>
{tabsNameArray.map((tabsNameArrayItem, i) => {
return <li key={i} className={'portfolio-page__tabs-item ' + (this.state.pressedTab === tabsNameArrayItem ? 'portfolio-page__tabs-item--active' : '')}
onClick={(event) => this.handleClickByFilter(tabsNameArrayItem, event)}>
{tabsNameArrayItem}</li>
})}
</ul>
<div className="portfolio-page__images">
{addSixItems()}
</div>
{this.state.currentAmountOnPage !== this.state.filteredData.length ? <button className="portfolio-page__button" type="button" onClick={this.handleClick.bind(this)}>Watch more
</button> : null}
</div>
</section>
)
}
}
export default PortfolioPage;<file_sep>/src/Components/ContactPage/index.js
import React from 'react';
import './style.scss';
import Logo from '../Logo';
import Title from '../Title';
class ContactPage extends React.Component {
constructor (props) {
super(props);
this.state = {
email: '',
formErrors: {email: ''},
emaildValid: false,
formValid: true
}
}
handleUserInput = (e) => {
const name = e.target.name;
const value = e.target.value;
this.setState({[name]: value}, () => { this.validateField(name, value)});
};
validateField(fieldName, value) {
const fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
switch(fieldName) {
case 'email':
emailValid = value.match(/^([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,6}$/i);
break;
default:
break;
}
this.setState({formErrors: fieldValidationErrors,
emailValid: emailValid,
}, this.validateForm);
}
validateForm() {
this.setState({formValid: this.state.emailValid});
}
render() {
return (
<div className="contact">
<div className="wrapper">
<Title
title={'Get'}
titlePurple={'in touch'}
/>
<div className="contact-block">
<div className="contact-form">
<form method="POST" action="#">
<div className="contact-form__name">
<input type="text" className="contact-form__control" name="text" placeholder="Your Name" required/>
</div>
<div className="contact-form__email">
<input type="email" className="contact-form__control" name="email" placeholder="Your Email" required value={this.state.email} onChange={this.handleUserInput}/>
{!this.state.formValid && (
<p className="contact-form__error">Email is not valid</p>
)}
</div>
<div className="contact-form__message">
<textarea name="comment" cols="23" rows="10" className="contact-form__control"placeholder="Your Message" required></textarea>
</div>
<button type="submit" className="contact-form__btn" onClick={function(e){e.preventDefault()}}>
Send Email
</button>
</form>
</div>
<div className="contact-info">
<p className="contact-info__text">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.
</p>
<p className="contact-info__details">
1600 Pennsylvania Ave NW, Washington, <br/>
DC 20500, United States of America.
</p>
<p className="contact-info__details">
T: (202) 456-1111 <br/>
M: (202) 456-1212
</p>
<div className="contact-info">
<a href="#" className="contact-info__social">f</a>
<a href="#" className="contact-info__social">t</a>
<a href="#" className="contact-info__social">g</a>
</div>
</div>
</div>
<Logo color='#676767' fontSize='50px'/>
</div>
</div>
);
}
}
export default ContactPage;<file_sep>/src/Components/PPImagesItem/index.js
import React from 'react';
import './style.scss';
class PPImagesItem extends React.Component {
render() {
return (
<div className="portfolio-page__images-item">
<div className="portfolio-page__image-wrapper">
<img className="portfolio-page__image" src={this.props.src} alt={this.props.title} />
</div>
<p className="portfolio-page__images-title">{this.props.title}</p>
<p className="portfolio-page__images-keywords">{this.props.keywords}</p>
</div>
)
}
}
export default PPImagesItem; | 0bb8b1b001d78ad337fcddd3973ab7c1e365d054 | [
"JavaScript"
] | 10 | JavaScript | TanuhaUA/Mate-hackathon | 23fb4314ccc135fbabb5128d830be84fef67d238 | eaae3da39af9a9af81a88b97b7bbfb2dd3466ac1 | |
refs/heads/master | <repo_name>franleplant/css-flex-gap-patch<file_sep>/src/App.js
import './App.css';
function App() {
return (
<div className="">
<div className="example">
<div className="container-a">
<div className="item-a"></div>
<div className="item-a"></div>
<div className="item-a"></div>
<div className="item-a"></div>
<div className="item-a"></div>
<div className="item-a"></div>
</div>
</div>
<div className="example">
<div className="container-b">
<div className="item-b"></div>
<div className="item-b"></div>
<div className="item-b"></div>
<div className="item-b"></div>
<div className="item-b"></div>
<div className="item-b"></div>
</div>
</div>
</div>
);
}
export default App;
| 87af9be83a4b28baa50c4f938ed11deedf03a0c9 | [
"JavaScript"
] | 1 | JavaScript | franleplant/css-flex-gap-patch | 23ff0ce150614cbb5222ddbb4b1acf8eef0dfcb5 | 82dbff8968a2e41c8848582c87fbb85ac015e065 | |
refs/heads/master | <repo_name>laihaibo/react-swiper<file_sep>/src/containers/Swiper.js
import React, {Component} from 'react';
// import CSSTransition from 'react-transition-group/CSSTransition';
import data from '../static/data';
import Figure from '../components/Figure';
import Fade from '../components/Fade';
import '../static/css/swiper.css';
class Swiper extends Component {
constructor(props) {
super(props);
this.state = {
current: data[5],
data,
animate: {},
show: false
};
this.onPrev = this
.onPrev
.bind(this);
this.onNext = this
.onNext
.bind(this);
this.onSetCurrent = this
.onSetCurrent
.bind(this);
}
onPrev() {
let current = this.state.current;
let currentIndex = this
.state
.data
.map((obj, index) => ({
...obj,
index
}))
.filter(obj => obj.id === current.id)[0]
.index;
let prevIndex = currentIndex === 0
? this.state.data.length - 1
: --currentIndex;
this.setState((prevState) => ({
current: prevState.data[prevIndex],
show: !prevState.show,
animate: {
appear: 'animated',
appearActive: 'flip',
enter: 'animated',
enterActive: 'fadeInLeft',
exit: 'animated',
exitActive: 'fadeOutRight'
}
}));
}
onNext() {
let current = this.state.current;
let currentIndex = this
.state
.data
.map((obj, index) => ({
...obj,
index
}))
.filter(obj => obj.id === current.id)[0]
.index;
let nextIndex = currentIndex === this.state.data.length - 1
? 0
: ++currentIndex;
this.setState((prevState) => ({
current: prevState.data[nextIndex],
show: !prevState.show,
animate: {
appear: 'animated',
appearActive: 'flip',
enter: 'animated',
enterActive: 'fadeInRight',
exit: 'animated',
exitActive: 'fadeOutLeft'
}
}));
}
onSetCurrent(id) {
this.setState((prevState) => ({
current: prevState.data[id],
show: !prevState.show,
animate: {
appear: 'animated',
appearActive: 'flip',
enter: 'animated',
enterActive: 'fadeInRight',
exit: 'animated',
exitActive: 'fadeOutLeft'
}
}));
}
render() {
return (
<div className="swiper">
<div className="control-left" onClick={this.onPrev}>prev</div>
<div className="rollbar">
<Fade in={this.state.show} classNames={this.state.animate}>
<Figure {...this.state.current}/>
</Fade>
<div className="ballbar">
{this
.state
.data
.map(ball => <div
style={{
background: ball.id === this.state.current.id
? 'red'
: '#ccc'
}}
onClick={() => this.onSetCurrent(ball.id)}
className="ball"
key={ball.id}/>)}
</div>
</div>
<div className="control-right" onClick={this.onNext}>next</div>
</div>
);
}
}
export default Swiper;<file_sep>/README.md
# react-swiper
a swiper by react
<file_sep>/src/components/Fade.js
import React from 'react';
import CSSTransition from 'react-transition-group/CSSTransition';
const Fade = ({
children,
...props
}) => (
<CSSTransition {...props} timeout={500}>
{children}
</CSSTransition>
);
export default Fade; | 62cc49418e5bc544b2255b824ec65dc16e0b3200 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | laihaibo/react-swiper | b43825d9bda529fcc043e64478089aad19c9217d | 79bd7f3fe06619d3a426ffd7bbc6b719a4f83669 | |
refs/heads/main | <file_sep>my_board = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' '}
board_keys = []
for key in my_board:
board_keys.append(key)
def print_board(board):
"""Prints board on console to start the game. """
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['1'] + '|' + board['2'] + '|' + board['3'])<file_sep>from board import my_board, print_board, board_keys
def game():
turn = 'X'
count = 0
for i in range(10):
print_board(my_board)
print("It's your turn," + turn + ".Move to which place?")
move = input()
if my_board[move] == " ":
my_board[move] = turn
count += 1
else:
print("That place is already taken.\nMove to which place? ")
continue
# check if player X or O has won,for every move after 5 moves.
if count >= 5:
if my_board['7'] == my_board['8'] == my_board['9'] != ' ': # across the top
print_board(my_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif my_board['4'] == my_board['5'] == my_board['6'] != ' ': # across the middle
print_board(my_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif my_board['1'] == my_board['2'] == my_board['3'] != ' ': # across the bottom
print_board(my_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif my_board['1'] == my_board['4'] == my_board['7'] != ' ': # down the left side
print_board(my_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif my_board['2'] == my_board['5'] == my_board['8'] != ' ': # down the middle
print_board(my_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif my_board['3'] == my_board['6'] == my_board['9'] != ' ': # down the right side
print_board(my_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif my_board['7'] == my_board['5'] == my_board['3'] != ' ': # diagonal
print_board(my_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
elif my_board['1'] == my_board['5'] == my_board['9'] != ' ': # diagonal
print_board(my_board)
print("\nGame Over.\n")
print(" **** " + turn + " won. ****")
break
# IF neither X nor 0 wins and the board if full, we'll declare the result as tie.
if count == 9:
print("\nGame Over.\n")
print("It's a Tie!!")
# Change player after every move.
if turn == "X":
turn = "O"
else:
turn = 'X'
restart = input("Do you want to play again?(y/n)")
if restart in 'yY':
for key in board_keys:
my_board[key] = " "
game()
if __name__ == "__main__":
game()
<file_sep># Games in Python3
A bunch of classic games I created using python3
| de9895770f8ec87b5fe150e150862d4c0b136e84 | [
"Markdown",
"Python"
] | 3 | Python | asanmateu/games-py | a3d92c5c4b83e70f8c518fe03059507abfa8ccda | da7fc142860fc9481d1f59f91e8b312765214b63 | |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\SiteContato;
use App\MotivoContato;
class ContatoController extends Controller
{
public function contato(Request $request)
{
$motivo_contato = MotivoContato::all();
return view('site.contato', ['motivo_contato' => $motivo_contato]);
}
public function salvar(Request $request)
{
$regras = [
'nome' => 'required|min:3|max:40|unique:site_contatos', //minimo 3, maximo 40 e verifica se já há um nome igual no formulário
'telefone' => 'required',
'email' => 'required|email',
'motivo_contatos_id' => 'required',
'mensagem' => 'required|max:2000'
];
$feedback = [
'required' => 'O campo :attribute precisa ser preenchido',
'nome.min' => 'O campo nome precisa ter no mínimo 3 caracteres',
'nome.max' => 'O campo nome precisa ter no máximo 40 caracteres',
'nome.unique' => 'Nome já em uso',
'email.email' => 'Email inválido',
'mensagem.max' => 'A mensagem deve ter no máximo 2000 caracteres'
];
//validar os dados do formulário
$request->validate($regras, $feedback);
SiteContato::create($request->all());
return redirect()->route('site.index');
}
}
| 6507540f0550b848a82525f1d090d74c0176ef28 | [
"PHP"
] | 1 | PHP | pedrocavt/sistema-gestao | e2c634cf00457ee9920ba4480aab8959a959fed5 | 9c24197e28140dc3daaf75eaff2b7f4273bca7a7 | |
refs/heads/master | <file_sep>WordsUtility = function(sentence){
this.countWords = function(){
return sentence.split(" ").length;
}
this.averageWordLength = function(){
var words = sentence.split(" ");
var sameLetter = sentence.indexOf("c");
for (var i = 0; i>sentence.length; i++)
{
sameLetter = words[i];
}
return sameLetter;
}
this.wordsWithTheSameLength = function(){
}
this.shortestWord = function(){
var mine = sentence.split(" ");
var shortestWord = mine[mine.length-1];
//var mine=sentence.split(" ");
for(i =0; i < mine.length; i++){
if(shortestWord.length > mine[i].length){
shortestWord =mine[i];
}
}
return shortestWord + shortestWord.length;
}
this.longestWord = function(){
var mine = sentence.split(" ");
var longestWord = "";
var mine=sentence.split(" ");
for(i =0; i < mine.length; i++){
if(longestWord.length < mine[i].length){
longestWord = mine[i];
}
}
return longestWord + longestWord.length;
};
this.whatLetterDoesTheMostWordsStartWith = function(){
}
this.whatLetterDoesTheMostWordsEndWith = function(){
}
this.noWordsWithTheSameLength = function(){
}
}
| 62f19e1811ed5c6c7394b648ba2d6ee8789ac326 | [
"JavaScript"
] | 1 | JavaScript | denvereezy/codeX_ProgrammingExercises | e40f20c025ec4ef51b7d5a06f2beb66ce77b34a3 | 554fdd29e00e2863432e01eeaebd3296dfb63de2 | |
refs/heads/master | <file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.jtlv.env.module;
import net.sf.javabdd.BDDDomain;
import net.sf.javabdd.BDDException;
import net.sf.javabdd.BDDVarSet;
/**
* <p>
* JTLVBDDField is an object representing a field variable in JTLV environment.
* On one hand, this object encapsulate the BDD domain, which does not
* necessarily have two boolean values. On the other hand, this object also
* encapsulate both prime and unprime versions of the variables.
* </p>
*
* @version {@value edu.wis.jtlv.env.Env#version}
* @author <NAME>.
*
*/
public class ModuleBDDField extends ModuleEntity {
/**
* <p>
* The domain of this field.
* </p>
*/
protected BDDDomain main;
/**
* <p>
* Identify whether this field is the prime or the unprime version of the
* field.
* </p>
*/
protected boolean is_prime;
/**
* <p>
* The other version of this field. i.e., if this is the unprime version
* then this.pair is the prime one, and wise versa.
* </p>
*/
protected ModuleBDDField pair;
private int traceId;
/**
* <p>
* The main public constructor for JTLVBDDField. Given a name, a
* domain, and a corresponding domain, a new BDD field is created with a
* corresponding prime version of the field.
* </p>
*
* @param unprime
* The domain to which we are constructing a field.
* @param prime
* The other corresponding domain.
* @param name
* A name for this field.
*
* @see edu.wis.jtlv.env.Env#newVar(String, String)
* @see edu.wis.jtlv.env.Env#newVar(String, String, int)
*/
public ModuleBDDField(BDDDomain unprime, BDDDomain prime,
String name) {
this.main = unprime;
this.main.setName(name);
this.name = name;
this.is_prime = false;
this.pair = new ModuleBDDField(prime, this, name + "'");
}
/**
* <p>
* The corresponding private constructor for creating the prime version of
* the field.
* </p>
*
* @param prime
* The domain to which we are constructing a field.
* @param main_pair
* The other JTLVBDDField which has invoked this instance.
* @param name
* A name for this field.
*
* @see edu.wis.jtlv.env.module.ModuleBDDField#JTLVBDDField(BDDDomain,
* BDDDomain, String, String)
*/
private ModuleBDDField(BDDDomain prime, ModuleBDDField main_pair,
String name) {
this.main = prime;
this.main.setName(name);
this.name = name;
this.is_prime = true;
this.pair = main_pair;
}
/**
* <p>
* Return the other version of the field, regardless of which instance this
* is.
* </p>
*
* @return The other version of the field.
*
* @see edu.wis.jtlv.env.module.ModuleBDDField#prime()
* @see edu.wis.jtlv.env.module.ModuleBDDField#unprime()
*/
public ModuleBDDField other() {
return this.pair;
}
/**
* <p>
* Get the prime version of this field.
* </p>
*
* @return The prime version of this field.
* @throws BDDException
* If this is a prime version of the field.
*
* @see edu.wis.jtlv.env.module.ModuleBDDField#other()
* @see edu.wis.jtlv.env.module.ModuleBDDField#unprime()
*/
public ModuleBDDField prime() throws BDDException {
if (is_prime) {
throw new BDDException("Cannot prime primed variables.");
}
return this.other();
}
/**
* <p>
* Get the unprime version of this field.
* </p>
*
* @return The unprime version of this field.
* @throws BDDException
* If this is an unprime version of the field.
*
* @see edu.wis.jtlv.env.module.ModuleBDDField#other()
* @see edu.wis.jtlv.env.module.ModuleBDDField#prime()
*/
public ModuleBDDField unprime() throws BDDException {
if (!is_prime) {
throw new BDDException("Cannot unprime unprimed variables.");
}
return this.other();
}
/**
* <p>
* Get the set of BDD variables which construct the domain for this field.
* </p>
*
* @return The set of BDD variables.
*/
public BDDVarSet support() {
// return this.getDomain().set();
return this.getDomain().ithVar(0).support();
}
/**
* <p>
* Check whether this is a prime version of the field representation.
* </p>
*
* @return true if this is the prime version of the field, false otherwise.
*/
public boolean isPrime() {
return is_prime;
}
/**
* <p>
* Getter for the domain of this field.
* </p>
*
* @return The domain of this field.
*
* @see edu.wis.jtlv.env.module.ModuleBDDField#getOtherDomain()
*/
public BDDDomain getDomain() {
return this.main;
}
/**
* <p>
* Getter for the domain of the other corresponding field.
* </p>
*
* @return The domain of the other corresponding field.
*
* @see edu.wis.jtlv.env.module.ModuleBDDField#getDomain()
*/
public BDDDomain getOtherDomain() {
return this.other().getDomain();
}
/**
* <p>
* Check whether this object's domain is comparable to the give object
* domain.
* </p>
*
* @param other
* The other object to compare this filed to.
* @return true if the given object's domain is comparable to this domain,
* false otherwise.
*
* @see edu.wis.jtlv.env.module.ModuleBDDField#equals(Object)
* @see edu.wis.jtlv.env.module.ModuleBDDField#strongEquals(Object)
*/
public boolean comparable(ModuleBDDField other) {
return this.getDomain().size().equals((other.getDomain().size()));
}
public int getTraceId() {
return traceId;
}
public void setTraceId(int traceId) {
this.traceId = traceId;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinputtrans.translator;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import tau.smlab.syntech.gameinput.model.Constraint;
import tau.smlab.syntech.gameinput.model.GameInput;
import tau.smlab.syntech.gameinput.model.Variable;
import tau.smlab.syntech.gameinput.spec.Operator;
import tau.smlab.syntech.gameinput.spec.Spec;
import tau.smlab.syntech.gameinput.spec.SpecExp;
import tau.smlab.syntech.gameinput.spec.VariableReference;
public class ArrayFunctionsTranslator implements Translator {
private static final Map<Operator, Operator> ARRAY_TO_UNIT_OPERATORS = Collections.unmodifiableMap(new HashMap<Operator, Operator>() {{
put(Operator.SUM_OF, Operator.ADD);
put(Operator.PROD_OF, Operator.MULTIPLY);
put(Operator.AND_OF, Operator.AND);
put(Operator.OR_OF, Operator.OR);
}});
@Override
public void translate(GameInput input) {
// guarantees
for (Constraint c : input.getSys().getConstraints()) {
c.setSpec(replaceArrayOperators(c.getSpec(), c.getTraceId()));
}
// assumptions
for (Constraint c : input.getEnv().getConstraints()) {
c.setSpec(replaceArrayOperators(c.getSpec(), c.getTraceId()));
}
}
private Spec replaceArrayOperators(Spec spec, int traceId) {
if (spec instanceof SpecExp) {
SpecExp specExp = (SpecExp) spec;
Operator arrayOp = specExp.getOperator();
if (ARRAY_TO_UNIT_OPERATORS.containsKey(arrayOp) && (specExp.getChildren()[0] instanceof VariableReference)) {
VariableReference array = (VariableReference) specExp.getChildren()[0];
Spec newSpec = new VariableReference(new Variable(array.getReferenceName() + "[0]", array.getVariable().getType()));
for (int index = 1; index < array.getIndexDimensions().get(0); index++) {
VariableReference currentElement = new VariableReference(new Variable(array.getReferenceName()+ "["+ index +"]", array.getVariable().getType()));
newSpec = new SpecExp(ARRAY_TO_UNIT_OPERATORS.get(arrayOp), currentElement, newSpec);
}
return newSpec;
} else {
for (int i = 0; i < specExp.getChildren().length; i++) {
specExp.getChildren()[i] = replaceArrayOperators(specExp.getChildren()[i], traceId);
}
}
}
return spec;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.gr1;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.jtlv.Env;
public class GR1GameBuilder {
public static GR1Game getDefault(GameModel model, int energyBound) {
boolean hasADD = Env.getBDDPackageInfo().contains("CUDDADDFactory");
if (hasADD) {
return new GR1GameEnergyADD(model, energyBound);
} else {
// in this case BDDGenerator took care of reduction already; we use regular GR1
return getDefault(model);
}
}
public static GR1Game getDefault(GameModel model) {
// are we using pure Java? (this check also works correctly if the user chose a
// native CUDD but Java is as fallback)
boolean hasJNI = !Env.getBDDPackageInfo().contains("JTLVJavaFactory");
// use GR(1)* synthesis
if (model.getSys().existReqNum() > 0) {
if (hasJNI) {
return new GR1StarGameImplC(model);
} else {
new GR1StarGameMemoryless(model);
}
}
if (hasJNI) {
return new GR1GameImplC(model);
}
return new GR1GameExperiments(model);
}
/**
* Enable/disable optimization (if true, not all winning states are calculated!)
*
* TODO the current way this works is very ugly refactor this and make it not
* static all over
*
* @param b
*/
public static void stopWhenInitialsLost(boolean b) {
GR1GameExperiments.STOP_WHEN_INITIALS_LOST = b;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.checks;
import java.util.ArrayList;
import java.util.List;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.lib.FixPoint;
/**
* assuming the user has an unrealizable spec this check will determine whether it makes sense to add assumptions that
* allow "good" executions: where the environment can satisfy all assumptions and where the system can satisfy all
* guarantees
*
* This gives no guarantee that a corresponding strategy exists.
*
*/
public class CouldAsmHelp {
/**
* assuming the user has an unrealizable spec this check will determine whether it makes sense to add assumptions that
* allow "good" executions: where the environment can satisfy all assumptions and where the system can satisfy all
* guarantees
*
* This gives no guarantee that a corresponding strategy exists.
*
* @param m
* the game model with both players
* @return true if there is a common way to satisfy asms and gars
*/
public static boolean couldAsmHelp(GameModel m) {
BDD ini = m.getSys().initial().and(m.getEnv().initial());
BDD trans = m.getSys().trans().and(m.getEnv().trans());
List<BDD> buchis = new ArrayList<BDD>();
for (int i = 0; i < m.getSys().justiceNum(); i++) {
buchis.add(m.getSys().justiceAt(i));
}
for (int i = 0; i < m.getEnv().justiceNum(); i++) {
buchis.add(m.getEnv().justiceAt(i));
}
if (buchis.isEmpty()) {
buchis.add(Env.TRUE());
}
boolean commonSat = commonGeneralizedBuchiRealizable(ini, trans, buchis);
ini.free();
trans.free();
return commonSat;
}
/**
* compute a cooperative solution to the generalized Buchi game
*
* @param ini
* @param trans
* @param buchis
* @return
*/
private static boolean commonGeneralizedBuchiRealizable(BDD ini, BDD trans, List<BDD> buchis) {
BDD Z = Env.TRUE();
FixPoint zFix = new FixPoint(true);
while (zFix.advance(Z)) {
Z = Z.id();
for (BDD buchi : buchis) {
BDD start = buchi.id().andWith(Env.pred(trans, Z));
BDD nextZ = Z.id().andWith(reachBwd(trans, start));
Z.free();
Z = nextZ;
start.free();
BDD iniWin = ini.and(Z);
if (iniWin.isZero()) {
iniWin.free();
return false;
}
iniWin.free();
}
}
return true;
}
/**
* compute all backwards reachable states
*
* @param trans
* @param to
* @return
*/
public static BDD reachBwd(BDD trans, BDD to) {
BDD attr = Env.FALSE(); // no states
FixPoint f = new FixPoint(true);
while (f.advance(attr)) {
attr = to.id().orWith(Env.pred(trans, attr));
}
return attr;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinputtrans.translator;
import tau.smlab.syntech.gameinput.model.Constraint;
import tau.smlab.syntech.gameinput.model.GameInput;
import tau.smlab.syntech.gameinput.model.TriggerConstraint;
import tau.smlab.syntech.gameinput.model.WeightDefinition;
import tau.smlab.syntech.gameinput.spec.Operator;
import tau.smlab.syntech.gameinput.spec.Spec;
import tau.smlab.syntech.gameinput.spec.SpecExp;
import tau.smlab.syntech.gameinput.spec.SpecRegExp;
import tau.smlab.syntech.gameinput.spec.VariableReference;
import tau.smlab.syntech.gameinputtrans.TranslationException;
/**
* should be run only after all past LTL, predicates, patterns, and defines have
* been instantiated
*
* will only translate primes in main specifications
*/
public class PrimesTranslator implements Translator {
@Override
public void translate(GameInput input) {
for (Constraint c : input.getSys().getConstraints()) {
c.setSpec(replacePrimes(c.getSpec(), c.getTraceId()));
}
for (TriggerConstraint c : input.getSys().getTriggers()) {
c.setSpec(detectPrimes(c.getInitSpecRegExp(), c.getTraceId()));
c.setSpec(detectPrimes(c.getEffectSpecRegExp(), c.getTraceId()));
}
for (Constraint c : input.getEnv().getConstraints()) {
c.setSpec(replacePrimes(c.getSpec(), c.getTraceId()));
}
for (Constraint c : input.getAux().getConstraints()) {
c.setSpec(replacePrimes(c.getSpec(), c.getTraceId()));
}
for (WeightDefinition wd : input.getWeightDefs()) {
wd.getDefinition().setSpec(replacePrimes(wd.getDefinition().getSpec(), wd.getDefinition().getTraceId()));
}
}
/**
* look for prime operators and replace them
*
* @param spec
* @return
*/
private Spec replacePrimes(Spec spec, int traceId) {
if (spec instanceof SpecExp) {
SpecExp e = (SpecExp) spec;
if (Operator.PRIME.equals(e.getOperator())) {
Spec pSpec = primeVarAllReferences(e.getChildren()[0], traceId);
return replacePrimes(pSpec, traceId);
} else {
for (int i = 0; i < e.getChildren().length; i++) {
e.getChildren()[i] = replacePrimes(e.getChildren()[i], traceId);
}
}
}
return spec;
}
/**
* detect primes in triggers if there are any left after predicate translations
* @param spec
* @param traceId
* @return
*/
private Spec detectPrimes(Spec spec, int traceId) {
if (spec instanceof SpecRegExp) {
SpecRegExp e = (SpecRegExp) spec;
detectPrimes(e.getPredicate(), traceId);
detectPrimes(e.getLeft(), traceId);
detectPrimes(e.getRight(), traceId);
} else if (spec instanceof SpecExp) {
SpecExp e = (SpecExp) spec;
if (Operator.PRIME.equals(e.getOperator())) {
throw new TranslationException("Regular expressions can't have primed ('next') variables", traceId);
} else {
for (int i = 0; i < e.getChildren().length; i++) {
detectPrimes(e.getChildren()[i], traceId);
}
}
}
return spec;
}
/**
* replace reference names with primed versions
*
* @param spec
*/
private Spec primeVarAllReferences(Spec spec, int traceId) {
if (spec instanceof VariableReference) {
String refName = ((VariableReference) spec).getReferenceName();
if (refName.endsWith("'")) {
throw new TranslationException("Cannot prime primed variable.", traceId);
}
return new VariableReference(((VariableReference) spec).getVariable(), refName + "'");
} else if (spec instanceof SpecExp) {
SpecExp e = (SpecExp) spec;
for (int i = 0; i < e.getChildren().length; i++) {
e.getChildren()[i] = primeVarAllReferences(e.getChildren()[i], traceId);
}
}
return spec;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.sfa;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.sfa.SFA.Pair;
/**
* @author <NAME>
* @author <NAME>
*
*/
public class PowerSetIterator {
private PowerSetIterator() {};
public static enum PowerSetIteratorType {
DEFAULT, EFFICIENT;
}
/**
* Returns an iterator that iterates over the powerset of the given set of SFA transitions. Each element in
* the iteration is an (ordered) Pair object whose left component is a transitions' subset {@code t} and whose right component is a satisfiable BDD {@code b} that encodes
* the conjunction of all transitions' guards in {@code t}. Subsets {@code t} where {@code b} is unsatisfiable (i.e., where {@code b} is the FALSE BDD), do not occur in the iteration.
*
* @param type
* @param transitionsSet
* @return
*/
public static <T extends SFAState> Iterator<Pair<Set<Map.Entry<T, BDD>>, BDD>>
getIterator(PowerSetIteratorType type, Set<Map.Entry<T, BDD>> transitionsSet) {
if(type.equals(PowerSetIteratorType.DEFAULT)) {
return new DefaultPowerSetIterator<T>(transitionsSet);
}
if(type.equals(PowerSetIteratorType.EFFICIENT)) {
return new EfficientPowerSetIterator<T>(transitionsSet);
}
return null;
}
/**
* A class for constructing a lazy powerset iterator over sets of SFA
* transitions. The iterator uses a binary counter to keep track of the subsets' enumeration.
* The iterator only generates transitions' subsets whose transition formulas'
* conjunction is satisfiable.
*/
private static class DefaultPowerSetIterator<T extends SFAState> implements Iterator<Pair<Set<Map.Entry<T, BDD>>, BDD>>{
private List<Map.Entry<T, BDD>> transitionsSetList;
private boolean[] nextSubsetBinaryList;
private Set<Map.Entry<T, BDD>> nextSubset = new HashSet<>();
private BDD nextSubsetBDD, nextNextSubsetBDD;
private Set<Map.Entry<T, BDD>> nextNextSubset = new HashSet<>();
DefaultPowerSetIterator(Set<Map.Entry<T, BDD>> transitionsSet) {
this.transitionsSetList = new ArrayList<>(transitionsSet);
this.nextSubsetBinaryList = new boolean[transitionsSet.size()];
this.nextNextSubsetBDD = Env.TRUE();
}
@Override
public boolean hasNext() {
if (this.nextNextSubset == null) {
return false;
}
return true;
}
@Override
public Pair<Set<Map.Entry<T, BDD>>, BDD> next() {
if (!this.hasNext()) {
return null;
}
this.nextSubset.clear();
this.nextSubset.addAll(this.nextNextSubset);
this.nextSubsetBDD = this.nextNextSubsetBDD;
do {
for (int i = 0; i < this.nextSubsetBinaryList.length; ++i) {
this.nextSubsetBinaryList[i] = !this.nextSubsetBinaryList[i];
if (this.nextSubsetBinaryList[i]) {
break;
}
}
this.nextNextSubset.clear();
if(this.nextNextSubsetBDD.isZero()) {
this.nextNextSubsetBDD.free();
}
this.nextNextSubsetBDD = Env.TRUE();
for (int i = 0; i < this.transitionsSetList.size(); ++i) {
if (this.nextSubsetBinaryList[i]) {
this.nextNextSubset.add(this.transitionsSetList.get(i));
this.nextNextSubsetBDD.andWith(this.transitionsSetList.get(i).getValue().id());
if(this.nextNextSubsetBDD.isZero()) {
break;
}
}
}
if (this.nextNextSubset.isEmpty()) {
this.nextNextSubset = null;
this.nextNextSubsetBDD.free();
break;
}
} while(this.nextNextSubsetBDD.isZero());
return new Pair<Set<Map.Entry<T, BDD>>, BDD>(this.nextSubset, this.nextSubsetBDD);
}
}
/**
* A class for constructing a lazy powerset iterator over sets of SFA
* transitions. The iterator only generates transitions' subsets whose transition formulas'
* conjunction is satisfiable. The iterator generates transitions' subsets with a non-decreasing cardinality. In addition, it applies pruning as an optimization. That is,
* it does not look at proper supersets of a set which has already been explored and the conjunction of its transitions' formulas is unsatisfiable.
*
*/
private static class EfficientPowerSetIterator<T extends SFAState> implements Iterator<Pair<Set<Map.Entry<T, BDD>>, BDD>> {
private List<Map.Entry<T, BDD>> transitionsSetList;
private int nextTransitionsSetListIdx = 0;
private Set<Map.Entry<T, BDD>> nextSubset = new HashSet<>(), nextNextSubset = new HashSet<>();
private BDD nextSubsetBDD, nextNextSubsetBDD;
private int currPrevSizeSubsetIdx = 0; //the current index of the subset (of size N) that we try to extend with an additional element
private List<List<Integer>> prevSizeSubsetsIndices = new ArrayList<>(); //each list contains the transitions' indices in each subset of size N
private List<List<Integer>> currSizeSubsetsIndices = new ArrayList<>(); //each list contains the transitions' indices in each subset of size N+1
private List<BDD> prevSizeSubsetsBDDs = new ArrayList<>(); //each BDD is the conjunction of all transitions in the corresponding subset of size N
private List<BDD> currSizeSubsetsBDDs = new ArrayList<>(); //each BDD is the conjunction of all transitions in the corresponding subset of size N+1
EfficientPowerSetIterator(Set<Map.Entry<T, BDD>> transitionsSet) {
this.transitionsSetList = new ArrayList<>(transitionsSet);
this.prevSizeSubsetsIndices.add(new ArrayList<>());
this.nextNextSubsetBDD = Env.TRUE();
this.prevSizeSubsetsBDDs.add(Env.TRUE());
}
/*
* This method is basically a flat (iterative) version of a recursive method
* that generates lazily all SATISFIABLE transition subsets of growing size, and
* their formulas' BDD conjunction. Once there are no satisfiable subsets left,
* null is returned.
*
*/
@Override
public Pair<Set<Map.Entry<T, BDD>>, BDD> next() {
if(!this.hasNext()) {
return null;
}
this.nextSubset.clear();
this.nextSubset.addAll(this.nextNextSubset);
this.nextSubsetBDD = this.nextNextSubsetBDD;
Pair<Set<Map.Entry<T, BDD>>, BDD> nextPair = new Pair<>(this.nextSubset, this.nextSubsetBDD);
List<Integer> nextNextSubsetIndices, currPrevSizeSubsetIndices;
while(true) {
while (this.nextTransitionsSetListIdx < this.transitionsSetList.size()) {
this.nextNextSubsetBDD = this.prevSizeSubsetsBDDs.get(this.currPrevSizeSubsetIdx)
.and(this.transitionsSetList.get(this.nextTransitionsSetListIdx).getValue());
if(this.nextNextSubsetBDD.isZero()) {
this.nextNextSubsetBDD.free();
this.nextTransitionsSetListIdx++;
}
else {
//the BDD of the next next subset is not FALSE, so keep it to consider (in the future) proper supersets thereof
this.currSizeSubsetsBDDs.add(this.nextNextSubsetBDD.id());
//create the list of the transitions' indices which are in the next next transitions subset
nextNextSubsetIndices = new ArrayList<>();
nextNextSubsetIndices.addAll(this.prevSizeSubsetsIndices.get(this.currPrevSizeSubsetIdx));
nextNextSubsetIndices.add(this.nextTransitionsSetListIdx);
this.currSizeSubsetsIndices.add(nextNextSubsetIndices);
//increment the index of the transition which should be added next to the transitions subset
this.nextTransitionsSetListIdx++;
//compute the next next transitions subset (nextNextSubset) from its indices list (nextNextSubsetIndices)
this.nextNextSubset.clear();
for(int transIdx : nextNextSubsetIndices) {
this.nextNextSubset.add(this.transitionsSetList.get(transIdx));
}
return nextPair;
}
}
/*
*
* At this point, we have created all possible (satisfiable) supersets (of size N+1) of the current transitions subset of size N
* (which in this.prevSizeSubsetsIndices[this.currPrevSizeSubsetIdx]). Thus, we proceed to this.currPrevSizeSubsetIdx+1.
* If that's impossible, i.e., (this.currPrevSizeSubsetIdx+1) == this.prevSizeSubsetsIndices.size(), we clear and insert to this.prevSizeSubsetsIndices the indices
* lists in this.currSizeSubsetsIndices.
*
* */
this.currPrevSizeSubsetIdx++;
if(this.currPrevSizeSubsetIdx == this.prevSizeSubsetsIndices.size()) {
Env.free(this.prevSizeSubsetsBDDs); //free all previously stored BDDs
this.prevSizeSubsetsBDDs.clear(); //remove all previously stored BDD objects
this.prevSizeSubsetsIndices.clear(); //remove all previously stored transitions subsets' indices lists
if(this.currSizeSubsetsIndices.isEmpty()) { //there are no transitions' indices lists whose supersets should be generated next -> we are done!
this.setIsExhausted(); //mark that the iterator is exhausted
break;
}
//we have that this.currSizeSubsetsIndices is not empty
this.prevSizeSubsetsIndices.addAll(this.currSizeSubsetsIndices); //insert to this.prevSizeSubsetsIndices all the indices lists in this.currSizeSubsetsIndices
this.prevSizeSubsetsBDDs.addAll(this.currSizeSubsetsBDDs); //insert to this.prevSizeSubsetsBDDs all the BDDs in this.currSizeSubsetsBDDs
this.currPrevSizeSubsetIdx = 0; //reset the index of the subset that we try to extend with an additional element
//clear current subsets indices and BDDs
this.currSizeSubsetsIndices.clear();
this.currSizeSubsetsBDDs.clear();
}
//set this.nextTransitionsSetListIdx according to the current transitions' indices subset that we try to extend
//the next value of this.nextTransitionsSetListIdx should be equal to [maximal (last) index element in this.prevSizeSubsetsIndices.get(this.currPrevSizeSubsetIdx)] + 1
currPrevSizeSubsetIndices = this.prevSizeSubsetsIndices.get(this.currPrevSizeSubsetIdx);
this.nextTransitionsSetListIdx = currPrevSizeSubsetIndices.get(currPrevSizeSubsetIndices.size()-1)+1;
}
return nextPair;
}
@Override
public boolean hasNext() {
if (this.nextNextSubset == null) {
return false;
}
return true;
}
private void setIsExhausted() {
this.nextNextSubset = null;
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.checks;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDVarSet;
import tau.smlab.syntech.checks.ddmin.AbstractDdmin;
import tau.smlab.syntech.checks.ddmin.DdminUNSAT;
import tau.smlab.syntech.gameinput.model.Constraint;
import tau.smlab.syntech.gameinput.spec.Spec;
import tau.smlab.syntech.gameinput.spec.SpecExp;
import tau.smlab.syntech.gameinput.spec.SpecTraceable;
import tau.smlab.syntech.gameinput.spec.VariableReference;
import tau.smlab.syntech.gameinputtrans.translator.CounterTranslator;
import tau.smlab.syntech.gameinputtrans.translator.MonitorTranslator;
import tau.smlab.syntech.gameinputtrans.translator.PastLTLTranslator;
import tau.smlab.syntech.gamemodel.BehaviorInfo;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.gamemodel.PlayerModule;
import tau.smlab.syntech.games.controller.symbolic.SymbolicController;
import tau.smlab.syntech.jtlv.CoreUtil;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.env.module.ModuleBDDField;
/**
* some non-trivial checks on the BDD level
*
* @author ringert
*
*/
public class Checker {
private PlayerModule sys;
private PlayerModule env;
private String[] monitorCheckMessages;
private String[] counterCheckMessages;
/**
* Computes a subset of initial and safety system constraints that allow the environment to deadlock the system on its initial
* move. <br>
*
* @param m
* @return null if no deadlock can occur
*/
public List<BehaviorInfo> computeIniDeadlockCore(GameModel model, List<String> l) {
env = model.getEnv();
sys = model.getSys();
BDD sysDead = sys.initial().id().impWith(env.controlStates(sys, Env.FALSE()));
BDD envKillSys = env.initial().id().andWith(sysDead.forAll(sys.moduleUnprimeVars()));
sysDead.free();
if (envKillSys.isZero()) {
return null;
}
envKillSys.free();
return new AbstractDdmin<BehaviorInfo>() {
@Override
protected boolean check(List<BehaviorInfo> part) {
BDD iniPart = Env.TRUE();
part.stream().filter(p -> p.isInitial()).forEach(p -> iniPart.andWith(p.initial.id()));
BDD transPart = Env.TRUE();
part.stream().filter(p -> p.isSafety()).forEach(p -> transPart.andWith(p.safety.id()));
PlayerModule partSys = new PlayerModule();
partSys.conjunctTrans(transPart);
// initial states where the environment can force system to deadlock
BDD sysDead = iniPart.impWith(env.controlStates(partSys, Env.FALSE()));
partSys.free();
// initial environment assignment that can deadlock the system
BDD envKillSys = env.initial().id().andWith(sysDead.forAll(sys.moduleUnprimeVars()));
boolean win = !envKillSys.isZero();
if (win) {
BDD e = envKillSys.exist(sys.modulePrimeVars());
BDD e1 = e.exist(sys.moduleUnprimeVars());
e.free();
if (e1.isOne()) {
l.add("Any initial assignment.");
} else {
l.add(Env.toNiceSignleLineString(e1));
}
e1.free();
}
envKillSys.free();
return win;
}
}.minimize(
model.getSysBehaviorInfo().stream().filter(p -> p.isInitial() || p.isSafety()).collect(Collectors.toList()));
}
/**
* Computes reachable states (most permissive environment and system) and checks if justices can be reached. <br>
* This is a heuristics because it assumes environment and system to be only restricted by their safeties and not by
* any strategy.
*
* @param model
* @return
*/
public List<BehaviorInfo> computeUnreachableJustice(GameModel model) {
env = model.getEnv();
sys = model.getSys();
List<BehaviorInfo> unreachableJustice = new ArrayList<>();
// compute reachable states, which are not immediate deadlocks for the system
BDD reach = Env.allSucc(env.initial().and(sys.initial()), env.trans().and(sys.trans()));
BDD dead = env.controlStates(sys, Env.FALSE());
reach.andWith(dead.not());
dead.free();
for (BehaviorInfo bi : model.getSysBehaviorInfo()) {
if (bi.isJustice()) {
BDD tmp = bi.justice.and(reach);
if (tmp.isZero()) {
unreachableJustice.add(bi);
}
tmp.free();
}
}
for (BehaviorInfo bi : model.getEnvBehaviorInfo()) {
if (bi.isJustice()) {
BDD tmp = bi.justice.and(reach);
if (tmp.isZero()) {
unreachableJustice.add(bi);
}
tmp.free();
}
}
reach.free();
return unreachableJustice;
}
/**
* computes a minimal unsatisfiable subset of constraints INI or SAFETY
*
* @param model
* @return
*/
public List<BehaviorInfo> computeUnsatSafetyCore(GameModel model) {
sys = model.getSys();
DdminUNSAT cc = new DdminUNSAT();
if (sys.initial().isZero()) {
List<BehaviorInfo> inis = new ArrayList<>();
for (BehaviorInfo bi : model.getSysBehaviorInfo()) {
if (bi.isInitial()) {
inis.add(bi);
}
}
return cc.minimize(inis);
} else if (sys.trans().isZero()) {
List<BehaviorInfo> safeties = new ArrayList<>();
for (BehaviorInfo bi : model.getSysBehaviorInfo()) {
if (bi.isInitial() || bi.isSafety()) {
safeties.add(bi);
}
}
return cc.minimize(safeties);
}
env = model.getEnv();
if (env.initial().isZero()) {
List<BehaviorInfo> inis = new ArrayList<>();
for (BehaviorInfo bi : model.getEnvBehaviorInfo()) {
if (bi.isInitial()) {
inis.add(bi);
}
}
return cc.minimize(inis);
} else if (env.trans().isZero()) {
List<BehaviorInfo> safeties = new ArrayList<>();
for (BehaviorInfo bi : model.getEnvBehaviorInfo()) {
if (bi.isInitial() || bi.isSafety()) {
safeties.add(bi);
}
}
return cc.minimize(safeties);
}
return new ArrayList<>();
}
/**
* checks constraints whether they are trivially TRUE or FALSE
*
* @param model
* @return
*/
public List<BehaviorInfo> computeTrivialSpecs(GameModel model) {
List<BehaviorInfo> infos = new ArrayList<>();
infos.addAll(model.getSysBehaviorInfo());
infos.addAll(model.getEnvBehaviorInfo());
infos.addAll(model.getAuxBehaviorInfo());
List<BehaviorInfo> trivial = new ArrayList<>();
for (BehaviorInfo bi : infos) {
if (bi.getBdd().isZero() || bi.getBdd().isOne()) {
trivial.add(bi);
}
}
return trivial;
}
/**
* Checks whether there are illegal assumptions: initial assumptions with system variables or any primes, or safety
* assumptions with any system primes.
*
* @param model
* @return
*/
public List<BehaviorInfo> computeEnvBadPrimesSpecs(GameModel model) {
List<BehaviorInfo> infos = new ArrayList<>();
infos.addAll(computeBadIniPrimesSpecs(model));
infos.addAll(computeEnvBadIniSysSpec(model));
infos.addAll(computeEnvBadSafetyPrimesSpecs(model));
return infos;
}
/**
* Checks whether there are illegal assumptions: initial assumptions with system variables.
*
* @param model
* @return
*/
public List<BehaviorInfo> computeEnvBadIniSysSpec(GameModel model) {
sys = model.getSys();
env = model.getEnv();
List<BehaviorInfo> infos = new ArrayList<>();
BDDVarSet primes = Env.globalPrimeVars();
// initial assumptions may not have system variables
if (Env.hasVars(env.initial(), sys.moduleUnprimeVars())) {
// check whether BehaviorInfo was created
if (model.getEnvBehaviorInfo().isEmpty()) {
infos.add(new BehaviorInfo(env.initial(), null, null, null, null, 0, false));
} else {
for (BehaviorInfo bi : model.getEnvBehaviorInfo()) {
if (bi.isInitial() && Env.hasVars(bi.initial, sys.moduleUnprimeVars())) {
infos.add(bi);
}
}
}
}
primes.free();
return infos;
}
/**
* Checks whether there are illegal assumptions: initial assumptions with any primes.
*
* @param model
* @return
*/
public List<BehaviorInfo> computeBadIniPrimesSpecs(GameModel model) {
sys = model.getSys();
env = model.getEnv();
List<BehaviorInfo> infos = new ArrayList<>();
BDDVarSet primes = Env.globalPrimeVars();
// initial assumptions may not have primed variables
if (Env.hasVars(env.initial(), primes)) {
// check whether BehaviorInfo was created
if (model.getEnvBehaviorInfo().isEmpty()) {
infos.add(new BehaviorInfo(env.initial(), null, null, null, null, 0, false));
} else {
for (BehaviorInfo bi : model.getEnvBehaviorInfo()) {
if (bi.isInitial() && Env.hasVars(bi.initial, primes)) {
infos.add(bi);
}
}
}
}
primes.free();
return infos;
}
/**
* Checks whether there are illegal assumptions: safety assumptions with any system primes.
*
* @param model
* @return
*/
public List<BehaviorInfo> computeEnvBadSafetyPrimesSpecs(GameModel model) {
sys = model.getSys();
env = model.getEnv();
List<BehaviorInfo> infos = new ArrayList<>();
// safety assumptions may not have primed system variables
if (Env.hasVars(env.trans(), sys.modulePrimeVars())) {
// check whether BehaviorInfo was created
if (model.getEnvBehaviorInfo().isEmpty()) {
infos.add(new BehaviorInfo(null, env.trans(), null, null, null, 0, false));
} else {
for (BehaviorInfo bi : model.getEnvBehaviorInfo()) {
if (bi.isSafety() && Env.hasVars(bi.safety, sys.modulePrimeVars())) {
infos.add(bi);
}
}
}
}
return infos;
}
public List<BehaviorInfo> computeSysBadPrimesSpecs(GameModel model) {
sys = model.getSys();
env = model.getEnv();
List<BehaviorInfo> infos = new ArrayList<>();
BDDVarSet primes = Env.globalPrimeVars();
if (Env.hasVars(sys.initial(), primes)) {
// check whether BehaviorInfo was created
if (model.getSysBehaviorInfo().isEmpty()) {
infos.add(new BehaviorInfo(sys.initial(), null, null, null, null, 0, false));
} else {
for (BehaviorInfo bi : model.getSysBehaviorInfo()) {
if (bi.isInitial() && Env.hasVars(bi.initial, primes)) {
infos.add(bi);
}
}
}
}
primes.free();
return infos;
}
public Map<Integer, Set<BehaviorInfo>> computeTraceIdtoBIMap(GameModel gm) {
Map<Integer, Set<BehaviorInfo>> traceIdToBehaviorInfo = new HashMap<>();
Set<BehaviorInfo> biSet;
for (BehaviorInfo bi : gm.getAuxBehaviorInfo()) {
if (traceIdToBehaviorInfo.containsKey(bi.traceId)) {
biSet = traceIdToBehaviorInfo.get(bi.traceId);
} else {
biSet = new HashSet<>();
traceIdToBehaviorInfo.put(bi.traceId, biSet);
}
biSet.add(bi);
}
return traceIdToBehaviorInfo;
}
/**
* Fills in for the specified monitor monName the following info:
* (1) Behavior info of initial and safety constraints (in initialConstraints and safetyConstraints).
* (2) Behavior info of PAST initial and safety constraints, i.e, which were created during the PAST translation,
* (in pastInitialConstraints and pastSafetyConstraints).
* (3) A list of the PAST variable references (in monNameToVarRefs).
*/
public void fillMonitorConstraints(GameModel gm,
String monName,
MonitorTranslator monTranslator,
PastLTLTranslator pastTranslator,
Map<Integer, Set<BehaviorInfo>> traceIdToBehaviorInfo,
Map<String, Set<BehaviorInfo>> safetyConstraints,
Map<String, Set<BehaviorInfo>> initialConstraints,
Map<String, Set<BehaviorInfo>> pastSafetyConstraints,
Map<String, Set<BehaviorInfo>> pastInitialConstraints,
Map<String, Set<VariableReference>> monNameToVarRefs) {
Set<BehaviorInfo> biSet;
for (Integer traceId : monTranslator.getTraceIdsOfMonitor(monName)) {
biSet = traceIdToBehaviorInfo.get(traceId);
for (BehaviorInfo bi : biSet) {
if (bi.isInitial()) {
addConstraintToMonitor(initialConstraints, monName, bi);
} else if (bi.isSafety()) {
addConstraintToMonitor(safetyConstraints, monName, bi);
}
}
}
List<Constraint> monPastConstraints = new ArrayList<>();
for (Constraint c : monTranslator.getMonitorConstraints(monName)) {
monPastConstraints.addAll(
getPastConstraints(monName, c.getSpec(), pastTranslator, monNameToVarRefs));
}
for (Constraint c : monPastConstraints) {
biSet = traceIdToBehaviorInfo.get(c.getTraceId());
for (BehaviorInfo bi : biSet) {
if (bi.isInitial()) {
if (!initialConstraints.get(monName).contains(bi)) {
addConstraintToMonitor(pastInitialConstraints, monName, bi);
}
} else if (bi.isSafety()) {
if (!safetyConstraints.get(monName).contains(bi)) {
addConstraintToMonitor(pastSafetyConstraints, monName, bi);
}
}
}
}
}
private Set<Constraint> getPastConstraints(String monName, Set<Constraint> cons, PastLTLTranslator pastTranslator,
Map<String, Set<VariableReference>> monNameToVarRefs) {
Set<Constraint> all = new HashSet<>(cons);
for (Constraint c : cons) {
all.addAll(getPastConstraints(monName, c.getSpec(), pastTranslator, monNameToVarRefs));
}
return all;
}
private Set<Constraint> getPastConstraints(String monName, Spec spec,
PastLTLTranslator pastTranslator,
Map<String, Set<VariableReference>> monNameToVarRefs) {
if (spec instanceof VariableReference) {
VariableReference varRef = (VariableReference) spec;
//we need to maintain a mapping of a monitor name to variables of a monitor
if (pastTranslator.getConstraintsOfVarRef(varRef) != null) {
Set<VariableReference> monVarRefs;
if (monNameToVarRefs.containsKey(monName)) {
monVarRefs = monNameToVarRefs.get(monName);
} else {
monVarRefs = new HashSet<>();
monNameToVarRefs.put(monName, monVarRefs);
}
monVarRefs.add(varRef);
return getPastConstraints(monName, new HashSet<Constraint>(pastTranslator.getConstraintsOfVarRef(varRef)),
pastTranslator, monNameToVarRefs);
}
}
if (spec instanceof SpecExp) {
SpecExp se = (SpecExp) spec;
Set<Constraint> childrenConstraints = new HashSet<>();
for (int i = 0; i < se.getChildren().length; i++) {
childrenConstraints.addAll(getPastConstraints(monName,
se.getChildren()[i], pastTranslator, monNameToVarRefs));
}
return childrenConstraints;
}
return new HashSet<>();
}
/**
* Returns the behavior info list of the specified monitor monName.
*
* @param monName
* @param safetyConstraints
* @param initialConstraints
* @return
*/
private List<BehaviorInfo> getMonitorSpecList(String monName,
Map<String, Set<BehaviorInfo>> safetyConstraints,
Map<String, Set<BehaviorInfo>> initialConstraints) {
List<BehaviorInfo> monitorSpecs = new ArrayList<>();
if (safetyConstraints != null && safetyConstraints.containsKey(monName)) {
monitorSpecs.addAll(safetyConstraints.get(monName));
}
if (initialConstraints != null && initialConstraints.containsKey(monName)) {
monitorSpecs.addAll(initialConstraints.get(monName));
}
return monitorSpecs;
}
public List<BehaviorInfo> checkMonitorsForCompleteness(GameModel gm, MonitorTranslator monitorTranslator,
PastLTLTranslator pastLTLTranslator) {
List<BehaviorInfo> result;
Map<Integer, Set<BehaviorInfo>> traceIdtoBI = computeTraceIdtoBIMap(gm); //Note that the same traceId may have multiple Behavior infos
Map<String, Set<BehaviorInfo>> safetyConstraints = new HashMap<>();
Map<String, Set<BehaviorInfo>> pastSafetyConstraints = new HashMap<>();
Map<String, Set<BehaviorInfo>> pastInitialConstraints = new HashMap<>();
Map<String, Set<BehaviorInfo>> initialConstraints = new HashMap<>();
Map<String, Set<VariableReference>> monNameToVarRefs = new HashMap<>();
for (String monName : monitorTranslator.getMonitorsNames()) {
fillMonitorConstraints(gm, monName, monitorTranslator, pastLTLTranslator, traceIdtoBI,
safetyConstraints, initialConstraints, pastSafetyConstraints, pastInitialConstraints, monNameToVarRefs);
//check for completeness
// build a symbolic controller from the monitor's definition
SymbolicController symCtrl = new SymbolicController();
symCtrl.initial().free();
symCtrl.trans().free();
symCtrl.setTrans(Env.TRUE());
if (safetyConstraints.containsKey(monName)) {
for (BehaviorInfo bi : safetyConstraints.get(monName)) {
symCtrl.conjunctTransWith(bi.safety.id());
}
}
if (pastSafetyConstraints.containsKey(monName)) {
for (BehaviorInfo bi : pastSafetyConstraints.get(monName)) {
symCtrl.conjunctTransWith(bi.safety.id());
}
}
BDD initials = Env.TRUE();
if (initialConstraints.containsKey(monName)) {
for (BehaviorInfo bi : initialConstraints.get(monName)) {
initials.andWith(bi.initial.id());
}
}
if (pastInitialConstraints.containsKey(monName)) {
for (BehaviorInfo bi : pastInitialConstraints.get(monName)) {
initials.andWith(bi.initial.id());
}
}
symCtrl.setInit(initials);
result = performMonitorCompletenessCheck(gm, monName, monNameToVarRefs.get(monName), symCtrl, safetyConstraints,
initialConstraints);
if (!result.isEmpty()) {
return result;
}
}
// if we have reached here, the monitor has passed the check
return new ArrayList<>();
}
private void addConstraintToMonitor(Map<String, Set<BehaviorInfo>> constraints,
String parentMonitor, BehaviorInfo bi) {
Set<BehaviorInfo> constraintSet;
if (constraints.containsKey(parentMonitor)) {
constraintSet = constraints.get(parentMonitor);
} else {
constraintSet = new HashSet<>();
constraints.put(parentMonitor, constraintSet);
}
constraintSet.add(bi);
}
private List<BehaviorInfo> performMonitorCompletenessCheck(GameModel m, String monitorName,
Set<VariableReference> pastVarlist, SymbolicController ctrl,
Map<String, Set<BehaviorInfo>> safetyConstraints,
Map<String, Set<BehaviorInfo>> initialConstraints) {
// handling domain information
BDD doms = m.getSys().getDoms().and(m.getEnv().getDoms());
BDD domsIni = doms.exist(Env.globalPrimeVars());
ctrl.initial().andWith(domsIni.id());
ctrl.conjunctTrans(doms);
// 1) check that all initial assignments to all unprimed variables minus
// the monitor's (aux) variable(s) have a corresponding initial state in the monitor's controller
ModuleBDDField monVar = Env.getVar(monitorName);
//VarSets of unprimed and primed past aux variables. These may exists if there
//are past expressions in the monitor definition.
BDDVarSet monAuxSet = Env.getEmptySet(), primeMonAuxSet = Env.getEmptySet();
if (pastVarlist != null) {
ModuleBDDField monAuxVar;
for (VariableReference varRef : pastVarlist) {
monAuxVar = Env.getVar(varRef.getReferenceName());
monAuxSet.unionWith(monAuxVar.getDomain().set());
primeMonAuxSet.unionWith(monAuxVar.getOtherDomain().set());
}
}
BDDVarSet unprimedMonSet = monVar.getDomain().set().unionWith(monAuxSet);
BDDVarSet primedMonSet = monVar.getOtherDomain().set().unionWith(primeMonAuxSet);
BDDVarSet unprimedGloalMinusMonSet = Env.globalUnprimeVars().minus(unprimedMonSet);
BDDVarSet primedGloalMinusMonSet = Env.globalPrimeVars().minus(primedMonSet);
BDD ctrlIni = ctrl.initial().exist(unprimedMonSet);
BDD result = domsIni.imp(ctrlIni).forAll(unprimedGloalMinusMonSet);
if (!result.isOne()) {
result.free();
unprimedGloalMinusMonSet.free();
primedGloalMinusMonSet.free();
primedMonSet.free();
unprimedMonSet.free();
String[] errorMsg = new String[2];
errorMsg[0] = monitorName;
BDDVarSet nonAuxVars = Env.union(m.getSys().getNonAuxFields()).union(Env.union(m.getEnv().getNonAuxFields()));
errorMsg[1] = CoreUtil.satOne(domsIni.and(ctrlIni.not()), nonAuxVars).toStringWithDomains(Env.stringer);
ctrlIni.free();
this.setMonitorCheckMessages(errorMsg);
nonAuxVars.free();
return getMonitorSpecList(monitorName, null, initialConstraints);
}
result.free();
// 2) check that for all reachable states in the monitor controller it is enabled
// for all next assignments to all to all primed variables minus
// the monitor's (aux) variable
BDD reachable = Env.allSucc(ctrl.initial().id(), ctrl.trans());
BDD ctrlTrans = ctrl.trans().exist(primedMonSet);
result = reachable.and(doms).imp(ctrlTrans).forAll(Env.globalUnprimeVars().union(Env.globalPrimeVars()));
if (!result.isOne()) {
String[] errorMsg = new String[2];
BDDVarSet nonAuxVars = Env.union(m.getSys().getNonAuxFields()).union(Env.union(m.getEnv().getNonAuxFields()));
errorMsg[0] = monitorName;
errorMsg[1] = CoreUtil.satOne(reachable.and(doms).and(ctrlTrans.not()), nonAuxVars)
.toStringWithDomains(Env.stringer);
this.setMonitorCheckMessages(errorMsg);
ctrlTrans.free();
nonAuxVars.free();
}
Map<String, Set<BehaviorInfo>> safetiesToMark = (result.isOne() ? null : safetyConstraints);
result.free();
reachable.free();
unprimedGloalMinusMonSet.free();
primedGloalMinusMonSet.free();
primedMonSet.free();
unprimedMonSet.free();
return getMonitorSpecList(monitorName, safetiesToMark, null);
}
public void setMonitorCheckMessages(String[] messages) {
this.monitorCheckMessages = messages;
}
public String[] getMonitorCheckMessages() {
return this.monitorCheckMessages;
}
//////////////////////////
// --- Counters checks ---
//////////////////////////
public List<BehaviorInfo> checkCountersConsistency(GameModel gm, CounterTranslator counterTranslator) {
Map<Integer, Set<BehaviorInfo>> traceIdtoBI = computeTraceIdtoBIMap(gm);
for (String counterName : counterTranslator.getCountersNames()) {
List<SpecTraceable> inconstentPredicates = getInconstentCounterPredicates(gm, counterName, counterTranslator, traceIdtoBI);
if (inconstentPredicates.size() > 0) {
List<BehaviorInfo> result = new ArrayList<BehaviorInfo>();
for (SpecTraceable pred : inconstentPredicates) {
Set<BehaviorInfo> behaviorInfos = traceIdtoBI.get(pred.getTraceId());
result.addAll(behaviorInfos);
}
return result;
}
}
return new ArrayList<BehaviorInfo>();
}
private List<SpecTraceable> getInconstentCounterPredicates(GameModel gm, String counterName,
CounterTranslator counterTranslator, Map<Integer, Set<BehaviorInfo>> traceIdtoBI) {
List<SpecTraceable> predicates = counterTranslator.getCounterPredicates(counterName);
PlayerModule env = gm.getEnv();
PlayerModule sys = gm.getSys();
BDD reachableStates = Env.allSucc(env.initial().and(sys.initial()), env.trans().and(sys.trans()));
List<BDD> predicatesBdds = new ArrayList<BDD>();
for (SpecTraceable pred : predicates) {
for (BehaviorInfo bi : traceIdtoBI.get(pred.getTraceId())) {
predicatesBdds.add(bi.getBdd().id());
}
}
try {
for (int i = 0; i < predicates.size(); i++) {
for (int j = i + 1; j < predicates.size(); j++) {
SpecTraceable p1 = predicates.get(i);
SpecTraceable p2 = predicates.get(j);
BDD p1ReachableStates = predicatesBdds.get(i);
BDD p2ReachableStates = predicatesBdds.get(j);
BDD reachableAndP1 = p1ReachableStates.and(reachableStates).exist(Env.globalPrimeVars());
BDD reachableAndP2 = p2ReachableStates.and(reachableStates).exist(Env.globalPrimeVars());
BDD intersection = reachableAndP1.and(reachableAndP2);
reachableAndP1.free();
reachableAndP2.free();
if (!intersection.isZero()) {
BDDVarSet nonAuxVars = Env.union(sys.getNonAuxFields()).union(Env.union(env.getNonAuxFields()));
String[] errorMsg = new String[2];
errorMsg[0] = counterName;
errorMsg[1] = CoreUtil.satOne(intersection, nonAuxVars).toStringWithDomains(Env.stringer);
this.setCounterCheckMessages(errorMsg);
List<SpecTraceable> intersectingPredicates = new ArrayList<SpecTraceable>();
intersectingPredicates.add(p1);
intersectingPredicates.add(p2);
return intersectingPredicates;
}
intersection.free();
}
}
return new ArrayList<SpecTraceable>();
} finally {
for (BDD bdd : predicatesBdds) {
bdd.free();
}
reachableStates.free();
}
}
public void setCounterCheckMessages(String[] messages) {
this.counterCheckMessages = messages;
}
public String[] getCounterCheckMessages() {
return this.counterCheckMessages;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.symbolic;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;
/**
* characterization of a set of possible controllers
*
* default: initial = FALSE and trans = FALSE
*
* @author ringert
*
*/
public class SymbolicController {
private BDD initial = Env.FALSE();
private BDD trans = Env.FALSE();
public SymbolicController() {
}
/**
* creates a new controller from given BDDs (consumed)
*
* @param ini (consumed)
* @param trans (consumed)
*/
public SymbolicController(BDD ini, BDD trans) {
this.initial = ini;
this.trans = trans;
}
/**
*
* @return direct reference to BDD that describes inital states
*/
public BDD initial() {
return initial;
}
/**
* sets the inital states
*
* @param init is used (don't modify or free)
*/
public void setInit(BDD init) {
this.initial = init;
}
/**
*
* @return direct reference to BDD that describes transitions
*/
public BDD trans() {
return trans;
}
/**
* sets the transitions
*
* @param trans is used (don't modify or free)
*/
public void setTrans(BDD trans) {
this.trans = trans;
}
/**
* adds moreTrans as a disjunction to current transitions
*
* @param moreTrans (BDD not freed)
*/
public void disjunctTrans(BDD moreTrans) {
trans.orWith(moreTrans.id());
}
public void disjunctTransWith(BDD moreTrans) {
trans.orWith(moreTrans);
}
/**
* restricts trans of controller to trans2
*
* @param moreTrans (BDD not freed)
*/
public void conjunctTrans(BDD trans2) {
trans.andWith(trans2.id());
}
public void conjunctTransWith(BDD trans2) {
trans.andWith(trans2);
}
/**
* <p>
* This procedure return all states which the controller can reach in a single
* step from given a set of state.
* </p>
*
* @param from The set of state to start from.
* @return The set of states which the controller can reach in a single step
* from the given states.
*/
public BDD succ(BDD from) {
return Env.succ(from, trans);
}
public BDD pred(BDD to) {
return Env.pred(trans, to);
}
@Override
public String toString() {
String ret = "Initial states:\n";
ret += Env.toNiceString(initial);
ret += "\n\nTransitions:\n";
ret += Env.toNiceString(trans);
return ret;
}
public void free() {
initial.free();
trans.free();
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.modelchecker;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;;
/**
* An exception dedicated for counter examples.
*/
public class CounterExampleException extends ModelCheckException {
private static final long serialVersionUID = 1L;
private BDD[] path;
public CounterExampleException(String desc, BDD[] path) {
super(desc);
this.path = path;
}
public BDD[] getPath() {
return this.path;
}
public String toString() {
String res = super.toString() + "\n";
if ((path == null) || (path.length == 0))
return res + "No Counter Example Exists.";
res += " Counter Example\n";
res += "=================\n";
// the last is not printed. It is only to point to the cycle.
BDD last = path[path.length - 1];
int loop_index = -1;
boolean loop_exists = false;
for (int i = 0; i < path.length - 1; i++) {
boolean loop_here = path[i].biimp(last).isOne();
if ((loop_here) && (loop_index == -1)) {
loop_index = i + 1;
res += "[[" + (i + 1) + "]]";
loop_exists = true;
} else {
res += " " + (i + 1) + " ";
}
res += " \t: " + Env.toNiceSignleLineString(path[i]) + "\n";
}
if (loop_exists)
res += "Loop back to state " + loop_index;
else
res += " " + path.length + " \t: "
+ Env.toNiceSignleLineString(path[path.length - 1]) + "\n";
return res;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// BDDBitVector.java, created Jul 14, 2003 9:50:57 PM by jwhaley
// Copyright (C) 2003 <NAME>
// Licensed under the terms of the GNU LGPL; see COPYING for details.
// Note: re-written to support vectors operations of different lengths and of a negative sign in Oct - Nov, 2016.
package net.sf.javabdd;
import java.math.BigInteger;
/**
* <p>Bit vector implementation for BDDs.</p>
*
* @author <NAME>
* @version $Id: BDDBitVector.java,v 1.2 2009/10/18 19:30:54 uid228351 Exp $
*/
public abstract class BDDBitVector {
protected BDD[] bitvec;
protected BDD sign;
/**
* Creates a new BDDBitVector instance of the specified length. The new vector is not initialized. However, the sign BDD is
* initialized to zero, i.e., a positive sign.
* @param bitnum the length (number of bits) of the new BDDBitVector.
*/
protected BDDBitVector(int bitnum) {
bitvec = new BDD[bitnum];
sign = this.getFactory().zero();
}
/**
* Creates a new BDDBitVector instance initialized with the specified value.
* The vector's length is sufficient for the bit representation of the specified value
* and equals to {@code floor(log_2(val))+1}. If {@code val} holds a value out of the range of {@code long} type, the
* new vector would have the value of 0.
*
* @param val the value which the new BDDBitVector holds.
*/
protected BDDBitVector(BigInteger val) {
long lVal;
int bitnum = 0;
try {
lVal = val.longValueExact();
}
catch (ArithmeticException ae) {
lVal = 0;
}
long sVal = lVal;
if(lVal < 0) {
sVal = -lVal;
}
do {
bitnum++;
sVal >>= 1;
}
while(sVal != 0);
bitvec = new BDD[bitnum];
sign = this.getFactory().zero();
initialize(lVal);
}
protected void initialize(boolean isTrue) {
BDDFactory bdd = getFactory();
for (int n = 0; n < bitvec.length; n++)
if (isTrue)
bitvec[n] = bdd.one();
else
bitvec[n] = bdd.zero();
}
protected void initialize(int val) {
BDDFactory bdd = getFactory();
if(val < 0) {
sign.free();
sign = bdd.one();
}
for (int n = 0; n < bitvec.length; n++) {
if ((val & 0x1) != 0)
bitvec[n] = bdd.one();
else
bitvec[n] = bdd.zero();
val >>= 1;
}
}
protected void initialize(long val) {
BDDFactory bdd = getFactory();
if(val < 0) {
sign.free();
sign = bdd.one();
}
for (int n = 0; n < bitvec.length; n++) {
if ((val & 0x1) != 0)
bitvec[n] = bdd.one();
else
bitvec[n] = bdd.zero();
val >>= 1;
}
}
protected void initialize(BigInteger val) {
BDDFactory bdd = getFactory();
if(val.intValue() < 0) {
sign.free();
sign = bdd.one();
}
for (int n = 0; n < bitvec.length; n++) {
if (val.testBit(0))
bitvec[n] = bdd.one();
else
bitvec[n] = bdd.zero();
val = val.shiftRight(1);
}
}
protected void initialize(int offset, int step) {
BDDFactory bdd = getFactory();
for (int n = 0 ; n < bitvec.length ; n++)
bitvec[n] = bdd.ithVar(offset+n*step);
}
protected void initialize(BDDDomain d) {
initialize(d.vars());
}
protected void initialize(int[] var) {
BDDFactory bdd = getFactory();
for (int n=0 ; n < bitvec.length ; n++)
bitvec[n] = bdd.ithVar(var[n]);
}
public abstract BDDFactory getFactory();
/**
* Returns a copy of this BDDBitVector.
* @return copy of this BDDBitVector.
*/
public BDDBitVector copy() {
BDDFactory bdd = getFactory();
BDDBitVector dst = bdd.createBitVector(bitvec.length);
dst.sign = sign.id();
for (int n = 0; n < bitvec.length; n++)
dst.bitvec[n] = bitvec[n].id();
return dst;
}
public void replaceWith(BDDBitVector that) {
//if (bitvec.length != that.bitvec.length)
// throw new BDDException();
this.free();
this.bitvec = that.bitvec;
this.sign = that.sign;
that.bitvec = null;
that.sign = null;
}
/**
* Returns true if this BDDBitVector is a constant bit vector, i.e., every BDD bit is a constant boolean function (TRUE or FALSE BDD).
* @return true if this BDDBitVector is a constant bit vector.
*/
public boolean isConst() {
for (int n = 0; n < bitvec.length; n++) {
BDD b = bitvec[n];
if (!b.isOne() && !b.isZero()) return false;
}
return true;
}
/**
* Returns the decimal value this BDDBitVector encodes if this BDDBitVector is a constant bit vector, and otherwise 0.
* @return The decimal value this BDDBitVector encodes.
*/
public long val() {
int n;
long val = 0L;
if(this.sign.isOne()) { /*negative value*/
val = -1L;
}
for (n = bitvec.length - 1; n >= 0; n--)
if (bitvec[n].isOne())
val = (val << 1) | 1L;
else if (bitvec[n].isZero())
val = val << 1;
else /*non constant BDD Bit Vector*/
return 0;
return val;
}
/**
* Frees this BDDBitVector.
*/
public void free() {
for (int n = 0; n < bitvec.length; n++) {
bitvec[n].free();
}
bitvec = null;
this.sign.free();
}
/**
* Returns true if this BDDBitVector encodes only negative values.
* @return true if this BDDBitVector encodes only negative values.
*/
public boolean isNegative() {
return this.sign.isOne();
}
private static BDDBitVector removeTwosComplements(BDDBitVector vector) {
BDDFactory bdd = vector.getFactory();
BDDBitVector compVector = bdd.createBitVector(vector.size());
/*first, create a two's complement representation of vector*/
/*invert all bits*/
for (int i = 0 ; i < vector.size() ; i++) {
compVector.bitvec[i] = vector.bitvec[i].not();
}
compVector.sign = vector.sign.not();
/*increment by one*/
BDDBitVector oneVector = bdd.createBitVector(1);
oneVector.initialize(1);
BDDBitVector incCompVector = compVector.add(oneVector);
oneVector.free();
compVector.free();
/*if the sign bit is 1 (negative) cancel two's complement form (i.e., use positive form);
* else (sign bit is 0), use positive form as always.*/
BDDBitVector iteCompVector = bdd.createBitVector(vector.size());
/*make all representations in a positive form*/
for (int i = 0 ; i < vector.size() ; i++) {
iteCompVector.bitvec[i] = vector.sign.ite(incCompVector.bitvec[i], vector.bitvec[i]);
}
iteCompVector.sign = bdd.zero(); /*now all representations are positive*/
incCompVector.free();
return iteCompVector;
}
private static BDDBitVector restoreTwosComplements(BDD resSign, BDDBitVector posVector) {
BDDFactory bdd = resSign.getFactory();
BDDBitVector compVector = bdd.createBitVector(posVector.size());
/*first, create a two's complement representation of posVector*/
/*invert all bits*/
for (int i = 0 ; i < posVector.size() ; i++) {
compVector.bitvec[i] = posVector.bitvec[i].not();
}
compVector.sign = bdd.one();
/*increment by one*/
BDDBitVector oneVector = bdd.createBitVector(1);
oneVector.initialize(1);
BDDBitVector incCompVector = compVector.add(oneVector);
oneVector.free();
compVector.free();
BDD notZeroRes = bdd.zero();
for(int i = 0 ; i < posVector.size(); i++) {
notZeroRes.orWith(posVector.bitvec[i].id());
}
BDD negAndNotZeroRes = resSign.and(notZeroRes); /*a boolean function that is true iff the number is negative and not zero (thus
surely negative : this fix was added to handle cases of a negative number multiplied by zero)*/
/*if the sign bit is 1 (negative) add\restore two's complement form (i.e., use negative form);
* else (sign bit is 0 -> positive or zero), use positive form as always.*/
BDDBitVector iteCompVector = bdd.createBitVector(posVector.size());
for (int i = 0 ; i < posVector.size() ; i++) {
iteCompVector.bitvec[i] = negAndNotZeroRes.ite(incCompVector.bitvec[i], posVector.bitvec[i]);
}
iteCompVector.sign = negAndNotZeroRes; /*now all representations are positive*/
incCompVector.free();
return iteCompVector;
}
/**
* Performs bitwise multiplication of this and that BDDBitVectors. Both vectors can be of different lengths and of different signs (positive\negative).
* @param that
* @return
*/
public BDDBitVector mult(BDDBitVector that) {
BDDFactory bdd = this.getFactory();
int longArgLen = java.lang.Math.max(this.size(), that.size());
BDDBitVector shorterVector = (this.size() != longArgLen) ? this : that;
BDDBitVector longerVector = (this.size() == longArgLen) ? this : that;
BDDBitVector res = bdd.createBitVector(shorterVector.size() + longerVector.size());
res.initialize(0);
BDDBitVector posShorterVector = shorterVector;
if(!shorterVector.sign.isZero()) {
posShorterVector = removeTwosComplements(shorterVector);
}
BDDBitVector posLongerVector;
if(!longerVector.sign.isZero()) {
posLongerVector = removeTwosComplements(longerVector);
}
else {
posLongerVector = longerVector.copy();
}
BDDBitVector resIfShorterIsOne;
int n = 0;
for (; n < posShorterVector.size() ; n++) {
resIfShorterIsOne = res.add(posLongerVector);
for(int i = 0 ; i < res.size() ; i++) {
res.bitvec[i] = posShorterVector.bitvec[n].ite(resIfShorterIsOne.bitvec[i], res.bitvec[i]);
}
resIfShorterIsOne.free();
BDDBitVector tmp1 = posLongerVector.shlWithExtraBits(1, bdd.zero());
posLongerVector.free();
posLongerVector = tmp1;
}
res.sign.free();
res.sign = shorterVector.sign.xor(longerVector.sign);
if(shorterVector.sign.isZero() && longerVector.sign.isZero()) {
return res;
}
return restoreTwosComplements(res.sign, res);
}
/**
* Performs bitwise addition of this and that BDDBitVectors. Both vectors can be of different lengths and of different signs (positive\negative).
* @param that
* @return
*/
public BDDBitVector add(BDDBitVector that) {
BDDFactory bdd = this.getFactory();
int longArgLen = java.lang.Math.max(this.size(), that.size());
BDDBitVector shorterVector = (this.size() != longArgLen) ? this : that;
BDDBitVector longerVector = (this.size() == longArgLen) ? this : that;
BDD c = bdd.zero(); /*set initial carry to zero*/
BDDBitVector res = bdd.createBitVector(longArgLen+1);
res.sign.free();
int n = 0;
for (; n < shorterVector.size(); n++) {
/* bitvec[n] = l[n] ^ r[n] ^ c; */
res.bitvec[n] = bitvec[n].xor(that.bitvec[n]);
res.bitvec[n].xorWith(c.id());
/* c = (l[n] & r[n]) | (c & (l[n] | r[n])); */
BDD tmp1 = bitvec[n].or(that.bitvec[n]);
tmp1.andWith(c);
BDD tmp2 = bitvec[n].and(that.bitvec[n]);
tmp2.orWith(tmp1);
c = tmp2;
}
for (; n < longArgLen; n++) {
/* bitvec[n] = longVector[n] ^ shortVectorSignExtension ^ c; */
res.bitvec[n] = longerVector.bitvec[n].xor(shorterVector.sign);
res.bitvec[n].xorWith(c.id());
/* c = (longVector[n] & shortVectorSignExtension) | (c & (longVector[n] | shortVectorSignExtension)); */
BDD tmp1 = longerVector.bitvec[n].or(shorterVector.sign);
tmp1.andWith(c);
BDD tmp2 = longerVector.bitvec[n].and(shorterVector.sign);
tmp2.orWith(tmp1);
c = tmp2;
}
/*calculate the MSB*/
res.bitvec[n] = longerVector.sign.xor(shorterVector.sign);
res.bitvec[n].xorWith(c.id());
/* c = (longerVector.sign & shorterVector.sign) | (c & (longerVector.sign | shorterVector.sign)); */
BDD tmp1 = longerVector.sign.or(shorterVector.sign);
tmp1.andWith(c);
BDD tmp2 = longerVector.sign.and(shorterVector.sign);
tmp2.orWith(tmp1);
c = tmp2;
/*calculate the sign extension*/
res.sign = longerVector.sign.xor(shorterVector.sign);
res.sign.xorWith(c);
return res;
}
/**
* Performs bitwise subtraction of this and that BDDBitVectors. Both vectors can be of different lengths and of different signs (positive\negative).
* @param that
* @return
*/
public BDDBitVector sub(BDDBitVector that) {
BDDFactory bdd = getFactory();
int longArgLen = java.lang.Math.max(this.size(), that.size());
BDDBitVector shorterVector = (this.size() != longArgLen) ? this : that;
BDDBitVector longerVector = (this.size() == longArgLen) ? this : that;
BDD c = bdd.zero();
BDDBitVector res = bdd.createBitVector(longerVector.size() + 1);
res.sign.free();
int n;
BDD tmp1, tmp2;
for (n = 0; n < shorterVector.size(); n++) {
/* bitvec[n] = l[n] ^ r[n] ^ c; */
res.bitvec[n] = bitvec[n].xor(that.bitvec[n]);
res.bitvec[n].xorWith(c.id());
/* c = (l[n] & r[n] & c) | (!l[n] & (r[n] | c)); */
tmp1 = that.bitvec[n].or(c);
tmp2 = this.bitvec[n].apply(tmp1, BDDFactory.less);
tmp1.free();
tmp1 = this.bitvec[n].and(that.bitvec[n]);
tmp1.andWith(c);
tmp1.orWith(tmp2);
c = tmp1;
}
BDD l, r;
for (; n < longerVector.size(); n++) {
/* bitvec[n] = r.sign ^ l[n] ^ c; */
res.bitvec[n] = longerVector.bitvec[n].xor(c);
res.bitvec[n].xorWith(shorterVector.sign.id());
if(longerVector == that) {
l = this.sign;
r = that.bitvec[n];
}
else {
l = this.bitvec[n];
r = that.sign;
}
tmp1 = r.or(c);
tmp2 = l.apply(tmp1, BDDFactory.less);
tmp1.free();
tmp1 = l.and(r);
tmp1.andWith(c);
tmp1.orWith(tmp2);
c = tmp1;
}
res.bitvec[n] = c.xor(this.sign);
res.bitvec[n].xorWith(that.sign.id());
/* c = (l.sign & r.sign & c) | (!l.sign & (r.sign | c)); */
tmp1 = that.sign.or(c);
tmp2 = this.sign.apply(tmp1, BDDFactory.less);
tmp1.free();
tmp1 = this.sign.and(that.sign);
tmp1.andWith(c);
tmp1.orWith(tmp2);
c = tmp1;
res.sign = c.xor(this.sign);
res.sign.xorWith(that.sign.id());
return res;
}
/**
* Returns a BDD that encodes less than equal (lte) boolean function of this BDDBitVector and the specified BDDBitVector, i.e, this <= r.
* @param r
* @return
*/
public BDD lte(BDDBitVector r)
{
BDDFactory bdd = getFactory();
BDDBitVector cmpResTmp = this.sub(r);
BDDBitVector oneVec = bdd.createBitVector(BigInteger.valueOf(1));
BDDBitVector cmpRes = cmpResTmp.sub(oneVec);
cmpResTmp.free();
oneVec.free();
BDD res = cmpRes.sign.id();
cmpRes.free();
return res;
}
/**
* Returns a BDD that encodes less than (lt) boolean function of this BDDBitVector and the specified BDDBitVector, i.e, this < r.
* @param r
* @return
*/
public BDD lt(BDDBitVector r)
{
BDDBitVector cmpRes = this.sub(r);
BDD res = cmpRes.sign.id();
cmpRes.free();
return res;
}
/**
* Returns a BDD that encodes equals (eq) boolean function of this BDDBitVector and the specified BDDBitVector, i.e, this = r.
* @param r
* @return
*/
public BDD eq(BDDBitVector r)
{
BDDBitVector cmpRes = this.sub(r);
BDD res = cmpRes.sign.id();
for(int i = 0 ; i < cmpRes.size() ; i ++) {
res.orWith(cmpRes.bitvec[i].id());
}
BDD resTmp = res.not();
res.free();
cmpRes.free();
res = resTmp;
return res;
}
/**
* Left shift. The vector's length grows.
* @param pos
* @param c
* @return
*/
public BDDBitVector shlWithExtraBits(int pos, BDD c) {
if (pos < 0) {
throw new BDDException();
}
BDDFactory bdd = getFactory();
BDDBitVector res = bdd.createBitVector(bitvec.length + pos);
int n;
for (n = 0; n < pos; n++) {
res.bitvec[n] = c.id();
}
for (n = pos; n < bitvec.length + pos; n++) {
res.bitvec[n] = bitvec[n - pos].id();
}
res.sign = this.sign.id();
return res;
}
/**
* Conditional shift left. If the condition if true, then the value will be the left shifted, and otherwise
* the same value as no left shift has been performed. The vector's length grows.
* @param pos
* @param c
* @param cond
* @return
*/
public BDDBitVector condShlWithExtraBits(int pos, BDD c, BDD cond) {
if (pos < 0) {
throw new BDDException();
}
BDDFactory bdd = getFactory();
BDDBitVector res = bdd.createBitVector(bitvec.length + pos);
int n;
for (n = 0; n < pos; n++) {
res.bitvec[n] = cond.ite(c, this.bitvec[n]);
}
for (n = pos; n < bitvec.length + pos; n++) {
if(n < bitvec.length) {
res.bitvec[n] = cond.ite(bitvec[n - pos], this.bitvec[n]);
}
else {
res.bitvec[n] = cond.ite(bitvec[n - pos], this.sign);
}
}
res.sign = this.sign.id();
return res;
}
/**
* Right shift. The vector's length becomes shorter.
* @param pos
* @return
*/
public BDDBitVector shrWithLessBits(int pos) {
if (pos < 0) {
throw new BDDException();
}
int maxnum = Math.max(0, bitvec.length - pos);
BDDFactory bdd = getFactory();
BDDBitVector res = bdd.createBitVector(maxnum);
for (int n = 0 ; n < maxnum ; n++) {
res.bitvec[n] = bitvec[n + pos].id();
}
res.sign = this.sign.id();
return res;
}
public int size() {
return bitvec.length;
}
public BDD getBit(int n) {
return bitvec[n];
}
/**
* Left shift. The vector's length remains the same.
* @param pos
* @param c
* @return
*/
public BDDBitVector shl(int pos, BDD c) {
if (pos < 0)
throw new BDDException();
int minnum = Math.min(bitvec.length, pos);
BDDFactory bdd = getFactory();
BDDBitVector res = bdd.createBitVector(bitvec.length);
int n;
for (n = 0; n < minnum; n++)
res.bitvec[n] = c.id();
for (n = minnum; n < bitvec.length; n++)
res.bitvec[n] = bitvec[n - pos].id();
res.sign = this.sign.id();
return res;
}
/**
* Right shift. The vector's length remains the same.
* @param pos
* @param c
* @return
*/
public BDDBitVector shr(int pos, BDD c) {
if (pos < 0)
throw new BDDException();
int maxnum = Math.max(0, bitvec.length - pos);
BDDFactory bdd = getFactory();
BDDBitVector res = bdd.createBitVector(bitvec.length);
int n;
for (n = maxnum ; n < bitvec.length ; n++)
res.bitvec[n] = c.id();
for (n = 0 ; n < maxnum ; n++)
res.bitvec[n] = bitvec[n+pos].id();
res.sign = this.sign.id();
return res;
}
private static boolean powerOfTwo(long c) {
boolean haveSeenOne = false;
while(c != 0) {
if((c & 1L) != 0) {
if(haveSeenOne) {
return false;
}
haveSeenOne = true;
}
c >>= 1;
}
return haveSeenOne;
}
/**
* Computes {@code this modulo c}
* @param c the modulo value
* @return
*/
public BDDBitVector mod (long c) {
if(c <= 0L) {
throw new BDDException("modulo divisor must be positive");
}
BDDFactory bdd = this.getFactory();
BDDBitVector cBitVec = bdd.createBitVector(BigInteger.valueOf(c));
BDDBitVector result = mod(cBitVec, false, true);
cBitVec.free();
return result;
}
public BDDBitVector mod (BDDBitVector divisor) {
return mod (divisor, true, false);
}
/**
* Computes {@code this modulo divisor}. The divisor must have positive values only. If non positive value
* is found a {@link#BDDException} is thrown. However, {@code this} can be of any integer value.
* @param divisor
* @param checkZeroDivisor Whether to check if the divisor can get the value of zero.
* @param constDivisor Whether the divisor is a constant.
* @return The modulo result.
*/
public BDDBitVector mod (BDDBitVector divisor, boolean checkZeroDivisor, boolean constDivisor) {
if(!divisor.sign.isZero()) { /*check if the divisor can get negative values*/
throw new BDDException("modulo divisor must be positive");
}
BDDFactory bdd = getFactory();
BDDBitVector result;
if(this.sign.isZero()) { /*the dividend only has non-negative values*/
if(constDivisor && powerOfTwo(divisor.val())) {
/*check if the divisor is a constant of a power of 2.
If so, optimize the computation*/
int bitnum = 0;
long tmpC = divisor.val()-1;
while(tmpC != 0 && bitnum < this.bitvec.length) {
bitnum++;
tmpC >>= 1;
}
result = bdd.createBitVector(bitnum);
for(int i = 0; i < result.bitvec.length; i++) {
result.bitvec[i] = this.bitvec[i].id();
}
}
else {
/*perform modulo division, and return the remainder which is also the modulo*/
result = this.divmod(divisor, checkZeroDivisor, false, constDivisor);
}
}
else { /*the dividend has negative value(s)*/
/*Compute the remainder (this is the modulo only if this >= 0):
* this % c = this - (this / c) * c;
*
* */
BDDBitVector posThis = removeTwosComplements(this);
BDDBitVector posDivRes = posThis.divmod(divisor, checkZeroDivisor, true, constDivisor);
BDDBitVector divRes = restoreTwosComplements(this.sign, posDivRes);
posDivRes.free();
posThis.free();
BDDBitVector resTmp1 = divRes.mult(divisor);
BDDBitVector remainder = this.sub(resTmp1);
resTmp1.free();
divRes.free();
if(!remainder.sign.isZero()) { /*We have negative remainder(s)*/
/*Compute modulo in case of a negative remainder (possible only if this < 0): remainder + c */
BDDBitVector resIfRNeg = remainder.add(divisor);
result = bdd.createBitVector(remainder.bitvec.length);
for(int i = 0 ; i < result.bitvec.length ; i ++) {
result.bitvec[i] = remainder.sign.ite(resIfRNeg.bitvec[i], remainder.bitvec[i]);
}
remainder.free();
resIfRNeg.free();
}
else {
result = remainder;
}
}
return result;
}
private BDD isNonZeroBdd(BDDBitVector vector) {
BDDFactory bdd = getFactory();
BDD res = bdd.zero();
for(int i = 0 ; i < vector.bitvec.length ; i ++) {
res.orWith(vector.bitvec[i].id());
}
return res;
}
/**
* Performs bitwise (modulo 2) long division of this BDDBitVector (the dividend) and divisor (the divisor).
* Both vectors can be different lengths. However, both vectors must encode <i>positive</i> numbers only.
*
* @param divisor The divisor.
* @param retRes If true, returns the quotient; otherwise, returns the remainder.
* @param checkZeroDivisor Whether to check if the divisor can have a value of 0.
* @param constDivisor Whether the divisor is a constant.
* @return The result or the remainder of the division, depending on the value of {@code retRes}.
*/
public BDDBitVector divmod(BDDBitVector divisor, boolean checkZeroDivisor, boolean retRes, boolean constDivisor) {
if (!divisor.sign.isZero()) { /*check if the divisor can get negative values*/
throw new BDDException("divisor must be positive");
}
BDDFactory bdd = getFactory();
if(checkZeroDivisor) { /*check the divisor cannot have a value of 0 */
BDD zeroCheck = isNonZeroBdd(divisor);
if(!zeroCheck.isOne()) {
throw new BDDException("Divisor cannot have a value of 0");
}
zeroCheck.free();
}
/*set the result (quotient) to be 0 in the same length (number of bits) of the dividend*/
BDDBitVector quotient = bdd.buildVector(bitvec.length, false);
/*set the initial remainder to be the dividend*/
BDDBitVector remainder = this.copy();
BDDBitVector product = divisor.copy(), productTmp, termTmp;
BDD prodLteDiv = product.lt(this);//product.lte(this);
BDDBitVector oneConstVector = bdd.constantVector(BigInteger.valueOf(1L));
BDDBitVector term = oneConstVector;
/* the divisor multiplied by 2, resulting in product = divisor * 2^i, such that product * 2 > dividend
*
* */
/* term = 2^i, such that divisor * 2^(i+1) > divided
*
* */
while(!prodLteDiv.isZero()) {
/*shift left only products such that product < dividend*/
if(constDivisor) {
productTmp = product.shlWithExtraBits(1, bdd.zero());
}
else {
productTmp = product.condShlWithExtraBits(1, bdd.zero(), prodLteDiv);
}
product.free();
product = productTmp;
/*shift left only terms such that term < dividend*/
if(constDivisor) {
termTmp = term.shlWithExtraBits(1, bdd.zero());
}
else {
termTmp = term.condShlWithExtraBits(1, bdd.zero(), prodLteDiv);
}
term.free();
term = termTmp;
prodLteDiv.free();
prodLteDiv = product.lt(this);
}
BDD prodLteRemainder = product.lte(remainder);
BDD termIsNonZero = isNonZeroBdd(term); /*get the bdd that evaluates to true when the term vector
gets a non zero value*/
prodLteRemainder.andWith(termIsNonZero.id());
BDDBitVector quotientIfPLteR, remainderIfPLteR, quotientTmp, remainderTmp;//,productTmp, termTmp;
while(!termIsNonZero.isZero()) { /*term >= 1*/
if(!prodLteRemainder.isZero()) { /*product <= remainder*/
quotientIfPLteR = quotient.add(term);
quotientTmp = bdd.createBitVector(quotientIfPLteR.bitvec.length);
/*quotientIfPLteR.bitvec.length > quotient.bitvec.length*/
for(int i = 0 ; i < quotientTmp.bitvec.length ; i++) {
if(i < quotient.bitvec.length) {
quotientTmp.bitvec[i] = prodLteRemainder.ite(quotientIfPLteR.bitvec[i], quotient.bitvec[i]);
}
else {
quotientTmp.bitvec[i] = prodLteRemainder.ite(quotientIfPLteR.bitvec[i], quotient.sign);
}
}
remainderIfPLteR = remainder.sub(product);
remainderTmp = bdd.createBitVector(remainderIfPLteR.bitvec.length);
/*remainderIfPLteR.bitvec.length > remainder.bitvec.length*/
for(int i = 0 ; i < remainderTmp.bitvec.length ; i++) {
if(i < remainder.bitvec.length) {
remainderTmp.bitvec[i] = prodLteRemainder.ite(remainderIfPLteR.bitvec[i], remainder.bitvec[i]);
}
else {
remainderTmp.bitvec[i] = prodLteRemainder.ite(remainderIfPLteR.bitvec[i], remainder.sign);
}
}
quotientIfPLteR.free();
quotient.free();
remainderIfPLteR.free();
remainder.free();
quotient = quotientTmp;
remainder = remainderTmp;
}
/*divide (right shift) product and term by 2*/
productTmp = product.shrWithLessBits(1);
product.free();
product = productTmp;
termTmp = term.shrWithLessBits(1);
term.free();
term = termTmp;
prodLteRemainder.free();
prodLteRemainder = product.lte(remainder);
termIsNonZero.free();
termIsNonZero = isNonZeroBdd(term);
prodLteRemainder.andWith(termIsNonZero.id());
}
return (retRes ? quotient : remainder);
}
///////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// commented out methods of the original implementation /////////
///////////////////////////////////////////////////////////////////////////////////////////
/*BDD lte(BDDBitVector r) // less than equal
{
if (this.bitvec.length != r.bitvec.length)
throw new BDDException();
BDDFactory bdd = getFactory();
BDD p = bdd.one();
for (int n = 0 ; n < bitvec.length ; n++) {
p = (!l[n] & r[n]) |
* bdd_apply(l[n], r[n], bddop_biimp) & p;
BDD tmp1 = bitvec[n].apply(r.bitvec[n], BDDFactory.less);
BDD tmp2 = bitvec[n].apply(r.bitvec[n], BDDFactory.biimp);
tmp2.andWith(p);
tmp1.orWith(tmp2);
p = tmp1;
}
return p;
}*/
/* public BDDBitVector map2(BDDBitVector that, BDDFactory.BDDOp op) {
if (bitvec.length != that.bitvec.length)
throw new BDDException();
BDDFactory bdd = getFactory();
BDDBitVector res = bdd.createBitVector(bitvec.length);
for (int n=0 ; n < bitvec.length ; n++)
res.bitvec[n] = bitvec[n].apply(that.bitvec[n], op);
return res;
}
*/
/* public BDDBitVector add(BDDBitVector that) {
if (bitvec.length != that.bitvec.length)
throw new BDDException();
BDDFactory bdd = getFactory();
BDD c = bdd.zero();
BDDBitVector res = bdd.createBitVector(bitvec.length);
for (int n = 0; n < res.bitvec.length; n++) {
bitvec[n] = l[n] ^ r[n] ^ c;
res.bitvec[n] = bitvec[n].xor(that.bitvec[n]);
res.bitvec[n].xorWith(c.id());
c = (l[n] & r[n]) | (c & (l[n] | r[n]));
BDD tmp1 = bitvec[n].or(that.bitvec[n]);
tmp1.andWith(c);
BDD tmp2 = bitvec[n].and(that.bitvec[n]);
tmp2.orWith(tmp1);
c = tmp2;
}
c.free();
return res;
}
*/
/* public BDDBitVector sub(BDDBitVector that) {
if (bitvec.length != that.bitvec.length)
throw new BDDException();
BDDFactory bdd = getFactory();
BDD c = bdd.zero();
BDDBitVector res = bdd.createBitVector(bitvec.length);
for (int n = 0; n < res.bitvec.length; n++) {
bitvec[n] = l[n] ^ r[n] ^ c;
res.bitvec[n] = bitvec[n].xor(that.bitvec[n]);
res.bitvec[n].xorWith(c.id());
c = (l[n] & r[n] & c) | (!l[n] & (r[n] | c));
BDD tmp1 = that.bitvec[n].or(c);
BDD tmp2 = this.bitvec[n].apply(tmp1, BDDFactory.less);
tmp1.free();
tmp1 = this.bitvec[n].and(that.bitvec[n]);
tmp1.andWith(c);
tmp1.orWith(tmp2);
c = tmp1;
}
c.free();
return res;
}
*/
/* public BDDBitVector coerce(int bitnum) {
BDDFactory bdd = getFactory();
BDDBitVector dst = bdd.createBitVector(bitnum);
int minnum = Math.min(bitnum, bitvec.length);
int n;
for (n = 0; n < minnum; n++)
dst.bitvec[n] = bitvec[n].id();
for (; n < minnum; n++)
dst.bitvec[n] = bdd.zero();
return dst;
}
*/
/*
static void div_rec(BDDBitVector divisor,
BDDBitVector remainder,
BDDBitVector result,
int step) {
BDD isSmaller = divisor.lte(remainder);
BDDBitVector newResult = result.shl(1, isSmaller);
BDDFactory bdd = divisor.getFactory();
BDDBitVector zero = bdd.buildVector(divisor.bitvec.length, false);
BDDBitVector sub = bdd.buildVector(divisor.bitvec.length, false);
for (int n = 0; n < divisor.bitvec.length; n++)
sub.bitvec[n] = isSmaller.ite(divisor.bitvec[n], zero.bitvec[n]);
BDDBitVector tmp = remainder.sub(sub);
BDDBitVector newRemainder =
tmp.shl(1, result.bitvec[divisor.bitvec.length - 1]);
if (step > 1)
div_rec(divisor, newRemainder, newResult, step - 1);
tmp.free();
sub.free();
zero.free();
isSmaller.free();
result.replaceWith(newResult);
remainder.replaceWith(newRemainder);
}
*/
/*
public void replaceWith(BDDBitVector that) {
if (bitvec.length != that.bitvec.length)
throw new BDDException();
free();
this.bitvec = that.bitvec;
that.bitvec = null;
}
*/
/* public BDDBitVector divmod(long c, boolean which) {
if (c <= 0L)
throw new BDDException();
BDDFactory bdd = getFactory();
BDDBitVector divisor = bdd.constantVector(bitvec.length, c);
BDDBitVector tmp = bdd.buildVector(bitvec.length, false);
BDDBitVector tmpremainder = tmp.shl(1, bitvec[bitvec.length-1]);
BDDBitVector result = this.shl(1, bdd.zero());
BDDBitVector remainder;
div_rec(divisor, tmpremainder, result, divisor.bitvec.length);
remainder = tmpremainder.shr(1, bdd.zero());
tmp.free();
tmpremainder.free();
divisor.free();
if (which) {
remainder.free();
return result;
} else {
result.free();
return remainder;
}
}*/
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.ui.jobs;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDFactory;
import net.sf.javabdd.BDDVarSet;
import tau.smlab.syntech.bddgenerator.BDDGenerator;
import tau.smlab.syntech.bddgenerator.BDDGenerator.TraceInfo;
import tau.smlab.syntech.bddgenerator.BDDTranslationException;
import tau.smlab.syntech.gameinput.model.GameInput;
import tau.smlab.syntech.gameinputtrans.translator.Translator;
import tau.smlab.syntech.gamemodel.BehaviorInfo;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.gamemodel.PlayerModule.TransFuncType;
import tau.smlab.syntech.jtlv.BDDPackage;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.env.module.ModuleBDDField;
import tau.smlab.syntech.spectragameinput.translator.Tracer;
import tau.smlab.syntech.ui.logger.SpectraLogger;
import tau.smlab.syntech.ui.preferences.PreferencePage;
public abstract class SyntechJob extends Job {
protected IFile specFile;
protected MessageConsole console;
protected GameModel model;
protected GameInput gi;
protected TraceInfo trace = TraceInfo.NONE;
protected static IFile previousFileWithMarkers;
protected String consoleOutput = "";
protected long computationTime;
protected long bddTranslationTime;
protected boolean isUserCancelledJob = false;
protected boolean isRealizable;
protected boolean isWellSeparated;
protected int coreSize;
protected String issuesKind;
protected int numIssues;
protected List<Translator> translators;
private static List<Integer> traceIDListInCore = new ArrayList<Integer>();
/**
* set info what elements of spec to trace (creates relevant BehaviorInfo).<br>
* Note: the more you trace the longer everything takes due to BDD creation.
*
* @param trace
*/
public void setTrace(TraceInfo trace) {
this.trace = trace;
}
public SyntechJob() {
super("SYNTECH");
}
/**
* Implementation of default run method to start a thread that actually will do
* the work.
*/
@SuppressWarnings("deprecation")
@Override
protected IStatus run(IProgressMonitor monitor) {
long jobTime = System.currentTimeMillis();
BDDPackage.setCurrPackage(PreferencePage.getBDDPackageSelection(), PreferencePage.getBDDPackageVersionSelection());
if (PreferencePage.isReorderEnabled()) {
Env.enableReorder();
Env.TRUE().getFactory().autoReorder(BDDFactory.REORDER_SIFT);
} else {
Env.disableReorder();
}
Thread t = new Thread(() -> translateAnddoWork());
t.start();
while (t.isAlive()) {
if (monitor.isCanceled()) {
t.stop();
printToConsole("User cancelled job.");
Env.resetEnv();
isUserCancelledJob = true;
return Status.CANCEL_STATUS;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
computationTime = System.currentTimeMillis() - jobTime;
printToConsole("Computation time: " + computationTime + "ms");
SpectraLogger.logOperationDone(specFile, this.getName(), computationTime, isRealizable);
return Status.OK_STATUS;
}
/**
* determinize b
*
* @param b
* @param vars
* @return
*/
protected BDD det(BDD b, BDDVarSet vars) {
// set new varorder where vars are at the end
Env.disableReorder();
int[] oldOrder = b.getFactory().getVarOrder();
List<Integer> newOrder = Arrays.stream(oldOrder).boxed().collect(Collectors.toList());
List<Integer> varsL = Arrays.stream(vars.toArray()).boxed().collect(Collectors.toList());
newOrder.removeAll(varsL);
newOrder.addAll(varsL);
b.getFactory().setVarOrder(newOrder.stream().mapToInt(i->i).toArray());
BDD det = b.id();
for (int var : vars.toArray()) {
BDD tmp = det;
det = det(tmp, var);
tmp.free();
}
//b.getFactory().setVarOrder(oldOrder);
return det;
}
/**
* determinizes b to a fresh BDD
* @param b
* @param var
* @return
*/
private BDD det(BDD b, int var) {
if (b.isZero()) {
return b.id();
}
if (b.isOne()) {
return b.getFactory().nithVar(var).id();
}
// var appears so make decision one option
// this can only work because of varorder
if (b.var() == var) {
BDD blow = b.low();
if (!blow.isZero()) {
// take low branch regardless of high branch
BDD res = b.getFactory().ithVar(var);
res = res.ite(Env.FALSE(), blow);
blow.free();
return res;
} else {
// there is only one choice for b so it is fine
return b.id();
}
}
// var did not appear
if (passedVar(b, var)) {
BDD res = b.getFactory().ithVar(var);
res = res.ite(Env.FALSE(), b);
return res;
} else {
// determinize children
BDD res = b.getFactory().ithVar(b.var());
BDD bhi = b.high();
BDD high = det(bhi, var);
bhi.free();
BDD blo = b.low();
BDD low = det(blo, var);
blo.free();
res = res.ite(high, low);
high.free();
low.free();
return res;
}
}
/**
* did var only appear above b?
*
* @param b
* @param var
* @return
*/
private boolean passedVar(BDD b, int var) {
int lvlB = b.getFactory().var2Level(b.var());
int lvlVar = b.getFactory().var2Level(var);
return lvlB > lvlVar;
}
/**
* first translate GameInput into GameModel (this can already be expensive due
* to BDD creation)
*/
private void translateAnddoWork() {
long start = System.currentTimeMillis();
try {
this.model = BDDGenerator.generateGameModel(gi, trace, PreferencePage.isGroupVarSelection(),
PreferencePage.getTransFuncSelection(false));
bddTranslationTime = System.currentTimeMillis() - start;
printToConsole("BDD translation: " + bddTranslationTime + "ms (" + Env.getBDDPackageInfo() + ")");
int sysNonAux = getVarNum(model.getSys().getNonAuxFields());
int sysAux = getVarNum(model.getSys().getAuxFields());
printToConsole("Statespace env: " + getVarNum(model.getEnv().getAllFields()) + ", sys: " + sysNonAux
+ ", aux: " + sysAux);
doWork();
} catch (BDDTranslationException e) {
if (e.getTraceId() >= 0) {
createMarker(e.getTraceId(), e.getMessage(), MarkerKind.CUSTOM_TEXT_ERROR);
}
printToConsole(e.getMessage());
} catch (Exception e) {
printToConsole(e.getMessage());
e.printStackTrace();
}
}
/**
* compute number of variables of player
*
* @param p
* @return
*/
private int getVarNum(List<ModuleBDDField> fs) {
int varNum = 0;
for (ModuleBDDField f : fs) {
varNum += f.support().size();
}
return varNum;
}
/**
* do the actual work specific to the Job
*/
protected abstract void doWork();
public void setSpecFile(IFile f) {
specFile = f;
}
public void setConsole(MessageConsole console) {
this.console = console;
}
/**
* print a string to the console of the plug-in
*
* @param s
*/
public void printToConsole(String s) {
consoleOutput += s + System.lineSeparator();
MessageConsoleStream mcs = console.newMessageStream();
mcs.println(s);
try {
mcs.flush();
mcs.close();
} catch (IOException e) {
}
}
public void setGameInput(GameInput i) {
this.gi = i;
}
/**
* deletes all markers of all SYNTECH MarkerKind(s)
*/
public void clearMarkers(IFile specIfile) {
traceIDListInCore.clear();
for (MarkerKind k : MarkerKind.values()) {
try {
specIfile.deleteMarkers(k.getMarkerID(), true, IResource.DEPTH_ZERO);
} catch (CoreException e) {
}
}
}
public void clearMarkers() {
clearMarkers(specFile);
}
/**
* creates markers in the current file for a list of BehaviorInfos
*
* @param infos
* @param kind
*/
public void createMarker(List<BehaviorInfo> infos, MarkerKind kind) {
if (infos != null && infos.size() > 0) {
if (previousFileWithMarkers != null) {
clearMarkers(previousFileWithMarkers);
}
previousFileWithMarkers = specFile;
}
for (BehaviorInfo info : infos) {
createMarker(info.traceId, kind.getMessage(), kind);
}
}
/**
* create a marker for an element with the given traceId
*
* @param traceId
* @param message
* @param kind
*/
public void createMarker(int traceId, String message, MarkerKind kind) {
EObject o = Tracer.getTarget(traceId);
traceIDListInCore.add(traceId);
if (o != null) {
INode node = NodeModelUtils.getNode(o);
try {
IMarker marker = specFile.createMarker(kind.getMarkerID());
marker.setAttribute(IMarker.MESSAGE, message);
marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_NORMAL);
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
marker.setAttribute(IMarker.LOCATION, node.getStartLine());
marker.setAttribute(IMarker.CHAR_START, node.getOffset());
marker.setAttribute(IMarker.CHAR_END, node.getEndOffset());
} catch (CoreException e) {
}
}
}
public String getConsoleOutput() {
return this.consoleOutput;
}
public long getComputationTime() {
return this.computationTime;
}
public long getBddTranslationTime() {
return this.bddTranslationTime;
}
public boolean isUserCancelledJob() {
return this.isUserCancelledJob;
}
public boolean isRealizable() {
return this.isRealizable;
}
public boolean isWellSeparated() {
return this.isWellSeparated;
}
public int getCoreSize() {
return this.coreSize;
}
public String getIssuesKind() {
return issuesKind;
}
public int getNumIssues() {
return numIssues;
}
public static List<Integer> getTraceIDListInCore() {
// find active ifile
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart activeEditor = page.getActiveEditor();
IFile ifile;
if (activeEditor != null) {
IEditorInput input = activeEditor.getEditorInput();
if (input != null && input instanceof FileEditorInput) {
ifile = ((FileEditorInput) input).getFile();
if (ifile == null || !("spectra".equals(ifile.getFileExtension()))
|| (ifile != previousFileWithMarkers)) {
// return empty list. (We don't want to clear traceIDListInCore in case the user
// will open the previousFileWithMarkers again).
return new ArrayList<Integer>();
}
}
}
return traceIDListInCore;
}
public void setTranslators(List<Translator> transList) {
this.translators = transList;
}
@SuppressWarnings("unchecked")
public <T extends Translator> T getTranslator(Class<T> translatorClass) {
for (Translator t : translators) {
if (t.getClass().equals(translatorClass)) {
return (T) t;
}
}
return null;
}
public boolean needsBound() {
return false;
}
/**
* If decomposed transitions are used, frees and resets to TRUE (restricted by
* variable domain constraint) the single transition relations of both players
*/
public void resetSingleTrans() {
TransFuncType transFuncType = PreferencePage.getTransFuncSelection(false);
if (transFuncType != TransFuncType.SINGLE_FUNC) {
this.model.resetSingleTransFunc();
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gamemodel;
import java.util.List;
import net.sf.javabdd.BDD;
public class BehaviorInfo {
public BehaviorInfo() {
}
public BehaviorInfo(BDD initial, BDD safety, BDD justice, List<BDD> existentialFAssrts, SFAModuleConstraint existentialRegExp, int traceId, boolean aux) {
this.initial = initial;
this.safety = safety;
this.justice = justice;
this.existentialFAssrts = existentialFAssrts;
this.existentialRegExp = existentialRegExp;
this.traceId = traceId;
this.aux = aux;
}
public SFAModuleConstraint existentialRegExp;
public BDD initial;
public BDD safety;
public BDD justice;
public List<BDD> existentialFAssrts;
public int traceId;
public boolean aux;
public int getTraceId() {
return traceId;
}
public boolean isJustice() {
return justice != null;
}
public boolean isExistential() {
return this.existentialFAssrts != null || this.existentialRegExp != null;
}
public boolean isSafety() {
return safety != null;
}
public boolean isInitial() {
return initial != null;
}
@Override
public String toString() {
String s = isInitial() ? "ini" : "err";
s = isJustice() ? "justice" : s;
s = isSafety() ? "safety" : s;
s = isExistential() ? "existential" : s;
return "TraceId (" + s + ") = " + traceId;
}
public void free() {
if (isInitial()) {
initial.free();
}
if (isSafety()) {
safety.free();
}
if (isJustice()) {
justice.free();
}
if(isExistential()) {
if(this.existentialFAssrts != null) {
for(BDD exBdd : this.existentialFAssrts) {
if(!exBdd.isFree()) {
exBdd.free();
}
}
}
else { //this.existentialRegExp != null
this.existentialRegExp.free();
}
}
}
public BDD getBdd() {
if (isInitial()) {
return initial;
}
if (isSafety()) {
return safety;
}
if (isJustice()) {
return justice;
}
return null;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.jits;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;
public class ExistentialJitController extends AbstractJitController {
@Override
public void free() {
jitController.free();
Env.free(fulfill);
Env.free(towards);
safeZone.free();
}
private BDD[][] fulfill;
private BDD[][] towards;
private BDD safeZone;
private BDD[][] envViolationX;
private BDD[] envViolationY;
private int envViolationRank;
private boolean envViolationPhase = false;
private boolean exphase = false;
private int exn;
private int exjx = 0;
private int towardsRank;
private int fulfillRank;
public ExistentialJitController(JitController jitController) {
super(jitController);
}
private void loadFulfill(BDD fulfill, int[] fulfill_ranks, int exn) {
BDD[][] F = new BDD[exn][];
for (int exj = 0; exj < exn; exj++) {
F[exj] = new BDD[fulfill_ranks[exj]];
for (int r = 0; r < fulfill_ranks[exj]; r++) {
BDD temp = Env.getVar("util_exJn").getDomain().ithVar(exj);
temp.andWith(Env.getVar("util_Fn").getDomain().ithVar(r));
BDD fulfillBDD = fulfill.restrict(temp);
F[exj][r] = Env.prime(fulfillBDD);
fulfillBDD.free();
temp.free();
}
}
this.fulfill = F;
}
private void loadTowards(BDD towards, int[] towards_ranks, int exn) {
BDD[][] T = new BDD[exn][];
for (int exj = 0; exj < exn; exj++) {
T[exj] = new BDD[towards_ranks[exj]];
for (int r = 0; r < towards_ranks[exj]; r++) {
BDD temp = Env.getVar("util_exJn").getDomain().ithVar(exj);
temp.andWith(Env.getVar("util_Tn").getDomain().ithVar(r));
BDD towardsBDD = towards.restrict(temp);
T[exj][r] = Env.prime(towardsBDD);
towardsBDD.free();
temp.free();
}
}
this.towards = T;
safeZone = Env.TRUE();
for (int exj = 0; exj < exn; exj++) {
safeZone.andWith(this.towards[exj][towardsRank(exj) - 1].id());
}
}
private void loadEnvViolation(BDD envViolation, int m, int rank) {
BDD[][] EV = new BDD[m][];
BDD[] EVR = new BDD[rank];
for (int i = 0; i < m; i++) {
EV[i] = new BDD[rank];
for (int r = 0; r < rank; r++) {
BDD temp = Env.getVar("util_vIn").getDomain().ithVar(i);
temp.andWith(Env.getVar("util_vRn").getDomain().ithVar(r));
BDD envViolationBDD = envViolation.restrict(temp);
EV[i][r] = Env.prime(envViolationBDD);
envViolationBDD.free();
temp.free();
}
}
for (int r = 0; r < rank; r++) {
EVR[r] = Env.FALSE();
for (int i = 0; i < m; i++) {
EVR[r].orWith(EV[i][r].id());
}
}
this.envViolationX = EV;
this.envViolationY = EVR;
this.envViolationRank = rank - 1;
}
@Override
public void load(String folder, String name, Map<String, String[]> sysVars, Map<String, String[]> envVars) {
jitController.load(folder, name, sysVars, envVars);
try {
String prefix;
if (name == null) {
prefix = folder + File.separator;
} else {
prefix = folder + File.separator + name + ".";
}
BufferedReader sizesReader = new BufferedReader(new FileReader(prefix + "existential_sizes"));
exn = Integer.parseInt(sizesReader.readLine());
int[] fulfill_ranks = new int[exn];
int[] towards_ranks = new int[exn];
int env_violation_rank;
for (int f = 0; f < exn; f++) {
fulfill_ranks[f] = Integer.parseInt(sizesReader.readLine());
}
for (int t = 0; t < exn; t++) {
towards_ranks[t] = Integer.parseInt(sizesReader.readLine());
}
env_violation_rank = Integer.parseInt(sizesReader.readLine());
sizesReader.close();
System.out.println(Env.TRUE().getFactory().getNodeNum() + " - Read Existential Sizes");
// Extract fulfill BDD
BDD fulfill = Env.loadBDD(prefix + "fulfill.bdd");
loadFulfill(fulfill, fulfill_ranks, exn);
fulfill.free();
System.out.println(Env.TRUE().getFactory().getNodeNum() + " - Load Fulfill BDD");
// Extract towards BDD
BDD towards = Env.loadBDD(prefix + "towards.bdd");
loadTowards(towards, towards_ranks, exn);
towards.free();
System.out.println(Env.TRUE().getFactory().getNodeNum() + " - Load Towards BDD");
// Extract environment violation BDD
BDD envViolation = Env.loadBDD(prefix + "envviolation.bdd");
loadEnvViolation(envViolation, jitController.getJusticeAsm().size(), env_violation_rank);
envViolation.free();
System.out.println(Env.TRUE().getFactory().getNodeNum() + " - Load Env Violation BDD");
} catch (IOException e) {
e.printStackTrace();
}
Env.deleteVar("util_exJn");
Env.deleteVar("util_Fn");
Env.deleteVar("util_Tn");
Env.deleteVar("util_vIn");
Env.deleteVar("util_vRn");
}
private int fulfillRank(int exj) {
return fulfill[exj].length;
}
private int towardsRank(int exj) {
return towards[exj].length;
}
private BDD nextStatesEnvViolation(BDD currStatePrimed, BDD currAndTrans) {
BDD temp;
BDD nextStates = Env.FALSE();
// Find lowest rank
BDD candidate = Env.FALSE();
if (envViolationRank > 0) {
candidate = currAndTrans.and(envViolationY[envViolationRank-1]);
}
if (candidate.isZero()) {
for (int i = 0; i < getJusticeAsm().size(); i++) {
temp = envViolationX[i][envViolationRank].and(currStatePrimed);
if (!temp.isZero()) {
temp.free();
nextStates = currAndTrans.and(envViolationX[i][envViolationRank]);
break;
}
temp.free();
}
} else {
// It is guaranteed to stop on some k because Y[jx][rank] = Z
for (int r = 0; r < envViolationY.length; r++) {
temp = currAndTrans.and(envViolationY[r]);
if (!temp.isZero()) {
nextStates = temp;
envViolationRank = r;
break;
}
temp.free();
}
}
candidate.free();
return nextStates;
}
@Override
public BDD next(BDD currentState, BDD inputs) {
BDD nextStates = Env.FALSE();
// Phase 2
if (exphase) {
System.out.println(String.format("phase 2 - exjx %d, towards %d, fulfill %d", exjx, towardsRank, fulfillRank));
BDD currAndTrans = getJitContext().getTrans().id();
currAndTrans.andWith(currentState.id());
currAndTrans.andWith(Env.prime(inputs));
if (towardsRank == 0 && fulfillRank == 0) {
exjx = (exjx + 1) % exn;
exphase = false;
nextStates = prepareReturnToPhaseOne(currAndTrans);
} else if (towardsRank == 0 && fulfillRank > 0) {
nextStates = currAndTrans.and(fulfill[exjx][fulfillRank - 1]);
fulfillRank--;
// Asssume nextStates is FALSE here, move to the next existential guarantee
if (nextStates.isZero()) {
System.out.println(String.format("phase 2 - could not satisfy existential gar %s, move to next", exjx));
exjx = (exjx + 1) % exn;
exphase = false;
nextStates = prepareReturnToPhaseOne(currAndTrans);
}
} else {
nextStates = getLowestTowards(currAndTrans);
}
currAndTrans.free();
BDD primedNextStates = nextStates.exist(Env.globalUnprimeVars());
nextStates.free();
nextStates = Env.unprime(primedNextStates);
primedNextStates.free();
return nextStates;
} else { // Phase 1
// Check if there is at least one ex. gar. that cannot be reached from current state. This means that it will never be reached and
// the system cannot satisfy its guarantee GEF(regex). The only way to win that is left for the system is to force environment
// to violate assumptions
BDD currStatePrimed = Env.prime(currentState);
if (getEnvViolationPhase(currStatePrimed)) {
System.out.println("phase 1 - in env violation phase");
BDD currAndTrans = getJitContext().getTrans().id();
currAndTrans.andWith(currentState.id());
currAndTrans.andWith(Env.prime(inputs));
nextStates = nextStatesEnvViolation(currStatePrimed, currAndTrans);
currStatePrimed.free();
currAndTrans.free();
BDD primedNextStates = nextStates.exist(Env.globalUnprimeVars());
nextStates.free();
nextStates = Env.unprime(primedNextStates);
primedNextStates.free();
return nextStates;
}
currStatePrimed.free();
int oldJx = jitController.getJitState().getJx();
BDD nextStatesOriginal = jitController.next(currentState, inputs);
int newJx = jitController.getJitState().getJx();
System.out.println(String.format("phase 1 - old jx %d, new jx %d", oldJx, newJx));
// Justice guarantees cycle is satisfied
if (newJx < oldJx) {
// Maybe switching phase, recalculating next states
BDD currAndTrans = getJitContext().getTrans().id();
currAndTrans.andWith(currentState.id());
currAndTrans.andWith(Env.prime(inputs));
exphase = true;
fulfillRank = fulfillRank(exjx) - 1;
nextStates = getLowestTowards(currAndTrans);
currAndTrans.free();
BDD primedNextStates = nextStates.exist(Env.globalUnprimeVars());
nextStates.free();
nextStates = Env.unprime(primedNextStates);
primedNextStates.free();
return nextStates;
} else {
return nextStatesOriginal;
}
}
}
private boolean getEnvViolationPhase(BDD currentState) {
if (envViolationPhase) return true;
BDD temp = currentState.and(safeZone);
if (temp.isZero()) { // Not in safe zone
envViolationPhase = true;
}
temp.free();
return envViolationPhase;
}
private BDD prepareReturnToPhaseOne(BDD currAndTrans) {
BDD temp;
BDD next = Env.FALSE();
for (int r = 0; r < jitController.getJitContext().rank(0); r++) {
temp = currAndTrans.and(jitController.getJitContext().Y(0, r));
if (!temp.isZero()) {
next = temp;
jitController.getJitState().setRank(r);
break;
}
temp.free();
}
return next;
}
private BDD getLowestTowards(BDD currAndTrans) {
BDD temp;
BDD lowest = Env.FALSE();
for (int r = 0; r < towardsRank(exjx); r++) {
temp = currAndTrans.and(towards[exjx][r]);
if (!temp.isZero()) {
lowest = temp;
towardsRank = r;
break;
}
temp.free();
}
return lowest;
}
@Override
public void saveState() {
this.controller.saveState();
}
@Override
public void loadState() {
this.controller.loadState();
}
@Override
public BDD succ(BDD from) {
return jitController.succ(from);
}
@Override
public BDD pred(BDD to) {
return jitController.pred(to);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.ui.extension.console;
import org.eclipse.core.resources.IFile;
import org.eclipse.debug.ui.console.FileLink;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.IPatternMatchListenerDelegate;
import org.eclipse.ui.console.PatternMatchEvent;
import org.eclipse.ui.console.TextConsole;
import org.eclipse.ui.part.FileEditorInput;
public class ExplanationConsolePatternMatchListener implements IPatternMatchListenerDelegate
{
private TextConsole console;
IWorkbenchPage activePage;
public ExplanationConsolePatternMatchListener() {}
@Override
public void connect(TextConsole console)
{
this.console = console;
activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
@Override
public void disconnect()
{
console = null;
}
@Override
public void matchFound(PatternMatchEvent event)
{
IEditorPart editor = activePage.getActiveEditor();
if (editor != null) {
IFile spec = ((FileEditorInput)editor.getEditorInput()).getFile();
try {
String file_reference_text = console.getDocument().get(event.getOffset(), event.getLength());
// We add 2 because the match is "line: number" and we want to skip the ':' and the space
int line_number_index = file_reference_text.lastIndexOf(":") + 2;
int line_number = Integer.parseInt(file_reference_text.substring(line_number_index));
FileLink f_l = new FileLink(spec, null, -1, -1, line_number);
console.addHyperlink(f_l, event.getOffset(), event.getLength());
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller;
import java.util.Map;
import net.sf.javabdd.BDD;
public abstract class AbstractController implements Controller {
protected Controller controller;
public AbstractController(Controller controller) {
super();
this.controller = controller;
}
@Override
public void load(String folder, String name, Map<String, String[]> sysVars, Map<String, String[]> envVars) {
controller.load(folder, name, sysVars, envVars);
}
@Override
public BDD next(BDD currentState, BDD inputs) {
return controller.next(currentState, inputs);
}
@Override
public void free() {
controller.free();
}
@Override
public BDD transitions() {
return controller.transitions();
}
@Override
public BDD initial() {
return controller.initial();
}
@Override
public void init(BDD currentState) {
controller.init(currentState);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.ui.jobs;
import tau.smlab.syntech.bddgenerator.energy.BDDEnergyReduction;
import tau.smlab.syntech.games.gr1.GR1Game;
import tau.smlab.syntech.games.gr1.GR1GameEnergyADD;
import tau.smlab.syntech.games.gr1.GR1GameExperiments;
import tau.smlab.syntech.games.gr1.GR1GameImplC;
import tau.smlab.syntech.games.gr1.GR1GameMemoryless;
import tau.smlab.syntech.games.gr1.GR1SeparatedGame;
import tau.smlab.syntech.games.gr1.GR1SeparatedGameImplC;
import tau.smlab.syntech.games.gr1.GR1StarGameMemoryless;
import tau.smlab.syntech.jtlv.BDDPackage;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.ui.preferences.PreferenceConstants;
import tau.smlab.syntech.ui.preferences.PreferencePage;
public class CheckRealizabilityJob extends SyntechJob {
@Override
protected void doWork() {
GR1Game gr1;
// check for existential guarantees
if(model.getSys().existReqNum() > 0) {
printToConsole("GR1StarGameMemoryless");
gr1 = new GR1StarGameMemoryless(model);
}
// check for weights or special reordering
else if (model.getWeights() != null && PreferencePage.getBDDPackageSelection().equals(BDDPackage.CUDD_ADD)) {
printToConsole("GR1GameEnergyADD (without optimizations)");
gr1 = new GR1GameEnergyADD(model, gi.getEnergyBound());
/*} else if (PreferencePage.isSpecialReorderStrategy()) {
gr1 = new GR1GameReachable(model);
Env.TRUE().getFactory().autoReorder(BDDFactory.REORDER_NONE);
Env.TRUE().getFactory().reorder(BDDFactory.REORDER_SIFTITE);*/
} else {
PreferencePage.setOptSelection();
if (PreferencePage.getSynthesisMethod().equals(PreferenceConstants.SYNTHESIS_METHOD_PITERMAN) ||
PreferencePage.getSynthesisMethod().equals(PreferenceConstants.SYNTHESIS_METHOD_PITERMAN_REDUCTION)) {
if (PreferencePage.getBDDPackageSelection().equals(BDDPackage.CUDD)) {
printToConsole("GR1SeparatedGameImplC with memory");
gr1 = new GR1SeparatedGameImplC(model);
} else {
printToConsole("GR1SeparatedGame");
gr1 = new GR1SeparatedGame(model);
}
} else if (PreferencePage.hasSymmetryDetection()) {
printToConsole("GR1Game");
gr1 = new GR1Game(model);
} else if (PreferencePage.getBDDPackageSelection().equals(BDDPackage.CUDD)) {
printToConsole("GR1GameImplC with memory");
gr1 = new GR1GameImplC(model);
} else if (PreferencePage.hasOptSelection()) {
printToConsole("GR1GameExperiments (with optimizations)");
gr1 = new GR1GameExperiments(model);
} else {
printToConsole("GR1GameMemoryless");
gr1 = new GR1GameMemoryless(model);
}
}
this.isRealizable = false;
String message = "Specification is unrealizable.";
if (gr1.checkRealizability()) {
this.isRealizable = true;
message = "Specification is realizable.";
if (model.getWeights() != null) {
message += " System wins with minimal initial credit ";
if(PreferencePage.getBDDPackageSelection().equals(BDDPackage.CUDD_ADD)) {
message += ((GR1GameEnergyADD)gr1).getMinWinInitCred();
}
else {
message += BDDEnergyReduction.getMinWinCred(model, gr1.sysWinningStates()).toStringWithDomains(Env.stringer);
}
}
}
printToConsole(message);
Env.resetEnv();
}
@Override
public boolean needsBound() {
return true;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gamemodel.util;
import java.util.ArrayList;
import java.util.List;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.gamemodel.BehaviorInfo;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.gamemodel.ModuleException;
import tau.smlab.syntech.gamemodel.PlayerModule;
import tau.smlab.syntech.gamemodel.PlayerModule.TransFuncType;
import tau.smlab.syntech.jtlv.env.module.ModuleBDDField;
public class GameBuilderUtil {
/**
* Use this method to build the system PlayerModule of the given GameModel.
* Aux behaviors are automatically used.
*
* @param m game model
* @param part the behaviors
*/
public static void buildSys(GameModel m, List<BehaviorInfo> part) {
List<BehaviorInfo> bvs = new ArrayList<BehaviorInfo>(part);
bvs.addAll(m.getAuxBehaviorInfo());
m.getSysBehaviorInfo().clear();
m.getSysBehaviorInfo().addAll(part);
try {
build(m.getSys(), bvs);
} catch (ModuleException e) {
e.printStackTrace();
}
}
/**
* Use this method to build the environment PlayerModule of the given GameModel.
*
* @param m game model
* @param part the behaviors
*/
public static void buildEnv(GameModel m, List<BehaviorInfo> part) {
List<BehaviorInfo> bvs = new ArrayList<BehaviorInfo>(part);
m.getEnvBehaviorInfo().clear();
m.getEnvBehaviorInfo().addAll(part);
try {
build(m.getEnv(), bvs);
} catch (ModuleException e) {
e.printStackTrace();
}
}
/**
* Build the PlayerModule using the given behaviors. Take into consideration the type of safety the module uses
*
* @param module
* @param beavs
* @throws ModuleException
*/
private static void build(PlayerModule module, List<BehaviorInfo> beavs) throws ModuleException {
module.reset();
for (BehaviorInfo b : beavs) {
if (b.isInitial()) {
module.conjunctInitial(b.initial.id());
}
if (b.isSafety()) {
switch (module.getTransFuncType()) {
case SINGLE_FUNC:
module.conjunctTrans(b.safety.id());
break;
case DECOMPOSED_FUNC:
module.addToTransList(b.safety.id());
break;
case PARTIAL_DECOMPOSED_FUNC:
module.addToTransList(b.safety.id());
break;
default:
System.err.println("unknown type " + module.getTransFuncType());
break;
}
}
if (b.isJustice()) {
module.addJustice(b.justice.id(), b.traceId);
}
}
if (module.getTransFuncType() == TransFuncType.DECOMPOSED_FUNC) {
module.calcTransQuantList();
} else if (module.getTransFuncType() == TransFuncType.PARTIAL_DECOMPOSED_FUNC) {
module.createPartialTransQuantList();
}
}
public static void buildQuantifiedSys(GameModel m, List<ModuleBDDField> vars) {
PlayerModule module = m.getSys();
module.reset();
List<BehaviorInfo> part = new ArrayList<BehaviorInfo>();
part.addAll(m.getSysBehaviorInfo());
part.addAll(m.getAuxBehaviorInfo());
// quantify over core behavior and add
for (BehaviorInfo b : part) {
if (b.isJustice()) {
BDD q = b.justice.id();
q = quanAll(q, vars);
module.addJustice(q, b.traceId);
}
if (b.isSafety()) {
BDD q = b.safety.id();
q = quanAll(q, vars);
switch (module.getTransFuncType()) {
case SINGLE_FUNC:
module.conjunctTrans(q.id());
break;
case DECOMPOSED_FUNC:
module.addToTransList(q.id());
break;
case PARTIAL_DECOMPOSED_FUNC:
module.addToTransList(q.id());
break;
default:
System.err.println("unknown type " + module.getTransFuncType());
break;
}
}
if (b.isInitial()) {
BDD q = b.initial.id();
q = quanAll(q, vars);
module.conjunctInitial(q.id());
}
}
if (module.getTransFuncType() == TransFuncType.DECOMPOSED_FUNC) {
module.calcTransQuantList();
} else if (module.getTransFuncType() == TransFuncType.PARTIAL_DECOMPOSED_FUNC) {
module.createPartialTransQuantList();
}
}
/**
* quantify over a set of variables
*
* @param bdd the BDD
* @param vars the vars for existetial quantification
* @return
*/
private static BDD quanAll(BDD bdd, List<ModuleBDDField> vars) {
for (ModuleBDDField v:vars) {
bdd = bdd.exist(v.support());
}
return bdd;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.symbolic;
import java.util.Map;
import net.sf.javabdd.ADD;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDD.BDDIterator;
import net.sf.javabdd.BDDFactory;
import tau.smlab.syntech.gameinput.spec.Operator;
import tau.smlab.syntech.gameinput.spec.Spec;
import tau.smlab.syntech.gameinput.spec.SpecBDD;
import tau.smlab.syntech.gameinput.spec.SpecExp;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.gamemodel.PlayerModule;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.ModuleVariableException;
import tau.smlab.syntech.modelchecker.CounterExampleException;
import tau.smlab.syntech.modelchecker.LTLModelChecker;
import tau.smlab.syntech.modelchecker.ModelCheckException;
public class SymbolicControllerChecker {
public static boolean checkCompletenessForEnvIterate(SymbolicController ctrl, GameModel model) {
PlayerModule env = model.getEnv();
PlayerModule sys = model.getSys();
// 1) check that all inital assignments to environment variables have a
// corresponding inital state in the controller
BDD result = env.initial().id().impWith(ctrl.initial().exist(sys.moduleUnprimeVars()))
.forAll(env.moduleUnprimeVars());
if (!result.isOne()) {
result.free();
return false;
}
result.free();
// 2) check that for all reachable states in the controller it is enabled
// for all next assignments to environment variables
BDD reachable = Env.allSucc(ctrl.initial().id(), ctrl.trans().id());
for (BDDIterator sit = reachable.iterator(Env.globalUnprimeVars()); sit.hasNext();) {
BDD s = sit.nextBDD();
BDD ctrlSucc = s.and(ctrl.trans());
BDD envSucc = s.and(env.trans());
BDD envChoices = envSucc.exist(sys.modulePrimeVars());
envSucc.free();
BDD ctrlEnvChoices = ctrlSucc.exist(sys.modulePrimeVars());
ctrlSucc.free();
BDD envNotCovered = envChoices.andWith(ctrlEnvChoices.not());
if (!envNotCovered.isZero()) {
System.out.println("State " + Env.toNiceSignleLineString(s));
System.out.println(
"Successors in Controller: " + Env.toNiceSignleLineString(ctrlEnvChoices.exist(Env.globalUnprimeVars())));
System.out.println("EnvSuccessors not in Controller: "
+ Env.toNiceSignleLineString(envNotCovered.exist(Env.globalUnprimeVars())));
s.free();
envNotCovered.free();
ctrlEnvChoices.free();
return false;
}
s.free();
envNotCovered.free();
ctrlEnvChoices.free();
}
return true;
}
/**
* Check whether from every state of the controller the environment can make all
* choices
*
* @param ctrl
* @param model
* @return
*/
public static boolean checkCompletenessForEnv(SymbolicController ctrl, GameModel model) {
PlayerModule env = model.getEnv();
PlayerModule sys = model.getSys();
// 1) check that all inital assignments to environment variables have a
// corresponding inital state in the controller
BDD result = env.initial().id().impWith(ctrl.initial().exist(sys.moduleUnprimeVars()))
.forAll(env.moduleUnprimeVars());
if (!result.isOne()) {
System.out.println("initial states are not complete");
result.free();
return false;
}
result.free();
// 2) check that for all reachable states in the controller it is enabled
// for all next assignments to environment variables
BDD reachable = Env.allSucc(ctrl.initial().id(), ctrl.trans().id());
return reachable.andWith(env.trans().id()).impWith(ctrl.trans().exist(sys.modulePrimeVars()))
.forAll(env.modulePrimeVars()).isOne();
}
/**
* Check whether every reachable state (by controller and system) has an
* environment successor or is a deadlock state for the system
*
* @param ctrl
* @param model
* @return true if env has successors for all valid system choices
*/
public static boolean checkCompletenessForSys(SymbolicController ctrl, GameModel model) {
PlayerModule env = model.getEnv();
PlayerModule sys = model.getSys();
// 1) check that there is at least one valid initial env choice
BDD result = ctrl.initial().exist(env.moduleUnprimeVars());
if (result.isZero()) {
System.out.println("no inital env choice");
return false;
}
result.free();
// 2) check that for all reachable states in the controller it is enabled
BDD reachable = Env.allSucc(ctrl.initial().and(sys.initial()), sys.trans().and(ctrl.trans()));
// remove states where env has a successor
reachable.andWith(ctrl.trans().exist(env.modulePrimeVars().union(sys.modulePrimeVars())).not());
// remove dead states
reachable.andWith(env.controlStates(sys, Env.FALSE()).not());
return reachable.isZero();
}
public static boolean checkStrategyIsWinningForSys(SymbolicController ctrl, ADD weightedArena, double worstInitEng) {
ADD sourceStates = (ADD) ctrl.initial().id();
ADD strategyTrans = (ADD) ctrl.trans().and(Env.allSucc(sourceStates.id(), ctrl.trans().id()));
/* map every reachable state to -INF and every unreachable state to +INF */
ADD strategyTransTmp = strategyTrans.not();
strategyTrans.free();
strategyTrans = strategyTransTmp;
strategyTrans.applyWith(Env.CONST(2.0), BDDFactory.times);
strategyTrans.applyWith(Env.TRUE(), BDDFactory.minus);
strategyTrans.applyWith(Env.PLUS_INF(), BDDFactory.times);
/*
* restrict the arena to have only transitions from states that are reachable
* from the initial states if sys plays by the strategy. Every outgoing legal
* transition from a reachable source state, would have a finite or +INF weight;
* Otherwise, the transition would have a +INF weight.
*/
ADD strategyArena = weightedArena.apply(strategyTrans, BDDFactory.max);
strategyTrans.free();
/*
* If there is a transition with -INF weight that is reachable from the initial
* states when the system plays according to ctrl strategy, then it is loosing
*/
ADD minimumCheck = strategyArena.findMin();
if (minimumCheck.equals(Env.MINUS_INF())) {
System.out.println(
"The strategy is loosing for the system because there is a -INF transition reachable from an initial state");
minimumCheck.free();
return false;
}
minimumCheck.free();
System.out.println(
"Weights of reachable transitions from all initial states, if the system plays according to the constructed strategy:");
strategyArena.printTerminalValues();
System.out.println(
"Checking that the system can play according to this strategy, without going into a negative cycle...");
/*
* Check that there is no negative cycle reachable from every initial state if
* the system plays according to ctrl strategy
*/
if (thereIsNegativeCycle(sourceStates, strategyArena, worstInitEng)) {
System.out.println(
"Error: there is a reachable negative cycle if the system plays according to this controller, i.e. it is loosing for the system!!");
return false;
}
System.out.println("We don't have any negative cycles, so this controller is winning for the system!");
return true;
}
/**
* An implementation of symbolic Bellman Ford algorithm for calculating the
* shortest paths weights from all given source states.
*
* @param sourceStates
* @param arena the weighted arena
* @return true if there is a negative cycle reachable from one of the source
* states; false, otherwise.
*/
public static boolean thereIsNegativeCycle(ADD sourceStates, ADD arena, double worstInitEng) {
/*
* We add a new sink state, that has 0 weighted transitions to all initial
* states. Therefore, at we initialize the shortest path estimate of each
* initial state to 0; All other states are initialized to +INF.
*/
ADD curDistEstimates = sourceStates.ite(Env.FALSE(), Env.PLUS_INF());
ADD prevDistEstimates = null;
ADD distSum, relaxPrimed, relaxUnprimed, worstInitEngCheck;
/* V is the size of the state space */
long V = 1;
V <<= (2 * Env.globalPrimeVars().size());
System.out.println("V = " + V);
worstInitEng = (-1) * worstInitEng;
for (long i = 0; i < V && (prevDistEstimates == null || !curDistEstimates.equals(prevDistEstimates)); i++) {
if (i == V - 1) { // V's (last) iteration iff there is a negative cycle in the arena!
return true;
}
/*
* for efficiency of computation: if there is a negative cycle, we will end up
* with worst required energy that is higher than the declared one; If so, we
* should stop now (before reaching the V's iteration).
*/
worstInitEngCheck = curDistEstimates.findMin();
if (worstInitEngCheck
.getConstantValue() < worstInitEng) { /*
* the strategy seems to be wrong, or there might be a negative cycle
*/
System.out.println(
"the strategy requires energy from the initial states which is higher than the declared worst needed energy level!");
System.out.println("The worst energy level that was found: " + (-1) * worstInitEngCheck.getConstantValue()
+ ", but the declared energy is " + (-1) * worstInitEng);
return true;
}
worstInitEngCheck.free();
// curDistEstimates.printTerminalValues();
if (prevDistEstimates != null) {
prevDistEstimates.free();
}
prevDistEstimates = curDistEstimates;
/*
* for all states v, d(v) is the shortest path estimate from one of the initial
* states, i.e. it is the most energy consuming path to state v from one of the
* initial states.
*/
/*
* Relax operation: for every target state v, do: d*(v) = min(d(u) + w(u,v)) for
* all predecessors of v
*/
distSum = arena.apply(prevDistEstimates, BDDFactory.plus);
relaxPrimed = distSum.abstractMin(Env.globalUnprimeVars());
relaxUnprimed = (ADD) Env.unprime(relaxPrimed);
/*
* for every target state v, do: d(v) = min(d(v), d*(v)); this is the last step
* of the relax operation for each edge in the graph.
*/
curDistEstimates = relaxUnprimed.apply(prevDistEstimates, BDDFactory.min);
distSum.free();
relaxPrimed.free();
relaxUnprimed.free();
}
return false;
}
public static int checkMaxAccumulatedWeightUpToLimit(SymbolicController ctrl, Map<Integer, BDD> weights, int limit) {
// TODO implement fixed point algorithm over reachable states but divided by
// accumulated weights
// compute a downwards closed set to guarantee fixpoint (to make it
// downwardclosed keep only the state with the highest accumulated value)
return -1;
}
public static boolean checkCompletenessForEnvUpTo(SymbolicController ctrl, GameModel model, BDD upTo) {
PlayerModule env = model.getEnv();
PlayerModule sys = model.getSys();
// 1) check that all inital assignments to environment variables have a
// corresponding inital state in the controller
BDD result = env.initial().id().andWith(upTo.not()).impWith(ctrl.initial().exist(sys.moduleUnprimeVars()))
.forAll(env.moduleUnprimeVars());
if (!result.isOne()) {
result.free();
return false;
}
result.free();
// 2) check that for all reachable states in the controller it is enabled
// for all next assignments to environment variables
BDD reachable = Env.allSucc(ctrl.initial().id(), ctrl.trans().id()).andWith(upTo.not());
return reachable.andWith(env.trans().id()).impWith(ctrl.trans().exist(sys.modulePrimeVars()))
.forAll(env.modulePrimeVars()).isOne();
}
/**
* Model-checks controller against GR(1) specification (strict realizability
* semantics)
*
* @param ctrl
* @param m
* @return false in case of any exceptions (including counter-examples)
*/
public static boolean checkGR1Spec(SymbolicController ctrl, GameModel m) {
try {
checkGR1SpecWC(ctrl, m);
} catch (Exception e) {
return false;
}
return true;
}
/**
* Model-checks controller against GR(1) specification (strict realizability
* semantics)
*
* @param ctrl
* @param m
* @throws ModelCheckException
* @throws CounterExampleException (is a ModelCheckException) in case GR(1) spec
* is violated by controller
* @throws ModuleVariableException
*/
public static void checkGR1SpecWC(SymbolicController ctrl, GameModel m)
throws ModelCheckException, CounterExampleException, ModuleVariableException {
PlayerModule sys = m.getSys();
if (sys.justiceNum() == 0) {
sys.addJustice(Env.TRUE());
}
PlayerModule env = m.getEnv();
if (env.justiceNum() == 0) {
env.addJustice(Env.TRUE());
}
LTLModelChecker c = null;
PlayerModule mod = new PlayerModule();
mod.setName("symbolicGraph");
mod.resetInitial();
mod.conjunctInitial(ctrl.initial().id());
mod.resetTrans();
mod.conjunctTrans(ctrl.trans().id());
c = new LTLModelChecker(mod);
Spec sysJ = allJustice(sys);
Spec envJ = allJustice(env);
Spec rhoS = new SpecBDD(sys.trans());
Spec rhoE = new SpecBDD(env.trans());
Spec thetaS = new SpecBDD(sys.initial());
Spec thetaE = new SpecBDD(env.initial());
Spec implI = new SpecExp(Operator.IMPLIES, thetaE, thetaS);
Spec HrhoE = null;
// workaround of HISTORICALLY limitation in case of primes in rhoE
if (Env.containPrimeVars(env.trans())) {
HrhoE = new SpecExp(Operator.HISTORICALLY, new SpecExp(Operator.PRIME, new SpecExp(Operator.PREV, rhoE)));
} else {
HrhoE = new SpecExp(Operator.HISTORICALLY, rhoE);
}
Spec implS = new SpecExp(Operator.IMPLIES, thetaE,
new SpecExp(Operator.GLOBALLY, new SpecExp(Operator.IMPLIES, HrhoE, rhoS)));
Spec implJ = new SpecExp(Operator.IMPLIES,
new SpecExp(Operator.AND, thetaE, new SpecExp(Operator.AND, new SpecExp(Operator.GLOBALLY, rhoE), envJ)), sysJ);
Spec strongRealizability = new SpecExp(Operator.AND, new SpecExp(Operator.AND, implS, implJ), implI);
// c.modelCheckStandardOutput(strongRealizability);
c.modelCheck(strongRealizability);
}
/**
* produces a conjunction of all justices as /\_{i} GF(J_i)
*
* @param m
* @return
*/
private static Spec allJustice(PlayerModule m) {
Spec allSysJ = new SpecExp(Operator.GLOBALLY, new SpecExp(Operator.FINALLY, new SpecBDD(m.justiceAt(0))));
for (int i = 1; i < m.justiceNum(); i++) {
Spec spec = new SpecExp(Operator.GLOBALLY, new SpecExp(Operator.FINALLY, new SpecBDD(m.justiceAt(i))));
allSysJ = new SpecExp(Operator.AND, allSysJ, spec);
}
return allSysJ;
}
public static boolean checkRabinSpec(SymbolicController ctrl, GameModel m) {
boolean res = false;
PlayerModule sys = m.getSys();
PlayerModule env = m.getEnv();
LTLModelChecker c = null;
try {
PlayerModule mod = new PlayerModule();
mod.setName("symbolicGraph");
mod.resetInitial();
mod.conjunctInitial(ctrl.initial().id());
mod.resetTrans();
mod.conjunctTrans(ctrl.trans().id());
c = new LTLModelChecker(mod);
} catch (Exception e) {
e.printStackTrace();
return false;
}
Spec sysJ = allJustice(sys);
Spec envJ = allJustice(env);
Spec rhoS = new SpecBDD(sys.trans());
Spec rhoE = new SpecBDD(env.trans());
Spec thetaS = new SpecBDD(sys.initial());
Spec thetaE = new SpecBDD(env.initial());
Spec implI = new SpecExp(Operator.IMPLIES, thetaE, thetaS);
Spec HrhoE = null;
// workaround of HISTORICALLY limitation in case of primes in rhoE
if (Env.containPrimeVars(env.trans())) {
HrhoE = new SpecExp(Operator.HISTORICALLY, new SpecExp(Operator.PRIME, new SpecExp(Operator.PREV, rhoE)));
} else {
HrhoE = new SpecExp(Operator.HISTORICALLY, rhoE);
}
Spec implS = new SpecExp(Operator.AND, thetaE,
new SpecExp(Operator.GLOBALLY, new SpecExp(Operator.IMPLIES, HrhoE, rhoS)));
Spec implJ = new SpecExp(Operator.IMPLIES,
new SpecExp(Operator.AND, thetaE, new SpecExp(Operator.AND, new SpecExp(Operator.GLOBALLY, rhoE), envJ)), sysJ);
Spec strongRealizability = new SpecExp(Operator.AND, new SpecExp(Operator.AND, implS, implJ), implI);
Spec rabin = new SpecExp(Operator.NOT, strongRealizability);
res = c.modelCheckWithNoCounterExample(rabin);
return res;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.sfa;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.sfa.PowerSetIterator.PowerSetIteratorType;
/**
*
* An Epsilon-SFA that has exactly One Final state, which has no outgoing transitions.
*
* @author <NAME>
*
*/
public class OFEpsSFA extends EpsSFA {
private EpsSFAState finalState; //The unique, only final state of this automaton
protected OFEpsSFA() {
this(null, null, PowerSetIteratorType.EFFICIENT);
}
protected OFEpsSFA(SFAState ini) {
this(ini, null, PowerSetIteratorType.EFFICIENT);
}
protected OFEpsSFA(SFAState ini, SFAState finalState) {
this(ini, finalState, PowerSetIteratorType.EFFICIENT);
}
protected OFEpsSFA(PowerSetIteratorType psIterType) {
this(null, null, psIterType);
}
protected OFEpsSFA(SFAState ini, PowerSetIteratorType psIterType) {
this(ini, null, psIterType);
}
protected OFEpsSFA(SFAState ini, SFAState finalState, PowerSetIteratorType psIterType) {
super(ini, psIterType);
if(finalState != null) {
this.setFinalState(finalState);
}
}
@Override
public EpsSFAState getFinalState() {
return this.finalState;
}
@Override
public void setFinalState(SFAState finalState) {
if(!(finalState instanceof EpsSFAState)) {
throw new SFAException("The specified state has an invalid type. The final state must be an instance of EpsSFAState.");
}
if(!finalState.isAccepting()) {
finalState.flipAcceptance();
}
this.finalState = (EpsSFAState) finalState;
}
@Override
public OFEpsSFA copy() {
OFEpsSFA copy = new OFEpsSFA();
Map<EpsSFAState, EpsSFAState> copyStateMappingMap = new HashMap<>();
copy.setIni(this.getIni().cloneWithoutSucc());
copyStateMappingMap.put(this.getIni(), copy.getIni());
Queue<EpsSFAState> worklist = new LinkedList<>();
worklist.add(this.getIni());
while (!worklist.isEmpty()) {
EpsSFAState s = worklist.remove();
if(s == this.finalState) {
//the only accepting state is reachable from the initial state
copy.finalState = copyStateMappingMap.get(s);
}
//non-epsilon transitions/successors
for (Map.Entry<EpsSFAState, BDD> transition : s.getSucc().entrySet()) {
if (!copyStateMappingMap.containsKey(transition.getKey())) {
worklist.add(transition.getKey());
copyStateMappingMap.put(transition.getKey(), transition.getKey().cloneWithoutSucc());
}
copyStateMappingMap.get(s).addTrans(transition.getValue().id(),
copyStateMappingMap.get(transition.getKey()));
}
//handle epsilon transitions, if such transitions exist
if(s.hasEpsSuccessors()) {
for(EpsSFAState epsSucc : s.getEpsSucc()) {
if (!copyStateMappingMap.containsKey(epsSucc)) {
worklist.add(epsSucc);
copyStateMappingMap.put(epsSucc, epsSucc.cloneWithoutSucc());
}
copyStateMappingMap.get(s).addEpsTrans(copyStateMappingMap.get(epsSucc));
}
}
}
if(!copyStateMappingMap.containsKey(this.finalState)) {
//the final state is not reachable from the initial state
copy.finalState = this.finalState.cloneWithoutSucc();
}
return copy;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.simple;
import java.util.Stack;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDD.BDDIterator;
import net.sf.javabdd.BDDVarSet;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.games.AbstractGamesException;
import tau.smlab.syntech.games.GameMemory;
import tau.smlab.syntech.games.controller.enumerate.ConcreteControllerConstruction;
import tau.smlab.syntech.games.controller.enumerate.EnumStateI;
import tau.smlab.syntech.games.controller.enumerate.EnumStrategyI;
import tau.smlab.syntech.games.controller.enumerate.EnumStrategyImpl;
import tau.smlab.syntech.jtlv.CoreUtil;
public class SafetyGameConceteControllerConstruction extends ConcreteControllerConstruction {
private GameMemory mem;
public SafetyGameConceteControllerConstruction(GameMemory mem, GameModel m) {
super(mem, m);
this.mem = mem;
}
@Override
public EnumStrategyI calculateConcreteController() throws AbstractGamesException {
Stack<EnumStateI> st_stack = new Stack<EnumStateI>();
BDDVarSet envUnprimedVars = env.moduleUnprimeVars();
BDDVarSet sysUnprimedVars = sys.moduleUnprimeVars();
EnumStrategyImpl aut = new EnumStrategyImpl();
for (BDDIterator it = env.initial().iterator(envUnprimedVars); it.hasNext();) {
BDD envIni = it.nextBDD();
BDD iniWin = envIni.andWith(getWinningInitialStates());
BDD oneIni = CoreUtil.satOne(iniWin, envUnprimedVars.union(sysUnprimedVars));
st_stack.push(aut.getState(oneIni, null));
}
System.out.println("Initial states of environment: " + st_stack.size());
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
EnumStateI new_state = st_stack.pop();
BDD p_st = new_state.getData();
BDD good_suc = env.succ(p_st).andWith(mem.getWin().id());
BDD one_cand = CoreUtil.satOne(good_suc, envUnprimedVars.union(sysUnprimedVars));
good_suc.free();
// add succ
EnumStateI succ = aut.addSuccessorState(new_state, one_cand, null);
if (succ != null) {
// if a new state was created.
st_stack.push(succ);
}
}
return aut;
}
private BDD getWinningInitialStates() {
return mem.getWin().and(sys.initial());
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.gr1;
import java.util.List;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.lib.FixPoint;
/**
*
* Realizability checking for GR(1)* specifications as presented in FM'19.
*
*
* @author <NAME>
* @author <NAME>
*
*/
public class GR1GameExistentialFM19Memoryless extends GR1Game {
public GR1GameExistentialFM19Memoryless(GameModel model) {
super(model);
}
@Override
public boolean checkRealizability() {
BDD z = Env.TRUE(), nextZ, V;
FixPoint iterZ;
V = (model.getSys().existReqNum() > 0) ? computeJusticeAssumptionViolation() : Env.FALSE();
for (iterZ = new FixPoint(true); iterZ.advance(z);) {
nextZ = Env.TRUE();
for (int k = 0; k < model.getSys().existReqNum(); k++) {
nextZ.andWith(computeExistentialBdd(z, model.getSys().existReqAt(k).getExistFinallyAssrts()));
}
nextZ.andWith(computeJusticeIteration(z));
nextZ.orWith(V.id());
z = nextZ;
}
mem.setWin(z);
mem.setComplete(true);
iterZ.free();
return sysWinAllInitial(z);
}
/**
* GR(1) part: justice assumptions and justice guarantees
*
* @param z
* @return
*/
private BDD computeJusticeIteration(BDD z) {
BDD x, y, zApprox = z.id();
FixPoint iterY, iterX;
for (int j = 0; j < sys.justiceNum(); j++) {
BDD yieldZandJj = sys.justiceAt(j).id().andWith(env.yieldStates(sys, zApprox));
y = Env.FALSE();
for (iterY = new FixPoint(true); iterY.advance(y);) {
BDD start = yieldZandJj.id().orWith(env.yieldStates(sys, y));
y = Env.FALSE();
for (int i = 0; i < env.justiceNum(); i++) {
BDD negp = env.justiceAt(i).not();
x = zApprox.id();
for (iterX = new FixPoint(true); iterX.advance(x);) {
BDD sysCtrl = env.yieldStates(sys, x);
BDD sysCtrlAndNotJustice = sysCtrl.and(negp);
sysCtrl.free();
x = sysCtrlAndNotJustice.or(start);
sysCtrlAndNotJustice.free();
}
y.orWith(x);
iterX.free();
negp.free();
}
start.free();
}
zApprox.free();
zApprox = y;
iterY.free();
yieldZandJj.free();
}
return zApprox;
}
/**
* Existential guarantees
*
* @param z
* @param assertions
* @return
*/
private BDD computeExistentialBdd(BDD z, List<BDD> assertions) {
BDD currAssrt, nextTarget = z.id(), y, oldNextTarget;
if(assertions != null) {
FixPoint iterY;
for (int i = assertions.size() - 1; i >= 0; i--) {
currAssrt = assertions.get(i);
y = Env.FALSE();
for (iterY = new FixPoint(true); iterY.advance(y);) {
y = currAssrt.and(nextTarget).orWith(z.id().andWith(env.pred(sys, y)));
}
oldNextTarget = nextTarget;
nextTarget = y;
oldNextTarget.free();
iterY.free();
}
}
return nextTarget;
}
/**
* Justice assumptions violation
*
* @return
*/
private BDD computeJusticeAssumptionViolation() {
BDD x, y, cPreY, sysCtrl, sysCtrlAndNotJustice, negJe;
FixPoint iterY, iterX;
y = Env.FALSE();
for (iterY = new FixPoint(true); iterY.advance(y);) {
cPreY = env.yieldStates(sys, y);
y = Env.FALSE();
for (int i = 0; i < env.justiceNum(); i++) {
negJe = env.justiceAt(i).not();
x = Env.TRUE();
for (iterX = new FixPoint(true); iterX.advance(x);) {
sysCtrl = env.yieldStates(sys, x);
sysCtrlAndNotJustice = sysCtrl.and(negJe);
sysCtrl.free();
x = sysCtrlAndNotJustice.or(cPreY);
sysCtrlAndNotJustice.free();
}
y.orWith(x);
iterX.free();
negJe.free();
}
cPreY.free();
}
iterY.free();
return y;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games;
import java.util.Vector;
import net.sf.javabdd.BDD;
public abstract class GameIncrementalMemory {
public boolean NEW_INI_ADDED = false;
public boolean NEW_SAFETY_ADDED = false;
public boolean NEW_JUSTICE_ADDED = false;
public boolean PREV_INI_REMOVED = false;
public boolean PREV_SAFETY_REMOVED = false;
public boolean PREV_JUSTICE_REMOVED = false;
public int leastRemovedJusticeIdx = 0;
public BDD startZ = null;
abstract public void addToStartZ(BDD z, int idx);
public int getIncTypeBitmap()
{
int typeBitmap = 0;
// NOTE: the bitmap needs to correspond to the enum values in the C code.
// typedef enum INC_TYPE {
// INC_TYPE_NO_INC = 0,
// INC_TYPE_NEW_INI_ADDED = 1,
// INC_TYPE_NEW_SAFETY_ADDED =2,
// INC_TYPE_NEW_JUSTICE_ADDED = 4,
// INC_TYPE_PREV_INI_REMOVED = 8,
// INC_TYPE_PREV_SAFETY_REMOVED = 16,
// INC_TYPE_PREV_JUSTICE_REMOVED = 32
// } inc_type;
if (NEW_INI_ADDED) typeBitmap |= 1;
if (NEW_SAFETY_ADDED) typeBitmap |= 2;
if (NEW_JUSTICE_ADDED) typeBitmap |= 4;
if (PREV_INI_REMOVED) typeBitmap |= 8;
if (PREV_SAFETY_REMOVED) typeBitmap |= 16;
if (PREV_JUSTICE_REMOVED) typeBitmap |= 32;
return typeBitmap;
}
abstract public void setPrevFirstZIterMem(BDD[] prevFirstZIterMem);
abstract public void setPrevZMemory(BDD[] prevMem);
abstract public void setPrevXMem(BDD[][][] xMem);
abstract public void setPrevMem(Vector<BDD> zMem, Vector<Vector<Vector<BDD>>> xMem);
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinputtrans.translator;
import java.util.ArrayList;
import java.util.List;
import tau.smlab.syntech.gameinput.model.Constraint;
import tau.smlab.syntech.gameinput.model.Counter;
import tau.smlab.syntech.gameinput.model.DefineArray;
import tau.smlab.syntech.gameinput.model.ExistentialConstraint;
import tau.smlab.syntech.gameinput.model.GameInput;
import tau.smlab.syntech.gameinput.model.Pattern;
import tau.smlab.syntech.gameinput.model.Predicate;
import tau.smlab.syntech.gameinput.model.RegexpTestModel;
import tau.smlab.syntech.gameinput.model.TriggerConstraint;
import tau.smlab.syntech.gameinput.model.WeightDefinition;
import tau.smlab.syntech.gameinput.spec.DefineReference;
import tau.smlab.syntech.gameinput.spec.Spec;
import tau.smlab.syntech.gameinput.spec.SpecExp;
import tau.smlab.syntech.gameinput.spec.SpecHelper;
import tau.smlab.syntech.gameinput.spec.SpecRegExp;
import tau.smlab.syntech.gameinputtrans.TranslationException;
/**
* iterate over all specs (in guarantees, assumptions, auxiliary constraints,
* weight definition, patterns?, predicates)
*
* if spec contains a DefineReference replace it by the spec of the define
*
* finally delete the list of defines
*
* Depends on : VarIndexesTranslator, QuantifierTranslator
*
*/
public class DefinesTranslator implements Translator {
@Override
public void translate(GameInput input) {
if (noWorkToDo(input)) {
return;
}
// guarantees
for (Constraint c : input.getSys().getConstraints()) {
c.setSpec(replaceDefines(c.getSpec(), c.getTraceId()));
}
// sys existential constraints
for (ExistentialConstraint exC : input.getSys().getExistentialConstraints()) {
if(exC.isRegExp()) {
SpecRegExp regExp = exC.getRegExp();
for(SpecRegExp predRegExp : regExp.getPredicateSubExps()) {
predRegExp.setPredicate(replaceDefines(predRegExp.getPredicate(), 0));
}
}
else {
for(int i = 0; i < exC.getSize() ; i++) {
exC.replaceSpec(i, replaceDefines(exC.getSpec(i), exC.getTraceId()));
}
}
}
// regexp tests
for (RegexpTestModel reT : input.getRegtestExpressions()) {
SpecRegExp regExp = reT.getRegExp();
for(SpecRegExp predRegExp : regExp.getPredicateSubExps()) {
predRegExp.setPredicate(replaceDefines(predRegExp.getPredicate(), 0));
}
}
// sys triggers
replaceDefinesInTriggers(input.getSys().getTriggers());
// assumptions
for (Constraint c : input.getEnv().getConstraints()) {
c.setSpec(replaceDefines(c.getSpec(), c.getTraceId()));
}
// env triggers
replaceDefinesInTriggers(input.getEnv().getTriggers());
// auxiliary constraints
for (Constraint c : input.getAux().getConstraints()) {
c.setSpec(replaceDefines(c.getSpec(), c.getTraceId()));
}
// weight definition
for (WeightDefinition wd : input.getWeightDefs()) {
Constraint c = wd.getDefinition();
c.setSpec(replaceDefines(c.getSpec(), c.getTraceId()));
}
// patterns
for (Pattern patt : input.getPatterns()) {
for (Constraint c : patt.getExpressions()) {
c.setSpec(replaceDefines(c.getSpec(), c.getTraceId()));
}
}
// predicates
for (Predicate pred : input.getPredicates()) {
pred.setSpec(replaceDefines(pred.getExpression(), pred.getTraceId()));
}
for (Counter counter : input.getCounters()) {
if (counter.getDecPred() != null) {
counter.getDecPred().setContent(replaceDefines(counter.getDecPred().getContent(), counter.getTraceId()));
}
if (counter.getIncPred() != null) {
counter.getIncPred().setContent(replaceDefines(counter.getIncPred().getContent(), counter.getTraceId()));
}
if (counter.getIniPred() != null) {
counter.getIniPred().setContent(replaceDefines(counter.getIniPred().getContent(), counter.getTraceId()));
}
if (counter.getResetPred() != null) {
counter.getResetPred().setContent(replaceDefines(counter.getResetPred().getContent(), counter.getTraceId()));
}
}
// clear the list of the defines
input.getDefines().clear();
}
private void replaceDefinesInTriggers(List<TriggerConstraint> moduleTriggers) {
SpecRegExp initSpecRegExp, effectSpecRegExp;
for(TriggerConstraint trigger : moduleTriggers) {
initSpecRegExp = trigger.getInitSpecRegExp();
for(SpecRegExp predRegExp : initSpecRegExp.getPredicateSubExps()) {
predRegExp.setPredicate(replaceDefines(predRegExp.getPredicate(), 0));
}
effectSpecRegExp = trigger.getEffectSpecRegExp();
for(SpecRegExp predRegExp : effectSpecRegExp.getPredicateSubExps()) {
predRegExp.setPredicate(replaceDefines(predRegExp.getPredicate(), 0));
}
}
}
private boolean noWorkToDo(GameInput input) {
return input.getDefines() == null || input.getDefines().isEmpty();
}
private Spec replaceDefines(Spec spec, int traceId) {
if (spec instanceof DefineReference) {
DefineReference dr = (DefineReference) spec;
// important: spec = dr.getDefine().getExpression() isn't enough! there might be nested defines.
try {
DefineReference newdr = dr.clone();
if (newdr.getIndexSpecs() != null) {
List<Spec> indexSpecs = new ArrayList<>();
for (Spec indexSpec : newdr.getIndexSpecs()) {
indexSpecs.add(replaceDefines(indexSpec, traceId));
}
newdr.setIndexSpecs(indexSpecs);
}
// Single define
if (newdr.getDefine().getExpression() != null) {
newdr.getDefine().setExpression(replaceDefines(newdr.getDefine().getExpression(), traceId));
return newdr.getDefine().getExpression();
}
// Multiple define
newdr.getDefine().setDefineArray(replaceDefinesInDefineArrays(newdr.getDefine().getDefineArray(), traceId));
if (newdr.getIndexVars().isEmpty()) {
return extractSpecFromDefine(newdr.getIndexSpecs(), 0, newdr.getDefine().getDefineArray());
}
return newdr;
} catch (Exception e) {
throw new TranslationException(e.getMessage(), traceId);
}
} else if (spec instanceof SpecExp) {
try {
SpecExp se = ((SpecExp) spec).clone();
for (int i = 0; i < se.getChildren().length; i++) {
se.getChildren()[i] = replaceDefines(se.getChildren()[i], traceId);
}
return se;
} catch (Exception e) {
throw new TranslationException(e.getMessage(), traceId);
}
}
return spec;
}
private Spec extractSpecFromDefine(List<Spec> indexSpec, int index, DefineArray defArray) throws Exception {
Integer indexValue = SpecHelper.calculateSpec(indexSpec.get(index));
if (index == indexSpec.size() - 1) {
if (defArray.getExpressions() == null || defArray.getExpressions().size() == 0) {
throw new Exception("Invalid access to a define array, too few []");
}
if (defArray.getExpressions().size() <= indexValue) {
throw new Exception("Invalid access to a define array, out of bounds");
}
return defArray.getExpressions().get(indexValue);
} else {
if (defArray.getDefineArray() == null || defArray.getDefineArray().size() == 0) {
throw new Exception("Invalid access to a define array, too many []");
}
if (defArray.getDefineArray().size() <= indexValue) {
throw new Exception("Invalid access to a define array, out of bounds");
}
return extractSpecFromDefine(indexSpec, index + 1, defArray.getDefineArray().get(indexValue));
}
}
private DefineArray replaceDefinesInDefineArrays(DefineArray defArray, int traceId) {
List<Spec> newSpec = null;
if (defArray.getExpressions() != null) {
newSpec = new ArrayList<>();
for (Spec exp : defArray.getExpressions()) {
newSpec.add(replaceDefines(exp, traceId));
}
}
List<DefineArray> newDefArray = null;
if (defArray.getDefineArray() != null) {
newDefArray = new ArrayList<>();
for (DefineArray innerArray : defArray.getDefineArray()) {
newDefArray.add(replaceDefinesInDefineArrays(innerArray, traceId));
}
}
return new DefineArray(newSpec, newDefArray);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.symbolic;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.games.controller.jits.SymbolicControllerExistentialJitInfo;
import tau.smlab.syntech.games.controller.jits.SymbolicControllerJitInfo;
import tau.smlab.syntech.games.util.SaveLoadWithDomains;
import tau.smlab.syntech.jtlv.Env;
public class SymbolicControllerReaderWriter {
protected final static String CONTROLLER_INIT = "controller.init.bdd";
protected final static String CONTROLLER_TRANS = "controller.trans.bdd";
protected final static String VARS = "vars.doms";
protected final static String SIZES = "sizes";
protected final static String EXT_SIZES = "existential_sizes";
protected final static String FIXPOINTS = "fixpoints.bdd";
protected final static String TRANS = "trans.bdd";
protected final static String JUSTICE = "justice.bdd";
protected final static String FULFILL = "fulfill.bdd";
protected final static String TOWARDS = "towards.bdd";
protected final static String ENV_VIOLATION = "envviolation.bdd";
/**
* loads a symbolic controller from a file path
*
* Also loads and creates all BDD variables needed for it!
*
* @param path
* @return
* @throws IOException
*/
public static SymbolicController readSymbolicController(ObjectInputStream ois, BufferedReader initReader,
BufferedReader transReader) throws IOException {
// TODO: not implemented yet
return null;
}
public static void writeSymbolicController(SymbolicController ctrl, GameModel model, String path, boolean reorderBeforeSave) throws IOException {
writeSymbolicController(ctrl, model, path, null, reorderBeforeSave);
}
/**
* stores a symbolic controller to a file path
*
* @param ctrl
* @param model
* @param path needs to be a folder name (folder will be created if not exists)
* @param name name of the controller
*/
public static void writeSymbolicController(SymbolicController ctrl, GameModel model, String path, String name, boolean reorderBeforeSave) throws IOException {
// write the actual symbolic controller BDDs and doms
Env.disableReorder();
File folder = new File(path);
if (!folder.exists()) {
folder.mkdirs();
}
String prefix;
if (name == null) {
prefix = path + File.separator;
} else {
prefix = path + File.separator + name + ".";
}
SaveLoadWithDomains.saveStructureAndDomains(prefix + VARS, model);
Env.saveBDD(prefix + CONTROLLER_INIT, ctrl.initial(), reorderBeforeSave);
Env.saveBDD(prefix + CONTROLLER_TRANS, ctrl.trans(), reorderBeforeSave);
}
public static void writeJitSymbolicController(SymbolicControllerJitInfo jitInfo, GameModel model, String path, boolean reorderBeforeSave) throws IOException {
writeJitSymbolicController(jitInfo, model, path, null, reorderBeforeSave);
}
/**
* stores a symbolic controller just in time info to a file path
*
* @param jitInfo
* @param model
* @param path
* @param name of the controller
* @param reorderBeforeSave
* @throws IOException
*/
public static void writeJitSymbolicController(SymbolicControllerJitInfo jitInfo, GameModel model, String path, String name, boolean reorderBeforeSave) throws IOException {
File folder = new File(path);
if (!folder.exists()) {
folder.mkdirs();
}
String prefix;
if (name == null) {
prefix = path + File.separator;
} else {
prefix = path + File.separator + name + ".";
}
FileWriter sizesWriter = new FileWriter(prefix + SIZES);
sizesWriter.write(model.getSys().justiceNum() + System.lineSeparator() + model.getEnv().justiceNum() + System.lineSeparator());
for (int j = 0; j < model.getSys().justiceNum(); j++) {
sizesWriter.write((jitInfo.ranks(j) - 1) + System.lineSeparator());
}
sizesWriter.close();
SaveLoadWithDomains.saveStructureAndDomains(prefix + VARS, model);
Env.saveBDD(prefix + FIXPOINTS, jitInfo.fixpoints(), reorderBeforeSave);
Env.saveBDD(prefix + TRANS, jitInfo.safeties(), reorderBeforeSave);
Env.saveBDD(prefix + JUSTICE, jitInfo.justices(), reorderBeforeSave);
if (model.getSys().hasExistReqs()) {
SymbolicControllerExistentialJitInfo extJitInfo = (SymbolicControllerExistentialJitInfo) jitInfo;
sizesWriter = new FileWriter(prefix + EXT_SIZES);
sizesWriter.write(model.getSys().existReqNum() + System.lineSeparator());
for (int exj = 0; exj < model.getSys().existReqNum(); exj++) {
sizesWriter.write((extJitInfo.fulfillRanks(exj) - 1) + System.lineSeparator());
}
for (int exj = 0; exj < model.getSys().existReqNum(); exj++) {
sizesWriter.write((extJitInfo.towardsRanks(exj) - 1) + System.lineSeparator());
}
sizesWriter.write(extJitInfo.envViolationRank() + System.lineSeparator());
sizesWriter.close();
Env.saveBDD(prefix + FULFILL, extJitInfo.fulfill(), reorderBeforeSave);
Env.saveBDD(prefix + TOWARDS, extJitInfo.towards(), reorderBeforeSave);
Env.saveBDD(prefix + ENV_VIOLATION, extJitInfo.envViolation(), reorderBeforeSave);
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinputtrans.translator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import tau.smlab.syntech.gameinput.model.Constraint;
import tau.smlab.syntech.gameinput.model.Counter;
import tau.smlab.syntech.gameinput.model.Define;
import tau.smlab.syntech.gameinput.model.DefineArray;
import tau.smlab.syntech.gameinput.model.ExistentialConstraint;
import tau.smlab.syntech.gameinput.model.GameInput;
import tau.smlab.syntech.gameinput.model.Monitor;
import tau.smlab.syntech.gameinput.model.RegexpTestModel;
import tau.smlab.syntech.gameinput.model.TriggerConstraint;
import tau.smlab.syntech.gameinput.model.Variable;
import tau.smlab.syntech.gameinput.model.WeightDefinition;
import tau.smlab.syntech.gameinput.spec.MonitorReference;
import tau.smlab.syntech.gameinput.spec.Spec;
import tau.smlab.syntech.gameinput.spec.SpecExp;
import tau.smlab.syntech.gameinput.spec.SpecRegExp;
import tau.smlab.syntech.gameinput.spec.VariableReference;
/**
* This translator removes monitors from GameInput in two steps:
* <ul>
* <li>Translates monitors to auxiliary variables and adds auxiliary
* constraints.</li>
* <li>Replaces references to monitors by references to the auxiliary
* variables.</li>
* </ul>
*
* The replacement must happen in all places where monitors could be referenced,
* i.e., this code needs to know about other structures in the GameInput.
*
*/
public class MonitorTranslator implements Translator {
protected Map<String, List<Constraint>> monitorConstraints = new HashMap<>();;
protected Map<String, Set<Integer>> traceIdsByMonitor = new HashMap<>();
protected List<String> monitorNameList = new ArrayList<>();
@Override
public void translate(GameInput input) {
if (noWorkToDo(input)) {
return;
}
// translate monitors
Map<String, Variable> monVars = translateMonitors(input);
// replace the monitor references in
// guarantees
for (Constraint c : input.getSys().getConstraints()) {
c.setSpec(replaceMonRefs(monVars, c.getSpec()));
}
// sys existential constraints
for (ExistentialConstraint exC : input.getSys().getExistentialConstraints()) {
if (exC.isRegExp()) {
SpecRegExp regExp = exC.getRegExp();
for (SpecRegExp predRegExp : regExp.getPredicateSubExps()) {
predRegExp.setPredicate(replaceMonRefs(monVars, predRegExp.getPredicate()));
}
} else {
for (int i = 0; i < exC.getSize(); i++) {
exC.replaceSpec(i, replaceMonRefs(monVars, exC.getSpec(i)));
}
}
}
// regexp test
for (RegexpTestModel reT : input.getRegtestExpressions()) {
SpecRegExp regExp = reT.getRegExp();
for (SpecRegExp predRegExp : regExp.getPredicateSubExps()) {
predRegExp.setPredicate(replaceMonRefs(monVars, predRegExp.getPredicate()));
}
}
// sys triggers
replaceMonRefsInTriggers(monVars, input.getSys().getTriggers());
// assumptions
for (Constraint c : input.getEnv().getConstraints()) {
c.setSpec(replaceMonRefs(monVars, c.getSpec()));
}
// env triggers
replaceMonRefsInTriggers(monVars, input.getEnv().getTriggers());
// auxiliary constraints
for (Constraint c : input.getAux().getConstraints()) {
c.setSpec(replaceMonRefs(monVars, c.getSpec()));
}
// defines
for (Define d : input.getDefines()) {
if (d.getExpression() != null) {
d.setExpression(replaceMonRefs(monVars, d.getExpression()));
} else {
d.setDefineArray(replaceMonitorInDefineArrays(monVars, d.getDefineArray()));
}
}
// weight definition
for (WeightDefinition wd : input.getWeightDefs()) {
Constraint c = wd.getDefinition();
c.setSpec(replaceMonRefs(monVars, c.getSpec()));
}
// counters
for (Counter counter : input.getCounters()) {
if (counter.getDecPred() != null) {
counter.getDecPred().setContent(replaceMonRefs(monVars, counter.getDecPred().getContent()));
}
if (counter.getIncPred() != null) {
counter.getIncPred().setContent(replaceMonRefs(monVars, counter.getIncPred().getContent()));
}
if (counter.getIniPred() != null) {
counter.getIniPred().setContent(replaceMonRefs(monVars, counter.getIniPred().getContent()));
}
if (counter.getResetPred() != null) {
counter.getResetPred().setContent(replaceMonRefs(monVars, counter.getResetPred().getContent()));
}
}
input.getMonitors().clear();
}
/**
* replace the monitor references by references to the new variables
*
* @param monVars
* @param spec
* @return
*/
private Spec replaceMonRefs(Map<String, Variable> monVars, Spec spec) {
if (spec instanceof MonitorReference) {
// replace monitor reference by aux var
String name = ((MonitorReference) spec).getMonitor().getName();
return new VariableReference(monVars.get(name));
} else if (spec instanceof SpecExp) {
// replace references in all children
SpecExp se = (SpecExp) spec;
for (int i = 0; i < se.getChildren().length; i++) {
se.getChildren()[i] = replaceMonRefs(monVars, se.getChildren()[i]);
}
}
// nothing to do
return spec;
}
/**
* Translate all monitors by creating auxiliary variables and creating auxiliary
* constraints.
*
* @param input
* @return
*/
private Map<String, Variable> translateMonitors(GameInput input) {
Map<String, Variable> monVars = new HashMap<>();
Set<Integer> traceIdsSet;
List<Constraint> monConstList;
for (Monitor mon : input.getMonitors()) {
// maintain a list of all monitor names
monitorNameList.add(mon.getName());
// create auxiliary variable for monitor
Variable v = new Variable(mon.getName(), mon.getType());
input.getAux().addVar(v);
monVars.put(mon.getName(), v);
// maintain a traceIds set of the monitor's constraints
traceIdsSet = new HashSet<>();
traceIdsByMonitor.put(mon.getName(), traceIdsSet);
// maintain a list of the monitor's constraints
monConstList = new ArrayList<>();
monitorConstraints.put(mon.getName(), monConstList);
for (Constraint c : mon.getExpressions()) {
// add monitoring constraints to AUX player
input.getAux().addConstraint(c);
// add the current constraint c and its traceId
traceIdsSet.add(c.getTraceId());
monConstList.add(c);
}
}
return monVars;
}
public List<Constraint> getMonitorConstraints(String MonName) {
return monitorConstraints.get(MonName);
}
public Set<Integer> getTraceIdsOfMonitor(String monName) {
return traceIdsByMonitor.get(monName);
}
public List<String> getMonitorsNames() {
return monitorNameList;
}
private DefineArray replaceMonitorInDefineArrays(Map<String, Variable> monVars, DefineArray defArray) {
List<Spec> newSpec = null;
if (defArray.getExpressions() != null) {
newSpec = new ArrayList<>();
for (Spec exp : defArray.getExpressions()) {
newSpec.add(replaceMonRefs(monVars, exp));
}
}
List<DefineArray> newDefArray = null;
if (defArray.getDefineArray() != null) {
newDefArray = new ArrayList<>();
for (DefineArray innerArray : defArray.getDefineArray()) {
newDefArray.add(replaceMonitorInDefineArrays(monVars, innerArray));
}
}
return new DefineArray(newSpec, newDefArray);
}
private boolean noWorkToDo(GameInput input) {
return input.getMonitors() == null || input.getMonitors().isEmpty();
}
private void replaceMonRefsInTriggers(Map<String, Variable> monVars, List<TriggerConstraint> moduleTriggers) {
SpecRegExp initSpecRegExp, effectSpecRegExp;
for (TriggerConstraint trigger : moduleTriggers) {
initSpecRegExp = trigger.getInitSpecRegExp();
for (SpecRegExp predRegExp : initSpecRegExp.getPredicateSubExps()) {
predRegExp.setPredicate(replaceMonRefs(monVars, predRegExp.getPredicate()));
}
effectSpecRegExp = trigger.getEffectSpecRegExp();
for (SpecRegExp predRegExp : effectSpecRegExp.getPredicateSubExps()) {
predRegExp.setPredicate(replaceMonRefs(monVars, predRegExp.getPredicate()));
}
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.enumerate;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Vector;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.games.AbstractGamesException;
import tau.smlab.syntech.jtlv.Env;
public class EnumStrategyImpl implements EnumStrategyI {
// ////////////////////////////////////////////////////////////////////////
// the instance implementation of the result.
private Vector<EnumStateI> aut;
private Map<AbstractRankInfo, BDD> statesOfRank;
private Map<AbstractRankInfo, Map<BDD, EnumStateI>> allStatesOfRank;
private long wakeup_time = -1;
// updating the construction time every time something is changed
// (getState, when new state needs to be created, and addNextState).
private long construction_time = -1;
private int numTransitions;
private int lenLongestShortestPath;
private int maxNumOutEdgesPerState;
private int maxNumInEdgesPerState;
private boolean calcLenLongestShortestPath;
public EnumStrategyImpl() {
this(false);
}
public EnumStrategyImpl(boolean calcStats) {
aut = new Vector<EnumStateI>();
statesOfRank = new HashMap<AbstractRankInfo, BDD>();
allStatesOfRank = new HashMap<>();
wakeup_time = System.currentTimeMillis();
numTransitions = 0;
maxNumOutEdgesPerState = 0;
maxNumInEdgesPerState = 0;
calcLenLongestShortestPath = calcStats;
}
/**
* looks up a state or adds it to the automaton
*
* if the state is not already in the automaton it is created as an initial state
*/
@Override
public EnumStateI getState(BDD state, AbstractRankInfo rank) {
EnumStateI s = lookUpState(state, rank);
if (s != null)
return s;
// else need to create state
EnumStateI res = new EnumStateImpl(this, aut.size(), true, state, rank);
aut.add(res);
addState(res);
construction_time = System.currentTimeMillis() - wakeup_time;
return res;
}
@Override
public EnumStateI getState(int id) throws ArrayIndexOutOfBoundsException {
return aut.get(id);
}
// when doing together we could save an exhaustive search here.
// returns the newly created state id or -1 if no state was created
@Override
public EnumStateI addSuccessorState(EnumStateI from, BDD state,
AbstractRankInfo rank) throws AbstractGamesException {
from.incNumOutEdges();
this.maxNumOutEdgesPerState = Math.max(from.getNumOutEdges(), this.maxNumOutEdgesPerState);
EnumStateI succ = lookUpState(state, rank);
if (succ != null) {
succ.incNumInEdges();
this.maxNumInEdgesPerState = Math.max(succ.getNumInEdges(), this.maxNumInEdgesPerState);
if (this.calcLenLongestShortestPath) {
boolean updated = succ.updateDistFromIni(from.getDistFromIni());
if (updated) {
// this calculation can be expensive, which is why we only perform it when the user
// explicitly states he requires it via calcLenLongestSimplePath flag
LinkedList<EnumStateI> workList = new LinkedList<EnumStateI>();
workList.add(succ);
while (!workList.isEmpty()) {
EnumStateI currSucc = workList.pop();
Vector<EnumStateI> succs = currSucc.getSuccessors();
for (EnumStateI elem: succs) {
updated = elem.updateDistFromIni(currSucc.getDistFromIni());
if (updated) {
workList.add(elem);
}
}
}
}
}
this.lenLongestShortestPath = Math.max(succ.getDistFromIni(), this.lenLongestShortestPath);
from.addSuccessor(succ);
construction_time = System.currentTimeMillis() - wakeup_time;
numTransitions++;
return null;
}
// else succ not existent
EnumStateI to = new EnumStateImpl(this, aut.size(), false, state, rank);
aut.add(to);
addState(to);
to.incNumInEdges();
this.maxNumInEdgesPerState = Math.max(to.getNumInEdges(), this.maxNumInEdgesPerState);
if (this.calcLenLongestShortestPath) {
to.updateDistFromIni(from.getDistFromIni());
this.lenLongestShortestPath = Math.max(to.getDistFromIni(), this.lenLongestShortestPath);
}
from.addSuccessor(to);
construction_time = System.currentTimeMillis() - wakeup_time;
numTransitions++;
return to;
}
/**
* lookup a state we already created
*
* @param state
* @param rank
* @return null if state is not found
*/
private EnumStateI lookUpState(BDD state, AbstractRankInfo rank) {
Map<BDD, EnumStateI> m = allStatesOfRank.get(rank);
if (m != null) {
EnumStateI s = m.get(state);
return s;
}
return null;
}
/**
* adds a state to statesOfRank and allStatesOfRank
*
* @param s
*/
private void addState(EnumStateI s) {
AbstractRankInfo rank = s.get_rank_info();
BDD sor = statesOfRank.get(rank);
if (sor == null) {
sor = Env.FALSE();
statesOfRank.put(rank, sor);
}
sor.orWith(s.getData().id());
Map<BDD, EnumStateI> m = allStatesOfRank.get(rank);
if (m == null) {
m = new HashMap<>();
allStatesOfRank.put(rank, m);
}
m.put(s.getData(), s);
}
/**
* for states with ReactiveRankInfo retrive all of given rank
*
* @param sys_just
* @return
*/
public BDD getStatesOfRank(AbstractRankInfo rank) {
if (statesOfRank.containsKey(rank)) {
return statesOfRank.get(rank);
}
return Env.FALSE();
}
@Override
public int numOfStates() {
return this.aut.size();
}
@Override
public long getConstructionTime() {
return this.construction_time;
}
@Override
public Vector<? extends StateI> getInitialStates() {
Vector<StateI> ret = new Vector<StateI>();
for (StateI st : enumController())
if (st.isInitial())
ret.add(st);
return ret;
}
@Override
public Vector<? extends StateI> getNextState(StateI st) {
if (st instanceof EnumStateI)
return ((EnumStateI) st).getSuccessors();
return new Vector<StateI>();
}
@Override
public Vector<? extends EnumStateI> enumController() {
return aut;
}
@Override
public Vector<? extends EnumStateI> enumController(StateI st) {
return aut;
}
@Override
public int numOfTransitions() {
return this.numTransitions;
}
@Override
public int lenLongestShortestPath() {
return this.lenLongestShortestPath;
}
@Override
public int maxNumOutEdgesPerState() {
return this.maxNumOutEdgesPerState;
}
@Override
public int maxNumInEdgesPerState() {
return this.maxNumInEdgesPerState;
}
@Override
public boolean isCalcStats() {
return this.calcLenLongestShortestPath;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinput.model;
import java.io.Serializable;
import java.util.List;
public class Monitor implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6681607472181997841L;
private int traceId;
private String name;
private TypeDef type;
private List<Constraint> expressions;
/**
*
* @param name
* @param expressions
* @param traceId
*/
public Monitor(String name, TypeDef type, List<Constraint> expressions, int traceId)
{
this.name = name;
this.expressions = expressions;
this.traceId = traceId;
this.type = type;
}
public int getTraceId() {
return traceId;
}
public String getName() {
return name;
}
public TypeDef getType() {
return type;
}
public List<Constraint> getExpressions() {
return expressions;
}
public void addExpressions(List<Constraint> exps) {
this.expressions.addAll(exps);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.rabin;
import java.util.Vector;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.games.GameMemory;
import tau.smlab.syntech.jtlv.Env;
/**
* winning staes of game memory are winning for the environment!
*
*/
public class RabinMemory extends GameMemory {
private Vector<BDD> zMem;
private Vector<Vector<Vector<BDD>>> xMem;
public RabinMemory() {
zMem = new Vector<BDD>();
xMem = new Vector<Vector<Vector<BDD>>>();
}
public RabinMemory(Vector<BDD> zMem, Vector<Vector<Vector<BDD>>> xMem) {
this.zMem = zMem;
this.xMem = xMem;
}
public int sizeZ() {
return zMem.size();
}
public int sizeX(int cz, int k) {
return xMem.get(cz).get(k).size();
}
public boolean addZ(BDD z) {
return zMem.add(z);
}
public BDD getZ(int zi) {
return zMem.get(zi);
}
public BDD getX(int layer, int justice, int xi) {
return xMem.get(layer).get(justice).get(xi);
}
public void addXLayer(int width) {
Vector<Vector<BDD>> layer = new Vector<Vector<BDD>>();
for (int i = 0; i < width; i++)
layer.add(new Vector<BDD>());
xMem.add(layer);
}
/**
* deletes all vectors in the MOST RECENT x layer and frees their BDDs
*/
public void clearXLayer() {
if (xMem != null && xMem.size() > 0) {
Vector<Vector<BDD>> layer = xMem.lastElement();
for (int i = 0; i < layer.size(); i++) {
Env.free(layer.get(i));
layer.get(i).clear();
}
}
}
public boolean addX(int justice, BDD x) {
return xMem.lastElement().get(justice).add(x);
}
public int getZRank(BDD s) {
for (int i = 0; i < zMem.size(); i++)
if (!(zMem.get(i).and(s).isZero()))
return i;
throw new NullPointerException("the following state is not in the"
+ " Z memory (is it winning for the environment?)\n" + Env.toNiceSignleLineString(s));
}
public int getXRank(int zRank, int k, BDD s) {
// int zRank = getZRank(s);
Vector<BDD> relevantMem = xMem.get(zRank).get(k);
for (int i = 0; i < relevantMem.size(); i++)
if (!(relevantMem.get(i).and(s).isZero()))
return i;
throw new NullPointerException("the following state is not in the" + " the X memory (something is wrong... )\n"
+ Env.toNiceSignleLineString(s));
}
/**
* frees all BDDs in the x and z memory
*/
@Override
public void free() {
super.free();
Env.free(xMem);
Env.free(zMem);
}
public Vector<BDD> getZMem() {
return zMem;
}
public Vector<Vector<Vector<BDD>>> getXMem() {
return xMem;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.gr1;
import java.util.Map;
import java.util.Map.Entry;
import net.sf.javabdd.ADD;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDFactory;
import tau.smlab.syntech.gamemodel.PlayerModule;
import tau.smlab.syntech.jtlv.Env;
public abstract class AbstractADDAlgorithm {
protected PlayerModule env;
protected PlayerModule sys;
protected Map<Integer, BDD> weights;
public AbstractADDAlgorithm(PlayerModule env, PlayerModule sys, Map<Integer, BDD> weights) {
this.env = env;
this.sys = sys;
this.weights = weights;
}
/**
* weighted arena
*/
private ADD arena;
/**
* the winning region, consists of all states that are winning for the system
*/
private ADD winningRegion;
/**
* the required energy level from states in the winning region
*
*/
private ADD winningRegionEng;
/**
* maximal initial energy (a bound for the algorithm)
*/
private double maxEng;
public double getMaxEng() {
return maxEng;
}
public void setMaxEng(double maxEng) {
this.maxEng = maxEng;
}
public ADD getWeightedArena() {
return this.arena;
}
public ADD getWinningRegion() {
return this.winningRegion;
}
/**
* check that new energy values are the same as old energy values
*
* @return
*/
protected boolean reachedFixPoint(ADD previous, ADD current) {
if (current != null && previous != null) {
return current.equals(previous);
}
return false;
}
protected void printInitialEnergy() {
double[] initEngVals, engVals;
ADD initStatesEng, nonInitStatesEng;
ADD states = this.winningRegionEng;
String printStr = "Winning region required energy levels";
if (states != null) {
initStatesEng = (ADD) (env.initial().and(sys.initial())).ite(states, Env.PLUS_INF());
nonInitStatesEng = (ADD) (env.initial().and(sys.initial())).ite(Env.PLUS_INF(), states);
engVals = nonInitStatesEng.getTerminalValues();
initEngVals = initStatesEng.getTerminalValues();
System.out.println("Initial states required energy levels:");
for (int i = 0; i < initEngVals.length; i++) {
if (initEngVals[i] != Env.PLUS_INF().getConstantValue()) {
System.out.print(initEngVals[i] + ", ");
}
}
System.out.println(System.lineSeparator());
System.out.println(printStr);
for (int i = 0; i < engVals.length; i++) {
if (engVals[i] != Env.PLUS_INF().getConstantValue()) {
System.out.print(engVals[i] + ", ");
}
}
System.out.println(System.lineSeparator());
initStatesEng.free();
}
}
/**
* create arena with:
* <ul>
* <li>system deadlocks: -INF</li>
* <li>environment deadlocks: +INF</li>
* <li>all other transitions: weight as defined</li>
* <ul>
*
* @return
*/
private ADD computeWeightedArena() {
ADD deadlocks = (ADD) env.trans().ite(Env.MINUS_INF(), Env.PLUS_INF());
ADD weightedArena = (ADD) Env.FALSE();
for (Entry<Integer, BDD> w : weights.entrySet()) {
ADD tmp = (ADD) w.getValue().ite(Env.CONST(w.getKey()), weightedArena);
weightedArena.free();
weightedArena = tmp;
}
BDD both = env.trans().and(sys.trans());
arena = (ADD) both.ite(weightedArena, deadlocks);
weightedArena.free();
return arena;
}
public ADD computeWinningRegion() {
this.arena = computeWeightedArena();
winningRegionEng = computeWinningRegionEng();
winningRegion = (ADD) toStates(winningRegionEng);
return winningRegion;
}
protected BDD toStates(ADD s) {
return s.toZeroOneSLTThreshold(Env.PLUS_INF().getConstantValue());
}
abstract protected ADD computeWinningRegionEng();
/**
* computes the states from which the system can force to current on the given
* arena respecting the bound maxEng
*
* @param current
* @param arena
* @return
*/
protected ADD cPre(ADD current) {
ADD pCurrent = (ADD) Env.prime(current);
ADD accEngByTarget = pCurrent.engSubtract(arena, maxEng);
ADD accEngSysMin = accEngByTarget.abstractMin(sys.modulePrimeVars());
ADD pre = accEngSysMin.abstractMax(env.modulePrimeVars());
pCurrent.free();
accEngByTarget.free();
accEngSysMin.free();
return pre;
}
public void free() {
arena.free();
winningRegion.free();
winningRegionEng.free();
}
/**
* returns an ADD where states in BDD have value 0 and all others infinity
*
* @param states
* @return
*/
protected ADD getADDForGoodStates(BDD states) {
BDD neg = states.not();
ADD res = ((ADD) neg).apply(Env.PLUS_INF(), BDDFactory.times);
neg.free();
return res;
}
/**
* intersection of sets of states represented by the ADD (implemented via
* maximum)
*
* @param a1
* @param a2
* @return
*/
protected ADD inter(ADD a1, ADD a2) {
return a1.apply(a2, BDDFactory.max);
}
/**
* intersection of sets of states represented by the ADD (implemented via
* maximum)
*
* @param a1
* @param a2
* @return
*/
protected ADD interWith(ADD a1, ADD a2) {
return a1.applyWith(a2, BDDFactory.max);
}
/**
* union of sets of states represented by the ADD (implemented via minimum)
*
* @param a1
* @param a2
* @return
*/
protected ADD union(ADD a1, ADD a2) {
return a1.apply(a2, BDDFactory.min);
}
/**
* union of sets of states represented by the ADD (implemented via minimum)
*
* @param a1
* @param a2
* @return
*/
protected ADD unionWith(ADD a1, ADD a2) {
return a1.applyWith(a2, BDDFactory.min);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.gr1;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.games.GameIncrementalMemory;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.lib.FixPoint;
public class GR1GameIncremental extends GR1GameImplC {
protected BDD[] firstZIterMem;
protected GR1GameIncrementalMemory incMem;
// protected BDD startZ = null;
// protected BDD[] prevZMem;
// protected BDD[] prevFirstZIterMem;
// protected BDD[][][] prevXMem;
//
// public boolean NEW_INI_ADDED = false;
// public boolean NEW_SAFETY_ADDED = false;
// public boolean NEW_JUSTICE_ADDED = false;
// public boolean PREV_INI_REMOVED = false;
// public boolean PREV_SAFETY_REMOVED = false;
// public boolean PREV_JUSTICE_REMOVED = false;
//
// public int leastRemovedJusticeIdx = 0;
public GR1GameIncremental(GameModel model) {
super(model);
incMem = new GR1GameIncrementalMemory();
}
// public void setStartZ(BDD startZ)
// {
// this.startZ = startZ;
// }
//
// public void setPrevZMemory(BDD[] prevMem)
// {
// this.prevZMem = prevMem;
// }
//
// public void setPrevFirstZIterMem(BDD[] prevFirstZIterMem)
// {
// this.prevFirstZIterMem = prevFirstZIterMem;
// }
//
// public void setPrevXMem(BDD[][][] xMem)
// {
// this.prevXMem = xMem;
// }
public GameIncrementalMemory GetGameIncrementalMemory() {
return incMem;
}
public BDD[] getZMemoryCopy() {
return incMem.getZMemoryCopy(mem.z_mem, sys.justiceNum());
}
// public BDD[] getZMemoryCopy(BDD[] z_mem)
// {
// BDD[] z_mem_copy = new BDD[sys.justiceNum()];
// for (int j = 0; j < z_mem.length; j++)
// {
// z_mem_copy[j] = z_mem[j].id();
// }
//
// return z_mem_copy;
// }
public BDD[][][] getXMemoryCopy() {
return incMem.getXMemoryCopy(mem.x_mem, 0, sys.justiceNum(), env.justiceNum());
}
// public BDD[][][] getXMemoryCopy(BDD[][][] x_mem, int x_currSize)
// {
// BDD[][][] x_mem_copy = new BDD[sys.justiceNum()][env.justiceNum()][];
//
// for (int j = 0; j < x_mem.length; j++)
// {
// for (int i = 0; i < x_mem[0].length; i++)
// {
// int cySize = x_mem[j][i].length;
// if (x_currSize > cySize) cySize = x_currSize;
// x_mem_copy[j][i] = new BDD[cySize];
// for (int k = 0; k < x_mem[j][i].length; k++)
// {
// x_mem_copy[j][i][k] = x_mem[j][i][k].id();
// }
// }
// }
//
// return x_mem_copy;
// }
public BDD[][] getPartialXMemoryCopy() {
BDD[][] x_mem = new BDD[sys.justiceNum()][env.justiceNum()];
for (int j = 0; j < sys.justiceNum(); j++) {
for (int i = 0; i < env.justiceNum(); i++) {
int lastXIdx = mem.x_mem[j][i].length - 1;
x_mem[j][i] = mem.x_mem[j][i][lastXIdx].id();
}
}
return x_mem;
}
public BDD[] getFirstZIterMem() {
BDD[] z_mem_copy = new BDD[sys.justiceNum()];
for (int j = 0; j < firstZIterMem.length; j++) {
z_mem_copy[j] = firstZIterMem[j].id();
}
return z_mem_copy;
}
// public void addToStartZ(BDD z, int idx)
// {
// System.out.println("Add to startZ: startZ.isOne = " + startZ.isOne() +
// ", segMem.zMem["+idx+"].isOne = " + z);
// BDD tmp = startZ;
// startZ = tmp.and(z);
// tmp.free();
// }
@Override
public boolean checkRealizability() {
mem.x_mem = new BDD[sys.justiceNum()][env.justiceNum()][50];
mem.y_mem = new BDD[sys.justiceNum()][50];
mem.z_mem = new BDD[sys.justiceNum()];
firstZIterMem = new BDD[sys.justiceNum()];
int zIterCount = 0;
@SuppressWarnings("unused")
int yIterCount = 0;
@SuppressWarnings("unused")
int xIterCount = 0;
if ((incMem.PREV_INI_REMOVED && !incMem.PREV_SAFETY_REMOVED && !incMem.PREV_JUSTICE_REMOVED)
|| (incMem.NEW_INI_ADDED && !incMem.NEW_SAFETY_ADDED && !incMem.NEW_JUSTICE_ADDED)) {
System.out.println("Only ini states changed: PREV_INI_REMOVED=" + incMem.PREV_INI_REMOVED
+ ", NEW_INI_ADDED=" + incMem.NEW_INI_ADDED);
BDD z = incMem.prevZMem[sys.justiceNum() - 1].id();
mem.x_mem = incMem.getXMemoryCopy(incMem.prevXMem, 0, sys.justiceNum(), env.justiceNum());
mem.z_mem = incMem.getZMemoryCopy(incMem.prevZMem, sys.justiceNum());
firstZIterMem = incMem.getZMemoryCopy(incMem.prevFirstZIterMem, sys.justiceNum());
mem.setWin(z);
mem.setComplete(true);
return sysWinAllInitial(z);
}
// if (!PREV_SAFETY_REMOVED && PREV_JUSTICE_REMOVED && leastRemovedJusticeIdx >
// 0)
// {
// System.out.println("previous justice was removed, leastRemovedJusticeIdx = "
// + leastRemovedJusticeIdx);
//// mem.x_mem = new
// BDD[sys.justiceNum()][env.justiceNum()][previousMem.x_mem.length];
//// mem.y_mem = new BDD[sys.justiceNum()][previousMem.y_mem.length];
//// mem.z_mem = new BDD[sys.justiceNum()];
// for (int j = 0; j < leastRemovedJusticeIdx; j++)
// {
// mem.z_mem[j] = prevFirstZIterMem[j].id(); //previousMem.z_mem[j].id();
// if (previousMem.y_mem[j].length / 50 > 1) {
// mem.y_mem = mem.extend_size(mem.y_mem, previousMem.y_mem[j].length);
// }
// for (int k = 0; k < previousMem.y_mem[j].length; k++) {
// mem.y_mem[j][k] = previousMem.y_mem[j][k].id();
// }
// for (int i = 0; i < env.justiceNum(); i++) {
// if (previousMem.x_mem[j][i].length / 50 > 1) {
// mem.x_mem = mem.extend_size(mem.x_mem, previousMem.x_mem[j][i].length);
// }
// for (int k = 0; k < previousMem.x_mem[j][i].length; k++) {
// mem.x_mem[j][i][k] = previousMem.x_mem[j][i][k].id();
// }
// }
// }
// }
// NOTE: The justices were removed only from the end of the list
// if (!PREV_SAFETY_REMOVED && leastRemovedJusticeIdx == sys.justiceNum() &&
// leastRemovedJusticeIdx != 0)
// {
// System.out.println("leastRemovedJusticeIdx = sys.justiceNum() = " +
// leastRemovedJusticeIdx);
// mem.setWin(mem.z_mem[sys.justiceNum() - 1]);
// mem.setComplete(previousMem.isComplete());
// mem.x_mem = mem.extend_size(mem.x_mem, 0);
// mem.y_mem = mem.extend_size(mem.y_mem, 0);
// //TODO: need to recompute or maybe not?
// return sysWinAllInitial(mem.z_mem[sys.justiceNum() - 1]);
// }
BDD x = null, y, z;
FixPoint iterZ, iterY, iterX;
int cy = 0;
boolean firstZItr = true;
z = Env.TRUE();
int jStartIdx = 0;
// if (!PREV_SAFETY_REMOVED && PREV_JUSTICE_REMOVED && leastRemovedJusticeIdx >
// 0)
// {
// System.out.println("previous justice was removed, leastRemovedJusticeIdx = "
// + leastRemovedJusticeIdx);
// for (int j = 0; j < leastRemovedJusticeIdx; j++)
// {
// mem.z_mem[j] = prevFirstZIterMem[j].id();
// firstZIterMem[j] = prevFirstZIterMem[j].id();
// }
//
// z = prevFirstZIterMem[leastRemovedJusticeIdx-1];
// jStartIdx = leastRemovedJusticeIdx;
// }
if (incMem.NEW_JUSTICE_ADDED && !incMem.NEW_SAFETY_ADDED && sys.justiceNum() != 1) {
System.out.println("New justice(s) was added, to an existing list of justices, "
+ "current sys.justiceNum() = " + sys.justiceNum());
jStartIdx = incMem.prevZMem.length;
mem.z_mem = incMem.getZMemoryCopy(incMem.prevZMem, sys.justiceNum());
// mem.x_mem = getXMemoryCopy(prevXMem, 50);
for (int j = 0; j < incMem.prevXMem.length; j++) {
for (int i = 0; i < incMem.prevXMem[j].length; i++) {
for (int k = 0; k < incMem.prevXMem[j][i].length; k++) {
mem.x_mem[j][i][k] = incMem.prevXMem[j][i][k].id();
}
}
}
firstZIterMem = incMem.getZMemoryCopy(incMem.prevFirstZIterMem, sys.justiceNum());
z = incMem.prevZMem[incMem.prevZMem.length - 1];
System.out.println(
"New justice was added, starting from jStartIdx=" + jStartIdx + " and z.isOne=" + z.isOne());
} else if (incMem.NEW_JUSTICE_ADDED || incMem.NEW_SAFETY_ADDED) {
System.out.println("use startZ");
z = incMem.startZ;
}
System.out.println("is starting Z from One = " + z.isOne());
for (iterZ = new FixPoint(false); iterZ.advance(z);) {
zIterCount++;
System.out.println("sys.justiceNum() = " + sys.justiceNum());
if (firstZItr && !incMem.PREV_SAFETY_REMOVED && incMem.PREV_JUSTICE_REMOVED
&& incMem.leastRemovedJusticeIdx > 0) {
System.out.println(
"previous justice was removed, leastRemovedJusticeIdx = " + incMem.leastRemovedJusticeIdx);
for (int k = 0; k < incMem.leastRemovedJusticeIdx; k++) {
mem.z_mem[k] = incMem.prevFirstZIterMem[k].id();
firstZIterMem[k] = incMem.prevFirstZIterMem[k].id();
}
if (z != null)
z.free();
z = incMem.prevFirstZIterMem[incMem.leastRemovedJusticeIdx - 1];
jStartIdx = incMem.leastRemovedJusticeIdx;
System.out.println("starting first z iteration from jStartIdx = " + jStartIdx);
}
for (int j = jStartIdx; j < sys.justiceNum(); j++) {
System.out.println("j = " + j);
cy = 0;
y = Env.FALSE();
if (incMem.PREV_SAFETY_REMOVED && !incMem.PREV_JUSTICE_REMOVED) {
System.out.println("use prevZMem[" + j + "] for current Y");
y = incMem.prevZMem[j].id();
if (y.isZero()) {
System.out.println("Y = FALSE");
}
}
BDD yieldToJ = sys.justiceAt(j).id().andWith(env.yieldStates(sys, z));
for (iterY = new FixPoint(false); iterY.advance(y);) {
yIterCount++;
BDD start = yieldToJ.id().orWith(env.yieldStates(sys, y));
y = Env.FALSE();
for (int i = 0; i < env.justiceNum(); i++) {
BDD negp = env.justiceAt(i).not();
if (x != null) {
x.free();
}
if (incMem.NEW_SAFETY_ADDED && j < incMem.prevXMem.length /* prevPartialXMem.length */) {
System.out.println("use prevXMem[" + j + "][" + i + "][" + cy + "] for current X");
int k = cy;
if (incMem.prevXMem[j][i].length <= cy) {
System.out.println("\tprevXMem[j][i].length = " + incMem.prevXMem[j][i].length + " <= "
+ cy + " = cy");
k = incMem.prevXMem[j][i].length - 1;
}
x = incMem.prevXMem[j][i][k].and(z.id());
// NOTE: log for checks
// System.out.println("\tx.isOne = " + x.isOne());
// System.out.println("\tz.isOne = " + z.isOne());
// System.out.println("\tprevXMem.isOne = " + prevXMem[j][i][k].isOne());
// System.out.println("\tx in z = " + z.and(x).equals(x));
// System.out.println("\tz in x = " + z.and(x).equals(z));
// System.out.println("\tz equals x = " + z.equals(x));
// if (prevPartialXMem[j][i] == null) {
// System.out.println("\tis null, can't use it");
// x = z.id();
// } else {
// x = prevPartialXMem[j][i].and(z.id());
// System.out.println("\tx.isOne = " + x.isOne());
// System.out.println("\tz.isOne = " + z.isOne());
// System.out.println("\tprevPartialXMem[j][i].isOne = " +
// prevPartialXMem[j][i].isOne());
// if (z.equals(prevPartialXMem[j][i]))
// {
// System.out.println("\tequals current z");
// }
// if (z.equals(x))
// {
// System.out.println("\tx equals current z - prevPartialXMem did not minimized
// the possible states");
// }
// }
} else {
x = z.id();
}
for (iterX = new FixPoint(false); iterX.advance(x);) {
xIterCount++;
BDD sysCtrl = env.yieldStates(sys, x);
BDD sysCtrlAndNotJustice = sysCtrl.and(negp);
sysCtrl.free();
x = sysCtrlAndNotJustice.or(start);
sysCtrlAndNotJustice.free();
}
// NOTE: log for checks
// if (NEW_SAFETY_ADDED && j < prevXMem.length ) {
// int k = cy;
// if (prevXMem[j][i].length <= cy) k = prevXMem[j][i].length - 1;
//
// System.out.println("\tx new fixed point: x.isOne = " + x.isOne());
// System.out.println("\tx new fixed point: x in prev x = " +
// x.and(prevXMem[j][i][k]).equals(x));
// System.out.println("\tx new fixed point: x in prev x.and(z) = "
// + x.and((prevXMem[j][i][k].and(z.id()))).equals(x));
// }
// System.out.println("x iters # " + xIterCount);
xIterCount = 0;
mem.x_mem[j][i][cy] = x.id();
BDD oy = y;
y = y.or(x);
oy.free();
}
start.free();
mem.y_mem[j][cy] = y.id();
cy++;
if (cy % 50 == 0) {
mem.x_mem = mem.extend_size(mem.x_mem, cy);
mem.y_mem = mem.extend_size(mem.y_mem, cy);
}
}
for (int i = 0; i < env.justiceNum(); i++) {
for (int k = cy; k < mem.x_mem[j][i].length; k++) {
mem.x_mem[j][i][k] = null;
}
}
for (int k = cy; k < mem.y_mem[j].length; k++) {
mem.y_mem[j][k] = null;
}
// System.out.println("y iters # " + yIterCount);
yIterCount = 0;
z = y.id();
if (DETECT_FIX_POINT_EARLY && !firstZItr) {
// check if we will reach a fix-point after the end of this iteration
if (mem.z_mem[j].equals(z)) {
z.free();
z = mem.z_mem[sys.justiceNum() - 1].id();
break;
}
}
mem.z_mem[j] = z.id();
if (firstZItr) {
firstZIterMem[j] = z.id();
}
yieldToJ.free();
}
jStartIdx = 0;
if (firstZItr) {
firstZItr = false;
}
}
System.out.println("z iters # " + zIterCount);
mem.x_mem = mem.extend_size(mem.x_mem, 0);
mem.y_mem = mem.extend_size(mem.y_mem, 0);
mem.setWin(z);
mem.setComplete(true);
return sysWinAllInitial(z);
}
@Override
public void free() {
Env.free(firstZIterMem);
mem.free();
}
public boolean sysWinAllInitial() {
return this.sysWinAllInitial(mem.getWin());
}
public BDD sysWinningStates() {
return mem.getWin();
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gamemodel.util;
import java.util.ArrayList;
import java.util.List;
import tau.smlab.syntech.gamemodel.BehaviorInfo;
import tau.smlab.syntech.gamemodel.GameModel;
/**
* This is an abstract base class for building games based on lists of traces
*
* @author shalom
*
*/
public abstract class TraceInfoBuilder {
protected GameModel gm = null;
protected List<BehaviorInfo> env = null;
protected List<BehaviorInfo> sys = null;
protected List<BehaviorInfo> aux = null;
List<Integer> traceList = null;
public TraceInfoBuilder(GameModel gm) {
this.gm = gm;
env = new ArrayList<BehaviorInfo>(gm.getEnvBehaviorInfo());
sys = new ArrayList<BehaviorInfo>(gm.getSysBehaviorInfo());
aux = new ArrayList<BehaviorInfo>(gm.getAuxBehaviorInfo());
createTraceList();
}
/**
* return the list of all traces which are relevant to the module
*/
public List<Integer> getTraceList() {
return traceList;
}
/**
* restore the modle according to original traces
*
* @return restored model
*/
public GameModel restore() {
GameBuilderUtil.buildEnv(gm, env);
List<BehaviorInfo> gameAux = gm.getAuxBehaviorInfo();
gameAux.clear();
gameAux.addAll(aux);
GameBuilderUtil.buildSys(gm, sys);
return gm;
}
/**
* create a list of all traces which are relevant to the module
*/
protected abstract void createTraceList();
/**
* Build and return a model based on the one in the class which according to the subset of the trace list
* @param taken
* @return
*/
public abstract GameModel build(List<Integer> taken);
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.gr1;
public enum GR1StrategyType {
ZYX, ZXY, YZX, YXZ, XZY, XYZ;
/**
* 3 - Z Y X.<br>
* 7 - Z X Y.<br>
* 11 - Y Z X.<br>
* 15 - Y X Z.<br>
* 19 - X Z Y.<br>
* 23 - X Y Z.<br>
*
* @param st_kind
* @return
*/
public int old_value() {
switch (this) {
case ZYX:
return 3;
case ZXY:
return 7;
case YZX:
return 11;
case YXZ:
return 15;
case XZY:
return 19;
case XYZ:
return 23;
default:
break;
}
return -1;
}
public int hashValue() {
return old_value();
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.logs;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDVarSet;
import tau.smlab.syntech.jtlv.CoreUtil;
import tau.smlab.syntech.jtlv.Env;
public class BDDLogWriter {
private BufferedWriter writer;
private BDDVarSet vars;
/**
* by default logging all unprimed vars
*
* @param fileName
* @throws IOException
*/
public BDDLogWriter(String fileName) throws IOException {
this.writer = initWriter(fileName);
this.vars = Env.globalUnprimeVars();
}
public BDDLogWriter(String fileName, BDDVarSet vars) throws IOException {
this.writer = initWriter(fileName);
this.vars = vars;
}
/**
* create new buffered writer
*
* @param fileName
* @return
* @throws IOException
*/
private BufferedWriter initWriter(String fileName) throws IOException {
return new BufferedWriter(new FileWriter(fileName));
}
/**
* write the BDD to the log
*
* if the BDD has more than one assignment, writes one of them, if the BDD has no assignments writes FALSE
*
* @param entry
* @throws IOException
*/
public void write(BDD entry) throws IOException {
if (entry.isZero()) {
writer.write("FALSE");
} else if (entry.satCount() > 1 && !vars.isEmpty()) {
BDD one = CoreUtil.satOne(entry, vars);
writer.write(one.toStringWithDomains(Env.stringer));
one.free();
} else if (vars.isEmpty() && !entry.isZero()) {
writer.write("TRUE");
} else {
writer.write(entry.toStringWithDomains(Env.stringer));
}
writer.newLine();
writer.flush();
}
/**
* closes the file
*
* @throws IOException
*/
public void close() throws IOException {
writer.close();
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.enumerate;
import java.util.Vector;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.games.AbstractGamesException;
import tau.smlab.syntech.games.GamesStrategyException;
public class EnumStateImpl implements EnumStateI {
private EnumStrategyI holder;
private int id;
private boolean ini;
private AbstractRankInfo just;
private BDD state;
private Vector<EnumStateI> succ;
private int numInEdges;
private int numOutEdges;
private int distFromIni;
public EnumStateImpl(EnumStrategyI holder, int id, boolean ini, BDD state,
AbstractRankInfo just) {
this.holder = holder;
this.id = id;
this.ini = ini;
this.state = state;
this.just = just;
this.succ = new Vector<EnumStateI>(10);
this.numInEdges = 0;
this.numOutEdges = 0;
this.distFromIni = 0;
}
@Override
public void addSuccessor(StateI add) throws AbstractGamesException {
if (!(add instanceof EnumStateI))
throw new GamesStrategyException("Cannot add successor from"
+ " different type");
succ.add((EnumStateI) add);
}
@Override
public EnumStrategyI getHolder() {
return this.holder;
}
@Override
public int getStateId() {
return this.id;
}
@Override
public AbstractRankInfo get_rank_info() {
return this.just;
}
@Override
public Vector<EnumStateI> getSuccessors() {
return this.succ;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof EnumStateImpl))
return false;
EnumStateImpl other_raw = (EnumStateImpl) other;
return ((this.just == other_raw.just) && (this.ini == other_raw.ini) && (this.state
.equals(other_raw.state)));
}
@Override
public int hashCode() {
return this.just.hashCode() * this.state.hashCode() + (this.ini?1:0);
}
@Override
public boolean isInitial() {
return this.ini;
}
@Override
public BDD getData() {
return this.state;
}
@Override
public int getNumOutEdges() {
return this.numOutEdges;
}
@Override
public int getNumInEdges() {
return this.numInEdges;
}
@Override
public int getDistFromIni() {
return this.distFromIni;
}
@Override
public void incNumOutEdges() {
this.numOutEdges++;
}
@Override
public void incNumInEdges() {
this.numInEdges++;
}
@Override
public boolean updateDistFromIni(int neighborDist) {
if (isInitial()) {
return false;
}
if (this.distFromIni == 0) {
this.distFromIni = neighborDist + 1;
return true;
}
if (this.distFromIni > neighborDist + 1) {
this.distFromIni = neighborDist + 1;
return true;
}
return false;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinput.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Player implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5085525976634287802L;
private List<Variable> vars = new ArrayList<>();
private List<Constraint> constraints = new ArrayList<>();
private List<PatternConstraint> patterns = new ArrayList<>();
private List<TriggerConstraint> triggers = new ArrayList<>();
private List<ExistentialConstraint> existentialConstraints = new ArrayList<>();
public Player() {
this.vars = new ArrayList<>();
this.constraints = new ArrayList<>();
this.patterns = new ArrayList<>();
this.triggers = new ArrayList<>();
this.existentialConstraints = new ArrayList<>();
}
public String toString()
{
return "Player:[vars: " + vars + " constraints: " + constraints + "patterns: " + patterns+"]";
}
public List<Variable> getVars() {
return vars;
}
public void setVars(List<Variable> vars) {
this.vars = vars;
}
public List<Constraint> getConstraints() {
return constraints;
}
public void setConstraints(List<Constraint> constraints) {
this.constraints = constraints;
}
public List<PatternConstraint> getPatterns() {
return patterns;
}
public void setPatterns(List<PatternConstraint> patterns) {
this.patterns = patterns;
}
public void setExistentialConstraints(List<ExistentialConstraint> existentialConstraints) {
this.existentialConstraints = existentialConstraints;
}
public List<ExistentialConstraint> getExistentialConstraints() {
return existentialConstraints;
}
public void addVar(Variable variable)
{
this.vars.add(variable);
}
public void addConstraint(Constraint constraint)
{
this.constraints.add(constraint);
}
public void addPatternConstraint(PatternConstraint patternConstraint)
{
this.patterns.add(patternConstraint);
}
public void addExistentialConstraint(ExistentialConstraint existentialConstraint)
{
this.existentialConstraints.add(existentialConstraint);
}
public void addTrigger(TriggerConstraint trigger) {
this.triggers.add(trigger);
}
public List<TriggerConstraint> getTriggers() {
return triggers;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinput.spec;
/**
* <p>
* Specification expression.
* </p>
*
* @author <NAME>.
*
*/
public class SpecExp implements Spec {
/**
*
*/
private static final long serialVersionUID = -6833233099417793276L;
private Operator theOp;
private Spec[] elements;
/**
* <p>
* Constructor for an unary specification.
* </p>
*
* @param op
* The operator.
* @param e1
* The sub specification.
*/
public SpecExp(Operator op, Spec e1) {
this.theOp = op;
this.elements = new Spec[] { e1 };
}
public SpecExp(Operator op, SpecWrapper e1) {
this(op, e1.getSpec());
}
/**
* <p>
* Constructor for a binary specification.
* </p>
*
* @param op
* The operator.
* @param e1
* The first sub specification.
* @param e2
* The second sub specification.
*/
public SpecExp(Operator op, Spec e1, Spec e2) {
this.theOp = op;
this.elements = new Spec[] { e1, e2 };
}
public SpecExp(Operator op, SpecWrapper e1, SpecWrapper e2) {
this(op, e1.getSpec(), e2.getSpec());
}
public String toString() {
if (this.theOp.isUnary()) {
return theOp.toString() + "(" + elements[0].toString() + ")";
} else {
return elements[0].toString() + " " + theOp.toString() + " " + elements[1].toString();
}
}
/**
* <p>
* The operator representing this node.
* </p>
*
* @return An operator representing this node.
*/
public Operator getOperator() {
return theOp;
};
/**
* <p>
* Get the children specification of this node.
* <p>
*
* @return The children specification.
*/
public Spec[] getChildren() {
return this.elements;
}
/*
* (non-Javadoc)
*
* @see edu.wis.jtlv.env.spec.Spec#isPastLTLSpec()
*/
public boolean isPastLTLSpec() {
// checking that all children are prop.
for (Spec s : this.getChildren()) {
if (s.isPastLTLSpec()) {
return true;
}
}
// checking that I'm prop or pastLTL
return this.getOperator().isPastLTLOp();
}
/*
* (non-Javadoc)
*
* @see edu.wis.jtlv.env.spec.Spec#isPropSpec()
*/
public boolean isPropSpec() {
// checking that all children are prop.
for (Spec s : this.getChildren())
if (!s.isPropSpec()) {
System.out.println("I am operator " + getOperator().name() + " and child " + s.toString() + " returned false");
return false;
}
// checking that I'm prop
return this.getOperator().isProp();
}
/*
* (non-Javadoc)
*
* @see edu.wis.jtlv.env.spec.Spec#hasTemporalOperators()
*/
public boolean hasTemporalOperators() {
// if one of my elements is temporal.
for (Spec s : this.getChildren())
if (s.hasTemporalOperators())
return true;
// or I'm temporal.
return this.theOp.isTemporalOp();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object other) {
if (!(other instanceof SpecExp))
return false;
SpecExp otherExp = (SpecExp) other;
if (this.getOperator() != otherExp.getOperator())
return false;
Spec[] this_children = this.getChildren();
Spec[] other_children = otherExp.getChildren();
if (this_children.length != other_children.length)
return false;
for (int i = 0; i < this_children.length; i++)
if (!this_children[i].equals(other_children[i]))
return false;
return true;
}
public SpecExp clone() throws CloneNotSupportedException {
int elementsSize = this.elements.length;
if (elementsSize == 1) {
return new SpecExp(this.theOp, this.elements[0].clone());
} else {
return new SpecExp(this.theOp, this.elements[0].clone(), this.elements[1].clone());
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gamemodel.util;
import java.util.ArrayList;
import java.util.List;
import tau.smlab.syntech.gamemodel.BehaviorInfo;
import tau.smlab.syntech.gamemodel.GameModel;
/**
* This class finds and builds game models according to traces of system behaviors
* Auxiliary behaviors not attached to system or environment (like monitors, counters) count as system
*
* @author shalom
*
*/
public class SysTraceInfoBuilder extends TraceInfoBuilder {
public SysTraceInfoBuilder(GameModel gm) {
super(gm);
}
public GameModel build(List<Integer> taken) {
// make sure that we ask only for listed behaviors. All non listed are taken
assert(traceList.containsAll(taken));
List<BehaviorInfo> gameSys = new ArrayList<BehaviorInfo>();
for (BehaviorInfo bi : sys) {
if (!traceList.contains(bi.traceId) || taken.contains(bi.traceId)) {
gameSys.add(bi);
}
}
List<BehaviorInfo> gameAux = gm.getAuxBehaviorInfo();
gameAux.clear();
for (BehaviorInfo bi : aux) {
if (!traceList.contains(bi.traceId) || taken.contains(bi.traceId)) {
gameAux.add(bi);
}
}
GameBuilderUtil.buildSys(gm, gameSys);
return gm;
}
protected void createTraceList() {
TraceIdentifier iden = new TraceIdentifier(gm);
traceList = iden.getSysTraces();
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.logs.BDDLogWriter;
public class LoggingController extends AbstractController {
private BDDLogWriter log;
public LoggingController(Controller controller) {
super(controller);
}
@Override
public void load(String folder, String name, Map<String, String[]> sysVars, Map<String, String[]> envVars) {
controller.load(folder, name, sysVars, envVars);
// Creates folder ./logs if it doesn't exist. Prepares the log object to write a BDD log
File lp = new File("logs");
if (!lp.exists()) {
lp.mkdir();
}
String ts = "" + System.currentTimeMillis();
String logName = lp.getPath() + "/" + ts + ".gol";
try {
log = new BDDLogWriter(logName, Env.globalUnprimeVars());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public BDD next(BDD currentState, BDD inputs) {
BDD nextStates = controller.next(currentState, inputs);
//try to log the current state
try {
log.write(currentState);
} catch (IOException e) {
System.err.println("There was an error writing to log during controller execution: " + e.getMessage());
}
return nextStates;
}
@Override
public void init(BDD currentState) {
controller.init(currentState);
}
@Override
public void saveState() {
controller.saveState();
}
@Override
public void loadState() {
controller.loadState();
}
@Override
public BDD kSucc(BDD from, int k) {
return controller.kSucc(from, k);
}
@Override
public BDD kPred(BDD to, int k) {
return controller.kPred(to, k);
}
@Override
public BDD succ(BDD from) {
return controller.succ(from);
}
@Override
public BDD pred(BDD to) {
return controller.pred(to);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.sf.javabdd;
import java.util.List;
import net.sf.javabdd.BDDFactory.ReorderMethod;
public class CUDDPipeCallerMethodInfo {
public static final int MAX_METHOD_ARGS = 8; /*maximum number of arguments that all library functions have*/
public static class ReturnValue<T> {
protected T value;
public ReturnValue() {
this.value = null;
}
public ReturnValue(T value) {
this.value = value;
}
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return this.value;
}
}
public static class ReturnIntValue extends
ReturnValue <Integer> {
public ReturnIntValue(int val) {
this.value = val;
}
}
public static class ReturnLongValue extends
ReturnValue <Long> {
public ReturnLongValue(long val) {
this.value = val;
}
}
public static class ReturnBooleanValue extends
ReturnValue <Boolean> {
public ReturnBooleanValue(boolean val) {
this.value = val;
}
}
public static class ReturnDoubleValue extends
ReturnValue <Double> {
public ReturnDoubleValue(double val) {
this.value = val;
}
}
public static class ReturnReorderMethodValue extends
ReturnValue <ReorderMethod> {
public ReturnReorderMethodValue(ReorderMethod val) {
this.value = val;
}
}
public static class ReturnIntListValue extends
ReturnValue <List<Integer>> {
public ReturnIntListValue(List<Integer> val) {
this.value = val;
}
public int[] toPrimitiveIntArray() {
int size = this.value.size();
Integer[] arr = new Integer[size];
this.value.toArray(arr);
int[] converted = new int[size];
for(int i = 0; i < size; i++) {
converted[i] = arr[i];
}
return converted;
}
}
public static class ReturnLongListValue extends
ReturnValue <List<Long>> {
public ReturnLongListValue(List<Long> val) {
this.value = val;
}
}
public static class ReturnDoubleListValue extends
ReturnValue <List<Double>> {
public ReturnDoubleListValue(List<Double> val) {
this.value = val;
}
}
public static enum ReturnType {
BOOLEAN(0,4), INTEGER(1,4), LONG(2,8), DOUBLE(3,8), VOID(4,4), INT_LIST(5,4), LONG_LIST(6,8), DOUBLE_LIST(7,8), REORDER_METHOD(8,4);
private final int id;
private final int numBytes;
private ReturnType(int id, int numBytes) {
this.id = id;
this.numBytes = numBytes;
}
public int getId() {
return id;
}
public int getnumBytes() {
return numBytes;
}
public static ReturnType resolveReturnType(Class<?> type) {
if(type.equals(Boolean.class) || type.equals(boolean.class)) {
return BOOLEAN;
}
if(type.equals(Integer.class) || type.equals(int.class)) {
return INTEGER;
}
if(type.equals(Long.class) || type.equals(long.class)) {
return LONG;
}
if(type.equals(Double.class) || type.equals(double.class)) {
return DOUBLE;
}
if(type.equals(Integer[].class) || type.equals(int[].class)) {
return INT_LIST;
}
if(type.equals(Long[].class) || type.equals(long[].class)) {
return LONG_LIST;
}
if(type.equals(Double[].class) || type.equals(double[].class)) {
return DOUBLE_LIST;
}
if(type.equals(ReorderMethod.class)) {
return REORDER_METHOD;
}
return VOID;
}
}
public static enum MethodEntry {
INITIALIZE0("initialize0", 1, 2, ReturnType.LONG_LIST),
IS_INITIALIZED0("isInitialized0", 2, 0, ReturnType.BOOLEAN),
DONE0("done0", 3, 0, ReturnType.VOID),
VAR_NUM0("varNum0", 4, 0, ReturnType.INTEGER),
GET_SIZE0("getSize0", 5, 1, ReturnType.INTEGER),
SET_VAR_NUM0("setVarNum0", 6, 2, ReturnType.INTEGER),
ITH_VAR0("ithVar0", 7, 2, ReturnType.LONG),
LEVEL2_VAR0("level2Var0", 8, 1, ReturnType.INTEGER),
VAR2_LEVEL0("var2Level0", 9, 1, ReturnType.INTEGER),
SET_VAR_ORDER0("setVarOrder0", 10, 1, ReturnType.VOID),
GET_ALLOC_NUM0("getAllocNum0", 11, 0, ReturnType.INTEGER),
GET_NODE_NUM0("getNodeNum0", 12, 0, ReturnType.INTEGER),
GET_CACHE_SIZE0("getCacheSize0", 13, 0, ReturnType.INTEGER),
VAR0("var0", 14, 1, ReturnType.INTEGER),
HIGH0("high0", 15, 2, ReturnType.LONG),
LOW0("low0", 16, 2, ReturnType.LONG),
NOT0("not0", 17, 2, ReturnType.LONG),
ITE0("ite0", 18, 4, ReturnType.LONG),
RELPROD0("relprod0", 19, 3, ReturnType.LONG),
COMPOSE0("compose0", 20, 4, ReturnType.LONG),
EXIST0("exist0", 21, 3, ReturnType.LONG),
FOR_ALL0("forAll0", 22, 3, ReturnType.LONG),
SIMPLIFY0("simplify0", 23, 3, ReturnType.LONG),
RESTRICT0("restrict0", 24, 2, ReturnType.LONG),
RESTRICT_WITH0("restrictWith0", 25, 3, ReturnType.LONG),
SUPPORT0("support0", 26, 2, ReturnType.LONG),
APPLY0("apply0", 27, 6, ReturnType.LONG),
SAT_ONE0("satOne0", 28, 3, ReturnType.LONG), //changed by Or: 3rd arg: 2 -> 3
NODE_COUNT0("nodeCount0", 29, 1, ReturnType.INTEGER),
PATH_COUNT0("pathCount0", 30, 1, ReturnType.DOUBLE),
SAT_COUNT0("satCount0", 31, 1, ReturnType.DOUBLE),
ADD_REF("addRef", 32, 1, ReturnType.VOID),
DEL_REF("delRef", 33, 2, ReturnType.VOID),
VECCOMPOSE0("veccompose0", 34, 3, ReturnType.LONG),
REPLACE0("replace0", 35, 3, ReturnType.LONG),
ALLOC("alloc", 36, 1, ReturnType.LONG),
SET0("set0", 37, 4, ReturnType.VOID),
SET2("set2", 38, 3, ReturnType.VOID),
RESET0("reset0", 39, 2, ReturnType.VOID),
FREE0("free0", 40, 2, ReturnType.VOID),
IS_ZERO_ONE_ADD0("isZeroOneADD0", 41, 1, ReturnType.BOOLEAN),
ADD_CONST0("addConst0", 42, 1, ReturnType.LONG),
IS_ADD_CONST0("isAddConst0", 43, 1, ReturnType.BOOLEAN),
ADD_FIND_MAX0("addFindMax0", 44, 1, ReturnType.LONG),
ADD_FIND_MIN0("addFindMin0", 45, 1, ReturnType.LONG),
RETRIEVE_CONST_VALUE0("retrieveConstValue0", 46, 1, ReturnType.DOUBLE),
ADD_ADDITIVE_NEG0("addAdditiveNeg0", 47, 1, ReturnType.LONG),
ADD_APPLY_LOG0("addApplyLog0", 48, 1, ReturnType.LONG),
REORDER0("reorder0", 49, 1, ReturnType.VOID),
AUTO_REORDER0("autoReorder0", 50, 3, ReturnType.VOID),
GETREORDERMETHOD0("getreordermethod0", 51, 0, ReturnType.INTEGER),
AUTO_REORDER1("autoReorder1", 52, 0, ReturnType.VOID),
REORDER_VERBOSE0("reorderVerbose0", 53, 1, ReturnType.INTEGER),
ADD_VAR_BLOCK0("addVarBlock0", 54, 3, ReturnType.VOID),
CLEAR_VAR_BLOCKS0("clearVarBlocks0", 55, 0, ReturnType.VOID),
PRINT_STAT0("printStat0", 56, 0, ReturnType.VOID),
TO_ADD0("toADD0", 57, 1, ReturnType.LONG),
TO_BDD0("toBDD0", 58, 1, ReturnType.LONG),
TO_BDD_THRESHOLD("toBDDThreshold", 59, 2, ReturnType.LONG),
TO_BDD_STRICT_THRESHOLD("toBDDStrictThreshold", 60, 2, ReturnType.LONG),
TO_BDD_INTERVAL("toBDDInterval", 61, 3, ReturnType.LONG),
TO_BDD_ITH_BIT("toBDDIthBit", 62, 2, ReturnType.LONG),
VAR_SUPPORT_INDEX0("varSupportIndex0", 63, 1, ReturnType.INT_LIST),
PRINT_SET0("printSet0", 64, 2, ReturnType.VOID),
ARITHMETIC_ZERO0("arithmeticZero0", 65, 0, ReturnType.LONG),
LOGIC_ZERO0("logicZero0", 66, 0, ReturnType.LONG),
REPLACE_WITH0("replaceWith0", 67, 3, ReturnType.LONG),
ADD_ABSTRACT_MIN0("addAbstractMin0", 68, 2, ReturnType.LONG),
ADD_ABSTRACT_MAX0("addAbstractMax0", 69, 2, ReturnType.LONG),
ARITHMETIC_MINUS_INFINITY0("arithmeticMinusInfinity0", 70, 0, ReturnType.LONG),
ARITHMETIC_PLUS_INFINITY0("arithmeticPlusInfinity0", 71, 0, ReturnType.LONG),
DETERMINIZE_CONTROLLER0("determinizeController0", 72, 2, ReturnType.LONG),
REORDER_ENABLED0("reorderEnabled0", 73, 0, ReturnType.BOOLEAN), //Or added this method instead of negCycleCheck0!!!
ARITHMETIC_LOGIC_ONE0("arithmeticLogicOne0", 74, 0, ReturnType.LONG),
ADD_MINIMIZE_VAL0("addMinimizeVal0", 75, 2, ReturnType.LONG),
REORDER_TIMES0("reorderTimes0", 76, 0, ReturnType.INTEGER),
PRINT_VAR_TREE0("printVarTree0", 77, 0, ReturnType.VOID),
ADD_ENG_SUBTRACT0("addEngSubtract0", 78, 3, ReturnType.LONG),
CONVERT_TO_ZERO_ONE_ADD_BY_THRES0("convertToZeroOneADDByThres0", 79, 3, ReturnType.LONG),
PRINT_DOT0("printDot0", 80, 1, ReturnType.VOID),
ARITHMETIC_EXIST0("arithmeticExist0", 81, 2, ReturnType.LONG);
private final String name; /*method name*/
private final int methodIndex, argNum; /*method index, number of arguments (BOTH must be consistent with the native code!)*/
private final ReturnType retType; /*return type (must be consistent with the native code!)*/
private MethodEntry(String name, int methodIndex, int argNum, ReturnType retType) {
this.name = name;
this.methodIndex = methodIndex;
this.argNum = argNum;
this.retType = retType;
}
public String getName() {
return this.name;
}
public int getIndex() {
return this.methodIndex;
}
public int getReturnTypeId() {
return this.retType.getId();
}
public ReturnType getReturnType() {
return this.retType;
}
public int getArgNumber() {
return this.argNum;
}
public static int getMaxNumberOfArgs() {
int result = 0;
for(MethodEntry method: MethodEntry.values()) {
if(method.argNum > result) {
result = method.argNum;
}
}
return result;
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.spectragameinput.translator;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import tau.smlab.syntech.spectra.LTLAsm;
import tau.smlab.syntech.spectra.LTLGar;
/**
* Tracer maintains a connection between EObjects (e.g., elements of a Spectra specification) and traceIds
* (integers).<br>
* Clients can look up this connection in both ways.
*
*/
public class Tracer {
public static int ID = 0;
private Map<EObject, Integer> tracingMap = new HashMap<>();
private static Map<Integer, EObject> trace = new HashMap<>();
public Tracer() {
tracingMap = new HashMap<>();
trace = new HashMap<>();
}
/**
* creates a new entry for the EObject with a fresh traceID
*
* does not check whether the object already exists!
*
* @param eobject
* @return the ID of the added object
*/
public int addTrace(EObject eobject) {
trace.put(ID, eobject);
tracingMap.put(eobject, ID);
ID++;
return ID-1;
}
/**
* looks up the traceId of an EObject
*
* @param eobject
* @return ID of the traced eobject if exists. -1 otherwise.
*/
public int getTrace(EObject eobject) {
if (!tracingMap.containsKey(eobject)) {
return -1;
}
return tracingMap.get(eobject);
}
/**
* returns the EObject of this traceId (e.g., returns an element of the Spectra specification)
*
* @param traceId
* @return
*/
public static EObject getTarget(int traceId) {
return trace.get(traceId);
}
/**
* translates the element with the given traceId to a string (e.g., prints a guarantee from the specification)
*
* @param traceId
* @return
*/
public static String getNiceStringForId(int traceId) {
if (traceId == -1) {
return "TRUE";
}
EObject obj = getTarget(traceId);
if (obj instanceof LTLGar) {
LTLGar gar = (LTLGar) obj;
if (gar.getName() != null) {
return "guarantee " + gar.getName();
}
} else if (obj instanceof LTLAsm) {
LTLAsm asm = (LTLAsm) obj;
if (asm.getName() != null) {
return "assumption " + asm.getName();
}
}
return NodeModelUtils.getTokenText(NodeModelUtils.findActualNodeFor(obj));
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.jits;
import java.util.List;
import java.util.Map;
import net.sf.javabdd.BDD;
/**
*
* @author Ilia
*
*/
public class BookkeepingController extends AbstractJitController {
public BookkeepingController(JitController jitController) {
super(jitController);
}
private boolean[] bookkeepingArray;
private boolean master;
@Override
public void load(String folder, String name, Map<String, String[]> sysVars, Map<String, String[]> envVars) {
jitController.load(folder, name, sysVars, envVars);
bookkeepingArray = new boolean[jitController.getJusticeGar().size()];
}
@Override
public BDD next(BDD currentState, BDD inputs) {
int jx = jitController.getJitState().getJx();
List<BDD> justiceGar = jitController.getJusticeGar();
int n = justiceGar.size();
// Update bookkeeping array
for (int j = jx; j < n; j++) {
if (bookkeepingArray[j] == master) {
if (!justiceGar.get(j).and(currentState).isZero()) {
bookkeepingArray[j] = !master;
}
}
}
for (int j = 0; j < jx; j++) {
if (bookkeepingArray[j] == !master) {
if (!justiceGar.get(j).and(currentState).isZero()) {
bookkeepingArray[j] = master;
}
}
}
return jitController.next(currentState, inputs);
}
@Override
public void init(BDD currentState) {
jitController.init(currentState);
jitController.getJitState().setGoalFinder(new NextJusticeGoalFinder() {
@Override
public int findNextJusticeGoal(int jx) {
for (int j = jx + 1; j < jitController.getJusticeGar().size(); j++) {
if (bookkeepingArray[j] == master) {
return j;
}
}
master = !master;
for (int j = 0; j < jx; j++) {
if (bookkeepingArray[j] == master) {
return j;
}
}
return jx;
}
});
}
@Override
public void saveState() {
this.controller.saveState();
}
@Override
public void loadState() {
this.controller.loadState();
}
@Override
public BDD succ(BDD from) {
return jitController.succ(from);
}
@Override
public BDD pred(BDD to) {
return jitController.pred(to);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gamemodel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDVarSet;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.ModuleVariableException;
import tau.smlab.syntech.jtlv.VarKind;
import tau.smlab.syntech.jtlv.env.module.ModuleBDDField;
/**
* module representing a player by
* <li>variables as ModuleBDDField including their domains</li>
* <li>BDD initial</li>
* <li>BDD trans</li>
* <li>List<BDD> justice</li>
*
* The BDDs initial and trans are restricted according to the domains of the variables (while adding variables). The
* composed domain restrictions are also kept in BDD doms.
*/
public class PlayerModule {
public static boolean TEST_MODE = false;
public enum TransFuncType {
SINGLE_FUNC, DECOMPOSED_FUNC, PARTIAL_DECOMPOSED_FUNC
}
private class TransQuantPair {
public TransQuantPair(BDD partTrans, BDDVarSet quantSet) {
this.partTrans = partTrans;
this.quantSet = quantSet;
}
public BDD partTrans;
public BDDVarSet quantSet;
}
/**
*
* A nested class that represents an existential requirement of this player module.
*
*/
public class ExistentialRequirement {
List<BDD> existFinallyAssrts;
SFAModuleConstraint regExpSfaConstraint;
public ExistentialRequirement(List<BDD> existFinallyAssrts) {
this.existFinallyAssrts = existFinallyAssrts;
}
public ExistentialRequirement(SFAModuleConstraint regExpSfaConstraint) {
this.regExpSfaConstraint = regExpSfaConstraint;
}
public boolean hasRegExp() {
return this.regExpSfaConstraint != null;
}
public List<BDD> getExistFinallyAssrts() {
return existFinallyAssrts;
}
public SFAModuleConstraint getRegExpSfaConstraint() {
return regExpSfaConstraint;
}
public int rank() {
if(this.existFinallyAssrts != null) {
return this.existFinallyAssrts.size();
}
return 0;
}
}
private String name;
private BDD initial = Env.TRUE();
private BDD doms = Env.TRUE();
private boolean simConjunctAbs;
private TransFuncType transFunc;
private BDD trans = Env.TRUE();
private List<TransQuantPair> transQuantList = new ArrayList<>();
private List<BDD> transList = new ArrayList<>();
private List<BDD> justice = new ArrayList<>();
private Map<Integer, Integer> justiceIDs = new HashMap<>();
private List<ExistentialRequirement> existential = new ArrayList<>();
private int existRegExpReqNum = 0;
private Map<Integer, Integer> existentialIDs = new HashMap<>();
/**
* was called all_couples
*/
private List<ModuleBDDField> allFields = new ArrayList<ModuleBDDField>();
private List<ModuleBDDField> auxFields = new ArrayList<ModuleBDDField>();
private List<ModuleBDDField> nonAuxFields = new ArrayList<ModuleBDDField>();
private BDDVarSet cachedPrimeVars;
private int cachedVarsLen;
private BDDVarSet cachedUnprimeVars;
/**
* returns set of all primed variables of the module
*
* (do not consume)
*
* @return
*/
public BDDVarSet modulePrimeVars() {
if (cachedPrimeVars == null || this.getAllFields().size() != cachedVarsLen) {
computeVarSets();
}
return cachedPrimeVars;
}
/**
* computes the cachedPrimeVars and cachedUnprimeVars
*/
private void computeVarSets() {
cachedPrimeVars = Env.getEmptySet();
cachedUnprimeVars = Env.getEmptySet();
cachedVarsLen = this.getAllFields().size();
for (ModuleBDDField c : this.getAllFields()) {
if (c.isPrime()) {
cachedPrimeVars = cachedPrimeVars.union(c.support());
cachedUnprimeVars = cachedUnprimeVars.union(c.unprime().support());
} else {
cachedPrimeVars = cachedPrimeVars.union(c.prime().support());
cachedUnprimeVars = cachedUnprimeVars.union(c.support());
}
}
}
public BDDVarSet moduleUnprimeVars() {
if (cachedUnprimeVars == null || this.getAllFields().size() != cachedVarsLen) {
computeVarSets();
}
return cachedUnprimeVars;
}
/**
* all fields including auxiliary fields (auxFields + nonAuxFields)
*
* @see getAuxFields()
* @see getNonAuxFields()
* @return
*/
public List<ModuleBDDField> getAllFields() {
return allFields;
}
/**
* remove the given field from the module's field lists (all/aux/nonAux)
*
* @param f
*/
public void removeField(ModuleBDDField f) {
allFields.remove(f);
auxFields.remove(f);
nonAuxFields.remove(f);
}
public void setSCA(boolean sca) {
simConjunctAbs = sca;
}
/**
* returns original initial states
*
* @return
*/
public BDD initial() {
return initial;
}
/**
* returns original transition relation
*
* @return
*/
public BDD trans() {
return trans;
}
public int existReqNum() {
return existential.size();
}
/**
* Returns the number of existential requirements that have regular expressions.
*
* @return
*/
public int existRegExpReqNum() {
return existRegExpReqNum;
}
/**
* Checks whether this module has any existential requirements.
*
* @return
*/
public boolean hasExistReqs() {
return !this.existential.isEmpty();
}
/**
* Returns the existential requirement at index <code>k</code>.
*
* @param k
* @return
*/
public ExistentialRequirement existReqAt(int k) {
try {
return existential.get(k);
} catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException("No existential requirement at index " + k);
}
}
/**
*
* Checks whether the existential requirement at index <code>k</code> contains a regular expression.
*
* @param k
* @return
*/
public boolean existReqHasRegExp(int k) {
try {
return existential.get(k).hasRegExp();
} catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException("No existential requirement at index " + k);
}
}
/**
* Returns the rank of the {@code k}-th existential requirement.
* The rank is nesting depth of finally (F) temporal operators.
* If the {@code k}-th existential requirement consists of a regular expression, its rank is 0.
*
* @param k
* @return
*/
public int existReqRank(int k) {
try {
return existential.get(k).rank();
} catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException("No existential requirement at index " + k);
}
}
/**
* Adds the specified existential requirement.
*
* @param exReq the existential requirement
*/
public void addExistReq(ExistentialRequirement exReq) {
this.existential.add(exReq);
if(exReq.hasRegExp()) {
existRegExpReqNum++;
}
}
/**
* Adds a new existential requirement with the assertions in {@code existFinallyAssrts}.
*
* @param existFinallyAssrts the assertions
*/
public void addExistReq(List<BDD> existFinallyAssrts) {
this.addExistReq(new ExistentialRequirement(existFinallyAssrts));
}
/**
* Adds a new existential requirement that contains the specified regular expression
* given by the BDD encoding of its corresponding SFA.
*
* @param regExpSfaConstraint the BDD encoding of the SFA that corresponds to the regular expression
*/
public void addExistReq(SFAModuleConstraint regExpSfaConstraint) {
this.addExistReq(new ExistentialRequirement(regExpSfaConstraint));
}
/**
* Adds a new existential requirement that contains the specified regular expression
* given by the BDD encoding of its corresponding SFA.
*
* @param regExpSfaConstraint the BDD encoding of the SFA that corresponds to the regular expression
* @param traceId
*/
public void addExistReq(SFAModuleConstraint regExpSfaConstraint, int traceId) {
this.addExistReq(new ExistentialRequirement(regExpSfaConstraint), traceId);
}
/**
* Adds a new existential requirement with the assertions in {@code existFinallyAssrts}.
*
* @param existFinallyAssrts the assertions
* @param traceId
*/
public void addExistReq(List<BDD> existFinallyAssrts, int traceId) {
this.addExistReq(new ExistentialRequirement(existFinallyAssrts), traceId);
}
/**
* Adds the specified existential requirement.
*
* @param exReq the existential requirement
* @param traceId
*/
public void addExistReq(ExistentialRequirement exReq, int traceId) {
this.addExistReq(exReq);
this.existentialIDs.put(traceId, this.existential.size() - 1);
}
public Map<Integer, Integer> getTraceIdToExistReqIndexMap() {
return this.existentialIDs;
}
public int justiceNum() {
return justice.size();
}
/**
* Returns the original justice at index <code>i</code>
*
* @param i
* @return
*/
public BDD justiceAt(int i) {
try {
return justice.get(i);
} catch (Exception e) {
throw new ArrayIndexOutOfBoundsException("No justice at index " + i);
}
}
/**
* Adds the justice (does not free it!)
*
* @param j
*/
public void addJustice(BDD j) {
this.justice.add(j);
}
public void addJustice(BDD j, int id) {
this.justice.add(j);
this.justiceIDs.put(id, this.justice.size() - 1);
}
public Map<Integer, Integer> getJusticeIndexToIDMap() {
return this.justiceIDs;
}
public BDD[] getJustices() {
return this.justice.toArray(new BDD[this.justice.size()]);
}
/**
* conjunct transitions with <code>moreTrans</code> (consumed)
*
* @param moreTrans
*/
public void conjunctTrans(BDD moreTrans) {
trans.andWith(moreTrans);
}
/**
* conjunct transitions with <code>moreIni</code> (consumed)
*
* @param moreIni
*/
public void conjunctInitial(BDD moreIni) {
initial.andWith(moreIni);
}
/**
* Sets the type of the transition function that will be used in yield states.
*
* @param type
* the type of the transition function
* */
public void setTransFuncType(TransFuncType type) {
transFunc = type;
}
/**
* Gets the type of the transition function that will be used in yield states.
* */
public TransFuncType getTransFuncType() {
return transFunc;
}
/**
* Add a partial transition function to the transition functions list
*
* @param trans
* the partial transition function
* */
public void addToTransList(BDD trans) {
// System.out.println("addToTransList: " + trans.support());
BDDVarSet transSet = getIntersectSupportWithPrimed(trans);
boolean isAdded = false;
for (int i = 0; i < transList.size(); i++) {
BDDVarSet set = getIntersectSupportWithPrimed(transList.get(i));
if (transSet.equals(set)) {
transList.get(i).andWith(trans);
isAdded = true;
break;
}
}
if (!isAdded) {
transList.add(trans);
}
}
public void simpleAddToTransList(BDD trans) {
// System.out.println("simpleAddToTransList: " + trans.support());
transList.add(trans);
}
/**
* Create a single transition function from the partitioned transition function
* */
public void createTransFromPartTrans() {
if(trans != null && !trans.isFree()) {
trans.free();
}
trans = Env.TRUE();
for (TransQuantPair p : transQuantList) {
conjunctTrans(p.partTrans);
}
}
public List<TransQuantPair> getTransQuantList() {
return transQuantList;
}
public BDD[] getPartTransArray() {
if (transFunc == TransFuncType.SINGLE_FUNC) {
return new BDD[0];
}
BDD[] partTransArr = new BDD[transQuantList.size()];
for (int i = 0; i < transQuantList.size(); i++) {
partTransArr[i] = transQuantList.get(i).partTrans;
}
return partTransArr;
}
public BDDVarSet[] getQuantSetArray() {
if (transFunc == TransFuncType.SINGLE_FUNC) {
return new BDDVarSet[0];
}
BDDVarSet[] quantSetArr = new BDDVarSet[transQuantList.size()];
for (int i = 0; i < transQuantList.size(); i++) {
quantSetArr[i] = transQuantList.get(i).quantSet;
}
return quantSetArr;
}
private BDDVarSet getIntersectSupportWithPrimed(BDD bdd) {
BDDVarSet set1 = bdd.support();
BDDVarSet intr = getIntersectSupportWithPrimed(set1);
set1.free();
return intr;
}
private BDDVarSet getIntersectSupportWithPrimed(BDDVarSet set1) {
BDDVarSet intr = Env.getEmptySet();
BDDVarSet set2 = modulePrimeVars();
int[] arr1 = set1.toArray();
int[] arr2 = set2.toArray();
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
intr.unionWith(arr1[i]);
break;
}
}
}
return intr;
}
@SuppressWarnings("unused")
private BDDVarSet getMinus(BDDVarSet set1, BDDVarSet set2) {
BDDVarSet minus = Env.getEmptySet();
int[] arr1 = set1.toArray();
int[] arr2 = set2.toArray();
for (int i = 0; i < arr1.length; i++) {
boolean isEqual = false;
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
isEqual = true;
break;
}
}
if (!isEqual) {
minus.unionWith(arr1[i]);
}
}
return minus;
}
// map from primed support set to the quantification set
// private Map<BDDVarSet, BDDVarSet> partTransQuantMap = new HashMap<>();
private Map<Set<Integer>, BDDVarSet> partTransQuantMap = new HashMap<>();
// private List<BDDVarSet> orderTransList = new ArrayList<>();
private List<Set<Integer>> orderTransList = new ArrayList<>();
//private Map<BDD, Set<Integer>> primeSuppSet = new HashMap<>();
public void addToPartTransList(BDD trans) {
BDDVarSet pSupp = getIntersectSupportWithPrimed(trans);
// partTransQuantMap.put(toIntSet(pSupp), Env.getEmptySet());
Set<Integer> set = toIntSet(pSupp);
if (!partTransQuantMap.containsKey(set)) {
partTransQuantMap.put(set, Env.getEmptySet());
}
// partTransQuantMap.put(pSupp, Env.getEmptySet());
}
/*
* Calculate the the order of the quantifications according to:
* 1. Largest set that can be quantified out
* 2. Largest (primed) support set
*/
public void partCalcTransQuantList() {
// System.out.println("partTransQuantMap size = " + partTransQuantMap.size());
// int idx = 0;
// for (Set<Integer> supp : partTransQuantMap.keySet()) {
// System.out.println("partTransQuantMap support("+idx+") = " + supp);
// idx++;
// }
Set<Set<Integer>> keySets = new HashSet<Set<Integer>>();//partTransQuantMap.keySet());
for (Set<Integer> key : partTransQuantMap.keySet()) {
keySets.add(key.stream().collect(Collectors.toSet()));
}
while (!keySets.isEmpty()) {
Set<Integer> maxSet = new HashSet<>();
Set<Integer> keyMaxSet = new HashSet<>(); //Env.getEmptySet();
for (Set<Integer> key : keySets) {
Set<Integer> eset = key.stream().collect(Collectors.toSet());//toIntSet(key);
for (Set<Integer> otherKey : keySets) {
if (!key.equals(otherKey)) {
Set<Integer> otherSet = otherKey;//toIntSet(otherKey);
eset.removeAll(otherSet);
if (eset.isEmpty()) {
break;
}
}
}
if (maxSet.size() < eset.size()) {
maxSet = eset;
keyMaxSet = key.stream().collect(Collectors.toSet());//key;
}
}
if (!maxSet.isEmpty()) {
// System.out.println("found maximum E: " + maxSet + ", for key support set: " + keyMaxSet);
partTransQuantMap.put(keyMaxSet, toVarSet(maxSet));
orderTransList.add(keyMaxSet);
keySets.remove(keyMaxSet);
continue;
}
// System.out.println("no maximum E set - take the largest primed support set: ");
Set<Integer> maxKey = new HashSet<>();
for (Set<Integer> key : keySets) {
if (key.size() > maxKey.size()) {
maxKey = key;
}
}
System.out.println("max primed support set: " + maxKey);
if (!maxKey.isEmpty()) {
orderTransList.add(maxKey);
keySets.remove(maxKey);
} else {
// System.out.println("Can't decompose further, left trans: " + keySets.size());
for (Set<Integer> k : keySets) {
orderTransList.add(k);
}
break;
}
}
keySets.clear();
// System.out.println("orderTransList size = " + orderTransList.size());
// System.out.println("Order of quantification:");
// for (int i = 0; i < orderTransList.size(); i++) {
// System.out.println("support = " + orderTransList.get(i) + ", E_"+i+" = " + partTransQuantMap.get(orderTransList.get(i)));
// }
}
/*
* Create the list of partitioned transitions and the sets to quantify,
* according to the calculations done in partCalcTransQuantList()
*/
public void createPartialTransQuantList() {
// System.out.println("Curr transList size = " + transList.size());
// System.out.println("OrderTransList size = " + orderTransList.size());
// for (int i = 0; i < orderTransList.size(); i++) {
// System.out.println("orderTransList.get("+i+").support() = " + orderTransList.get(i)
// + ", E_"+i+" = " + partTransQuantMap.get(orderTransList.get(i)));
// }
//
// for (int i = 0; i < transList.size(); i++) {
// System.out.println("transList.get("+i+").support() = " + transList.get(i).support()
// + ", primed support = " +getIntersectSupportWithPrimed(transList.get(i).support()));
// }
Set<Integer> modulePrimeVars = toIntSet(modulePrimeVars());
Set<Integer> leftoverSet = new HashSet<>(modulePrimeVars);
Map<BDDVarSet, Integer> transSuppToIdx = new HashMap<>();
Map<Set<Integer>, BDDVarSet> transPrimedSuppToSupp = new HashMap<>();
for (int i = 0; i < transList.size(); i++) {
BDDVarSet supp = transList.get(i).support();
transSuppToIdx.put(supp, i);
transPrimedSuppToSupp.put(toIntSet(getIntersectSupportWithPrimed(supp)), supp);
}
for (Set<Integer> psupp : orderTransList) {
if (transList.isEmpty()) {
break;
}
//check if elem in transPrimedSuppToSupp contained in psupp
if (!transPrimedSuppToSupp.containsKey(psupp)) {
BDDVarSet quantSet = partTransQuantMap.get(psupp);
int last_idx = transQuantList.size() - 1;
if (!transQuantList.isEmpty()) { // && transQuantList.get(last_idx).quantSet.isEmpty()) {
transQuantList.get(last_idx).quantSet.unionWith(quantSet.id());
leftoverSet.removeAll(toIntSet(quantSet));
}
continue;
}
BDDVarSet quantSet = partTransQuantMap.get(psupp);
BDD partTrans = transList.get(transSuppToIdx.get(transPrimedSuppToSupp.get(psupp)));
if (!quantSet.isEmpty()) {
leftoverSet.removeAll(toIntSet(quantSet));
int last_idx = transQuantList.size() - 1;
if (!transQuantList.isEmpty() && transQuantList.get(last_idx).quantSet.isEmpty()) {
transQuantList.get(last_idx).partTrans.andWith(partTrans);
transQuantList.get(last_idx).quantSet = quantSet.id();
} else {
transQuantList.add(new TransQuantPair(partTrans, quantSet.id()));
}
} else {
// transQuantList.add(new TransQuantPair(partTrans.id(), quantSet.id()));
if (transQuantList.isEmpty()) {
transQuantList.add(new TransQuantPair(partTrans.id(), quantSet.id()));
} else {
transQuantList.get(transQuantList.size()-1).partTrans.andWith(partTrans);
}
}
}
int last_idx = transQuantList.size() - 1;
if (last_idx > 0 && transQuantList.get(last_idx).quantSet.isEmpty()) {
transQuantList.get(last_idx-1).partTrans.andWith(transQuantList.get(last_idx).partTrans);
transQuantList.remove(last_idx);
}
if (!leftoverSet.isEmpty()) {
System.out.println("leftoverSet = " + leftoverSet);
transQuantList.get(0).quantSet.unionWith(toVarSet(leftoverSet));
}
// NOTE: group quantify sets with 1 variable to groups of 2 or 3 variables
List<TransQuantPair> tmpList = new ArrayList<>();
int setSize = 3;
for (int j = 0; j < transQuantList.size(); j++) {
if (j + 1 < transQuantList.size() && (transQuantList.get(j).quantSet.size() + transQuantList.get(j+1).quantSet.size() <= setSize)) {
TransQuantPair p = new TransQuantPair(transQuantList.get(j).partTrans.andWith(transQuantList.get(j+1).partTrans),
transQuantList.get(j).quantSet.unionWith(transQuantList.get(j+1).quantSet));
if (j + 2 < transQuantList.size() && (transQuantList.get(j+2).quantSet.size() + p.quantSet.size() <= setSize)) {
p.partTrans.andWith(transQuantList.get(j+2).partTrans);
p.quantSet.unionWith(transQuantList.get(j+2).quantSet);
j++;
}
j++;
tmpList.add(p);
} else {
tmpList.add(transQuantList.get(j));
}
}
transQuantList.clear();
transQuantList = tmpList;
for (int j = 0; j < transQuantList.size(); j++) {
BDDVarSet supp = transQuantList.get(j).partTrans.support();
// System.out.println("transQuantList["+j+"].support = " + supp + ", E_"+j+" = " + transQuantList.get(j).quantSet);
supp.free();
}
}
/**
public void partCalcTransQuantList() {
System.out.println("partTransList size = " + partTransList.size());
// if (PlayerModule.TEST_MODE) {
// System.out.println("trans support: " + trans.support());
// BDD calcTrans = Env.TRUE();
// for (int i = 0; i < transList.size(); i++) {
// calcTrans.andWith(transList.get(i).id());
// }
//
// if (!calcTrans.equals(trans)){
// System.err.println("ERROR: The oroginal transition function doesn't equal the conjuction of the decomposed functions!" );
// }
//
// System.out.println("calcTrans.support: " + calcTrans.support());
// calcTrans.free();
// }
Map<BDD, Set<Integer>> primeSuppSet = new HashMap<>();
List<BDD> currList = partTransList;
Set<Integer> modulePrimeVars = toIntSet(modulePrimeVars());
// for (BDD b : currList) {
// Set<Integer> primedSup = toIntSuppSet(b);
// primedSup.retainAll(modulePrimeVars);
// primeSuppSet.put(b, primedSup);
// }
while (!currList.isEmpty()) {
Set<Integer> maxSet = new HashSet<>();
int maxIdx = -1;
for (int j = 0; j < currList.size(); j++) {
// Set<Integer> eset = new HashSet<Integer>(primeSuppSet.get(currList.get(j)));
// Set<Integer> eset_orig = new HashSet<Integer>(primeSuppSet.get(currList.get(j)));
Set<Integer> eset = new HashSet<Integer>(primeSuppSet.get(currList.get(j)));
for (int h = 0; h < currList.size(); h++) {
if (h != j) {
Set<Integer> otherSet = new HashSet<Integer>(primeSuppSet.get(currList.get(h)));
// if (eset_orig.equals(otherSet)) { //TODO: NEW!!!
// continue;
// }
eset.removeAll(otherSet);
if (eset.isEmpty()) {
break;
}
}
}
if (maxSet.size() < eset.size()) {
maxSet = eset;
maxIdx = j;
}
}
if (maxIdx == -1) {
System.out.println("no maximum - take the largest primed support set: ");
Set<Integer> maxSupp = new HashSet<>();
int maxSuppIdx = -1;
for (int q = 0; q < currList.size(); q++) {
Set<Integer> supp = primeSuppSet.get(currList.get(q));
System.out.println(" " + supp);
if (supp.size() > maxSupp.size()) {
maxSupp = supp;
maxSuppIdx = q;
}
}
System.out.println("max support: " + maxSupp + ", maxSuppIdx: " + maxSuppIdx);
if (maxSuppIdx > -1) {
partTransQuantList.add(new TransQuantPair(currList.get(maxSuppIdx), Env.getEmptySet()));
currList.remove(maxSuppIdx);
} else {
System.out.println("Can't decompose further, left trans: " + currList.size());
for (BDD b : currList) {
partTransQuantList.add(new TransQuantPair(b, Env.getEmptySet()));
}
break;
}
} else {
System.out.println("found maximum E: " + maxSet);
partTransQuantList.add(new TransQuantPair(currList.get(maxIdx), toVarSet(maxSet)));
currList.remove(maxIdx);
}
}
// for (BDD b : currList) {
// b.free();
// }
currList.clear();
for (int j = 0; j < partTransQuantList.size(); j++) {
BDDVarSet supp = partTransQuantList.get(j).partTrans.support();
System.out.println("partTransQuantList["+j+"].support = " + supp + ", E_"+j+" = " + partTransQuantList.get(j).quantSet);
supp.free();
}
}
*/
/*
* Create the list of partitioned transitions and the sets to quantify,
* according to the calculations done in partCalcTransQuantList()
*/
/**
public void createPartialTransQuantList() {
System.out.println("Curr transList size = " + transList.size());
System.out.println("left partTransList size = " + partTransList.size());
Set<Integer> modulePrimeVars = toIntSet(modulePrimeVars());
BDDVarSet leftoverSet = modulePrimeVars().id();
for (TransQuantPair tq : partTransQuantList) {
if (transList.isEmpty()) {
break;
}
BDDVarSet supp = tq.partTrans.support();
if (transList.remove(tq.partTrans)) {
if (!tq.quantSet.isEmpty()) {
leftoverSet = getMinus(leftoverSet, tq.quantSet);
if (!transQuantList.isEmpty() &&
(transQuantList.get(transQuantList.size()-1).quantSet.isEmpty()
// //TODO: NEW!!!
|| (transQuantList.get(transQuantList.size()-1).quantSet.equals(tq.quantSet) &&
transQuantList.get(transQuantList.size()-1).partTrans.support().equals(tq.partTrans.support()))
)) {
transQuantList.get(transQuantList.size()-1).partTrans.andWith(tq.partTrans.id());
transQuantList.get(transQuantList.size()-1).quantSet = tq.quantSet.id();
} else {
transQuantList.add(new TransQuantPair(tq.partTrans.id(), tq.quantSet.id()));
}
} else {
if (transQuantList.isEmpty()) {
transQuantList.add(new TransQuantPair(tq.partTrans.id(), tq.quantSet.id()));
} else {
transQuantList.get(transQuantList.size()-1).partTrans.andWith(tq.partTrans.id());
}
}
}
}
for (BDD b : transList) {
System.out.println("left in transList: " + b.support());
}
Set<Integer> e = new HashSet<>();
BDD leftTrans = Env.TRUE();
System.out.println("intersect the remaining trans: " + transList.size());
for (BDD trans : transList) {
BDDVarSet inter = getIntersectSupportWithPrimed(trans);
System.out.println(" " + inter);
inter.free();
leftTrans.andWith(trans);
}
e = toIntSuppSet(leftTrans);
e.retainAll(modulePrimeVars);
System.out.println("leftoverSet: " + leftoverSet);
leftoverSet = getMinus(leftoverSet, toVarSet(e));
System.out.println("resulting E: " + e);
// System.out.println("leftTrans: " + leftTrans.support());
// System.out.println("leftoverSet: " + leftoverSet);
if (!e.isEmpty() || transQuantList.isEmpty()) {
transQuantList.add(new TransQuantPair(leftTrans, toVarSet(e)));
} else {
transQuantList.get(transQuantList.size()-1).partTrans.andWith(leftTrans);
}
transList.clear();
if (!leftoverSet.isEmpty()) {
transQuantList.get(transQuantList.size()-1).quantSet.unionWith(leftoverSet);
}
// NOTE: group quantify sets with 1 variable to groups of 2 or 3 variables
List<TransQuantPair> tmpList = new ArrayList<>();
int setSize = 3;
for (int j = 0; j < transQuantList.size(); j++) {
if (j + 1 < transQuantList.size() && (transQuantList.get(j).quantSet.size() + transQuantList.get(j+1).quantSet.size() <= setSize)) {
TransQuantPair p = new TransQuantPair(transQuantList.get(j).partTrans.andWith(transQuantList.get(j+1).partTrans),
transQuantList.get(j).quantSet.unionWith(transQuantList.get(j+1).quantSet));
if (j + 2 < transQuantList.size() && (transQuantList.get(j+2).quantSet.size() + p.quantSet.size() <= setSize)) {
p.partTrans.andWith(transQuantList.get(j+2).partTrans);
p.quantSet.unionWith(transQuantList.get(j+2).quantSet);
j++;
}
j++;
tmpList.add(p);
} else {
tmpList.add(transQuantList.get(j));
}
}
// System.err.println("7. " + (System.nanoTime() - startTimeNano));
transQuantList.clear();
transQuantList = tmpList;
for (int j = 0; j < transQuantList.size(); j++) {
BDDVarSet supp = transQuantList.get(j).partTrans.support();
System.out.println("transQuantList["+j+"].support = " + supp + ", E_"+j+" = " + transQuantList.get(j).quantSet);
supp.free();
}
}
*/
public void calcTransQuantList() {
// long start = System.nanoTime();
// long startTimeNano = System.nanoTime();
// System.out.println("modulePrimeVars: " + modulePrimeVars());
// for (int i = 0; i < transList.size(); i++) {
// System.out.println("transList.get("+i+").support() = " + transList.get(i).support());
// }
if (transList.size() ==1 && transList.get(0).isOne()) {
// System.out.println("Trans is TRUE");
transQuantList.add(new TransQuantPair(transList.get(0), modulePrimeVars()));
return;
}
// System.err.println("1. " + (System.nanoTime() - startTimeNano));
// if (PlayerModule.TEST_MODE) {
// System.out.println("trans support: " + trans.support());
// BDD calcTrans = Env.TRUE();
// for (int i = 0; i < transList.size(); i++) {
// calcTrans.andWith(transList.get(i).id());
// }
//
// if (!calcTrans.equals(trans)){
// System.err.println("ERROR: The oroginal transition function doesn't equal the conjuction of the decomposed functions!" );
// }
//
// System.out.println("calcTrans.support: " + calcTrans.support());
// calcTrans.free();
// }
// System.err.println("2. " + (System.nanoTime() - startTimeNano));
List<BDD> currList = transList;
Set<Integer> modulePrimeVars = toIntSet(modulePrimeVars());
Set<Integer> leftoverSet = new HashSet<>(modulePrimeVars);
Map<BDD, Set<Integer>> primeSuppSet = new HashMap<>();
for (BDD b : currList) {
Set<Integer> primedSup = toIntSuppSet(b);
primedSup.retainAll(modulePrimeVars); // currently leftoverSet is the primed vars
primeSuppSet.put(b, primedSup);
}
// System.err.println("3. " + (System.nanoTime() - startTimeNano));
while (!currList.isEmpty()) {
Set<Integer> maxSet = new HashSet<>();
int maxIdx = -1;
for (int j = 0; j < currList.size(); j++) {
Set<Integer> eset = new HashSet<Integer>(primeSuppSet.get(currList.get(j)));
for (int h = 0; h < currList.size(); h++) {
if (h != j) {
Set<Integer> otherSet = new HashSet<Integer>(primeSuppSet.get(currList.get(h)));
eset.removeAll(otherSet);
if (eset.isEmpty()) {
break;
}
}
}
if (maxSet.size() < eset.size()) {
maxSet = eset;
maxIdx = j;
}
}
if (maxIdx > -1) {
leftoverSet.removeAll(maxSet);
// System.out.println("found maximum E: " + maxSet);
transQuantList.add(new TransQuantPair(currList.get(maxIdx), toVarSet(maxSet)));
currList.remove(maxIdx);
continue;
}
// System.out.println("no maximum - take the largest support set: ");
Set<Integer> maxSupp = new HashSet<>();
int maxSuppIdx = -1;
for (int q = 0; q < currList.size(); q++) {
Set<Integer> supp = primeSuppSet.get(currList.get(q));
// System.out.println(" " + supp);
if (supp.size() > maxSupp.size()) {
maxSupp = supp;
maxSuppIdx = q;
}
}
// System.out.println("max support: " + maxSupp + ", maxSuppIdx: " + maxSuppIdx);
if (maxSuppIdx > -1) {
transQuantList.add(new TransQuantPair(currList.get(maxSuppIdx), Env.getEmptySet()));
currList.remove(maxSuppIdx);
} else {
Set<Integer> e = new HashSet<>();
BDD leftTrans = Env.TRUE();
// System.out.println("no maximum - intersect the remaining trans ");
for (int q = 0; q < currList.size(); q++) {
// Set<Integer> inter = primeSuppSet.get(currList.get(q));
// System.out.println(" " + inter);
leftTrans.andWith(currList.get(q));
}
e = toIntSuppSet(leftTrans);
e.retainAll(modulePrimeVars);
// System.out.println("resulting E: " + e);
if (!e.isEmpty() || transQuantList.isEmpty()) {
transQuantList.add(new TransQuantPair(leftTrans, toVarSet(e)));
} else {
transQuantList.get(transQuantList.size()-1).partTrans.andWith(leftTrans);
}
leftoverSet.removeAll(e);
currList.clear();
}
}
// System.err.println("4. " + (System.nanoTime() - startTimeNano));
if (!leftoverSet.isEmpty()) {
transQuantList.get(0).quantSet.unionWith(toVarSet(leftoverSet));
}
// System.err.println("5. " + (System.nanoTime() - startTimeNano));
// NOTE: handle the support sets with empty quantify sets
List<TransQuantPair> tmpList = new ArrayList<TransQuantPair>(transQuantList);
transQuantList.clear();
Iterator<TransQuantPair> itr = tmpList.iterator();
while (itr.hasNext()) {
TransQuantPair p = itr.next();
if (!p.quantSet.isEmpty()) {
transQuantList.add(p);
} else {
boolean first = true;
do {
if (first) {
transQuantList.add(p);
first = false;
} else {
transQuantList.get(transQuantList.size()-1).partTrans.andWith(p.partTrans);
}
if (itr.hasNext()) {
p = itr.next();
} else {
break;
}
} while (p.quantSet.isEmpty());
transQuantList.get(transQuantList.size()-1).partTrans.andWith(p.partTrans);
transQuantList.get(transQuantList.size()-1).quantSet = p.quantSet;
}
}
// System.err.println("6. " + (System.nanoTime() - startTimeNano));
// NOTE: group quantify sets with 1 variable to groups of 2 or 3 variables
tmpList = new ArrayList<>();
int setSize = 3;
for (int j = 0; j < transQuantList.size(); j++) {
if (j + 1 < transQuantList.size() && (transQuantList.get(j).quantSet.size() + transQuantList.get(j+1).quantSet.size() <= setSize)) {
TransQuantPair p = new TransQuantPair(transQuantList.get(j).partTrans.andWith(transQuantList.get(j+1).partTrans),
transQuantList.get(j).quantSet.unionWith(transQuantList.get(j+1).quantSet));
if (j + 2 < transQuantList.size() && (transQuantList.get(j+2).quantSet.size() + p.quantSet.size() <= setSize)) {
p.partTrans.andWith(transQuantList.get(j+2).partTrans);
p.quantSet.unionWith(transQuantList.get(j+2).quantSet);
j++;
}
j++;
tmpList.add(p);
} else {
tmpList.add(transQuantList.get(j));
}
}
// System.err.println("7. " + (System.nanoTime() - startTimeNano));
transQuantList.clear();
transQuantList = tmpList;
// System.err.println("8. " + (System.nanoTime() - startTimeNano));
// BDDVarSet allSet = Env.getEmptySet();
for (int j = 0; j < transQuantList.size(); j++) {
BDDVarSet supp = transQuantList.get(j).partTrans.support();
// System.out.println("transQuantList["+j+"].support = " + supp + ", E_"+j+" = " + transQuantList.get(j).quantSet);
// System.out.println("nodes count = " + transQuantList.get(j).partTrans.nodeCount());
supp.free();
}
// long end = System.nanoTime() - start;
// System.out.println("overall time of calcTransQuantList time = " + end);
// System.err.println("9. " + (System.nanoTime() - startTimeNano));
// if (!allSet.equals(modulePrimeVars())) {
// System.err.println("All the quant sets not equal to prime sets!!! ");
// System.err.println(" allSet = " + allSet);
// System.err.println(" cachedPrimeVars = " + modulePrimeVars());
// }
// allSet.free();
}
/**
* create a BDDVarSet that contains the variables in e
* @param e
* @return
*/
private BDDVarSet toVarSet(Set<Integer> e) {
BDDVarSet res = Env.getEmptySet();
for (int i : e) {
res.unionWith(i);
}
return res;
}
/**
* create set that contains all integers of the BDDVarSet
* @param varSet
* @return
*/
private Set<Integer> toIntSet(BDDVarSet varSet) {
return Arrays.stream(varSet.toArray()).boxed().collect(Collectors.toSet());
}
private Set<Integer> toIntSuppSet(BDD b) {
BDDVarSet supp = b.support();
Set<Integer> res = toIntSet(supp);
supp.free();
return res;
}
@SuppressWarnings("unused")
private void calcTransQuantList2() {
computeVarSets();
Iterator<BDD> transItr = transList.iterator();
List<List<BDD>> tmpSets = new ArrayList<>();
while (transItr.hasNext())
{
BDD bdd = transItr.next();
BDDVarSet currVarSet = bdd.support().intersect(cachedUnprimeVars);
// System.out.println("currVarSet = " + currVarSet);
// TODO: add all the safeties to a list - conjunct just the ones with the same vars.
// Then perform all the calculations of the E sets in some function inside the Player module. it can be called at the first yield.
boolean isDisjoint = true;
for (int k = 0; k < tmpSets.size(); k++) {
for (int j = 0; j < tmpSets.get(k).size(); j++) {
//System.out.println("k = " + k + ", j = " + j);
//System.out.println("tmpSet.support() = " + tmpSets.get(k).get(j).support());
BDDVarSet tmpVarSet = tmpSets.get(k).get(j).support().intersect(cachedUnprimeVars);
BDDVarSet intersectSet = currVarSet.intersect(tmpVarSet);
//System.out.println("tmpVarSet = " + tmpVarSet);
//System.out.println("intersectSet = " + intersectSet);
// TODO: handle disjoint sets separately??
// if (intersectSet.isEmpty()) {
// System.out.println("empty intersection, continue ");
// continue;
// }
isDisjoint = false;
boolean contains = intersectSet.equals(tmpVarSet);
boolean contained = intersectSet.equals(currVarSet);
if (contains && contained) {
// System.out.println("equal support, add to this bdd");
tmpSets.get(k).get(j).andWith(bdd.id());
break;
} else if (j == (tmpSets.get(k).size() - 1)) {
// System.out.println("add to the end of the list ");
tmpSets.get(k).add(bdd.id());
break;
}
}
if (!isDisjoint) {
break;
}
}
if (isDisjoint && !bdd.support().isEmpty()) {
List<BDD> l = new ArrayList<>();
l.add(bdd.id());
tmpSets.add(l);
// System.out.println("found disjoint set, add list " + bdd.support());
}
if (bdd.support().isEmpty()) {
// System.out.println("bdd with empty support: " + bdd);
}
}
// for (int k = 0; k < tmpSets.size(); k++) {
// System.out.println("set " + k);
// for (int j = 0; j < tmpSets.get(k).size(); j++) {
// System.out.println(" " + tmpSets.get(k).get(j).support());
// }
// }
// System.out.println("trans support: " + trans.support());
List<List<TransQuantPair>> finalTrans = new ArrayList<>();
for (int k = 0; k < tmpSets.size(); k++) {
// System.out.println("set " + k);
List<TransQuantPair> partTransQuantList = new ArrayList<>();
List<BDD> currList = tmpSets.get(k);
while (!currList.isEmpty()) {
BDDVarSet maxSet = Env.getEmptySet();
int maxIdx = -1;
for (int j = 0; j < currList.size(); j++) {
BDDVarSet set = currList.get(j).support().intersect(cachedUnprimeVars);
BDDVarSet eset = set;
for (int h = 0; h < currList.size(); h++) {
if (h != j) {
eset = eset.minus(currList.get(h).support().intersect(cachedUnprimeVars));
}
}
if (maxSet.size() < eset.size()) {
maxSet = eset;
maxIdx = j;
}
}
if (maxIdx == -1) {
// System.out.println("no maximum - intersect the remaining trans ");
BDD leftTrans = Env.TRUE();
for (int q = 0; q < currList.size(); q++) {
leftTrans.andWith(currList.get(q));
}
BDDVarSet e = leftTrans.support().intersect(cachedUnprimeVars);
// System.out.println("resulting E: " + e);
// System.out.println("intersect with prime: " + leftTrans.support().intersect(cachedPrimeVars));
// System.out.println("is TRUE: " + leftTrans.isOne());
// System.out.println("is FALSE: " + leftTrans.isZero());
if (!e.isEmpty()) {
partTransQuantList.add(new TransQuantPair(leftTrans, e));
}
currList.clear();
} else {
// System.out.println("found maximum E: " + maxSet);
partTransQuantList.add(new TransQuantPair(currList.get(maxIdx), maxSet));
currList.remove(maxIdx);
}
}
finalTrans.add(partTransQuantList);
}
// NOTE: keep the order of sets of every list, but order according the BDDVarSets between the lists.
// while (!finalTrans.isEmpty()) {
// int maxSize = 0;
// int maxIdx = -1;
// for (int k = 0; k < finalTrans.size(); k++) {
// System.out.println("------------------------------------" + finalTrans.get(k).get(0).quantSet.size());
// if (maxSize < finalTrans.get(k).get(0).quantSet.size()) {
// maxSize = finalTrans.get(k).get(0).quantSet.size();
// maxIdx = k;
// }
// }
// transQuantList.add(finalTrans.get(maxIdx).get(0));
// finalTrans.get(maxIdx).remove(0);
// if (finalTrans.get(maxIdx).isEmpty()) {
// finalTrans.remove(maxIdx);
// }
// }
for (int j = 0; j < transQuantList.size(); j++) {
BDDVarSet supp = transQuantList.get(j).partTrans.support();
System.out.println("transQuantList["+j+"].support = " + supp + ", E_"+j+" = " + transQuantList.get(j).quantSet);
supp.free();
}
}
/**
* <p>
* A state s in included in the returning result if responder module can force this module to reach a state in
* "to".<br>
* That is, regardless of how this module will move from the result, the responder module can choose an appropriate
* move into "to".
* </p>
*
* @param responder
* The module which moves (i.e. this is the responder).
* @param to
* The states to reach.
* @return The states which can be controlled by this module.
*/
public BDD yieldStatesTransDecomposed(PlayerModule responder, BDD to) {
List<TransQuantPair> responder_transQuantList = responder.getTransQuantList();
// System.out.println("to.support: " + to.support());
BDD res = Env.prime(to);
for (int i = 0; i < responder_transQuantList.size(); i++) {
// BDD tmp = res.and(responder_transQuantList.get(i).partTrans);
// System.out.println("sys is trans: " + responder_transQuantList.get(i).equals(responder.trans()));
// res.free();
// res = tmp.exist(responder_transQuantList.get(i).quantSet);
// tmp.free();
BDD tmp;
if (simConjunctAbs) {
tmp = res.relprod(responder_transQuantList.get(i).partTrans, responder_transQuantList.get(i).quantSet);
res.free();
res = tmp;
} else {
tmp = res.and(responder_transQuantList.get(i).partTrans);
res.free();
res = tmp.exist(responder_transQuantList.get(i).quantSet);
tmp.free();
}
}
if (PlayerModule.TEST_MODE) {
// System.out.println("-------res.nodeCount = " + res.nodeCount());
BDD tmpPrimedBdd = Env.prime(to);
BDD tmpAndBdd = tmpPrimedBdd.and(responder.trans());
BDD exy = tmpAndBdd.exist(responder.modulePrimeVars());
if (!exy.equals(res)){
System.err.println("exy not equals res" );
System.err.println(" exy.support() = " + exy.support());
System.err.println(" res.support() = " + res.support());
assert(false);
}
exy.free();
tmpAndBdd.free();
tmpPrimedBdd.free();
}
for (int i = 0; i < this.transQuantList.size(); i++) {
BDD tmp = this.transQuantList.get(i).partTrans.imp(res);
res.free();
res = tmp.forAll(this.transQuantList.get(i).quantSet);
tmp.free();
}
if (PlayerModule.TEST_MODE) {
BDDVarSet intrTest = getIntersectSupportWithPrimed(res);
if (!intrTest.isEmpty()) {
System.err.println("ERR: has prime vars!!!");
System.err.println(" res.support() = " + res.support());
System.err.println(" res.support().intersect(cachedPrimeVars) = " + intrTest);
}
intrTest.free();
BDD res2 = yieldStatesOrig(responder, to);
if (!res2.equals(res))
{
System.err.println("ERR: Not equal yield states! ");
System.err.println("res.support() = " + res.support());
System.err.println("res2.support() = " + res2.support());
assert(false);
}
res2.free();
}
return res;
}
public BDD yieldStatesOrig(PlayerModule responder, BDD to) {
// System.out.println("yieldStatesOrig");
BDDVarSet responder_prime = responder.modulePrimeVars();
BDDVarSet this_prime = this.modulePrimeVars();
BDD tmpPrimedBdd = Env.prime(to);
// System.out.println("tmpPrimedBdd.nodeCount() = " + tmpPrimedBdd.nodeCount());
// System.out.println("responder.trans().nodeCount() = " + responder.trans().nodeCount());
BDD exy;
if (simConjunctAbs) {
exy = tmpPrimedBdd.relprod(responder.trans(), responder_prime);
} else {
BDD tmpAndBdd = tmpPrimedBdd.and(responder.trans());
// System.out.println("after and: tmpAndBdd.nodeCount() = " + tmpAndBdd.nodeCount());
// System.out.println("to == responder.justiceAt(0): " +to.equals(responder.justiceAt(0)));
// System.out.println("tmpPrimedBdd == tmpAndBdd: " + tmpPrimedBdd.equals(tmpAndBdd));
exy = tmpAndBdd.exist(responder_prime);
tmpAndBdd.free();
}
// System.out.println("after exist: exy = " + exy.toStringWithDomains());
// System.out.println("after exist: exy.nodeCount() = " + exy.nodeCount());
// System.out.println("after exist: exy.isOne() = " + exy.isOne());
// System.out.println("after exist: exy.isZero() = " + exy.isZero());
BDD exyImp = this.trans().imp(exy);
BDD res = exyImp.forAll(this_prime);
// System.out.println("res.nodeCount() = " + res.nodeCount());
tmpPrimedBdd.free();
exy.free();
exyImp.free();
return res;
}
public BDD yieldStates(PlayerModule responder, BDD to) {
switch (transFunc) {
case SINGLE_FUNC:
return yieldStatesOrig(responder, to);
case DECOMPOSED_FUNC:
return yieldStatesTransDecomposed(responder,to);
case PARTIAL_DECOMPOSED_FUNC:
return yieldStatesTransDecomposed(responder,to);
default:
System.err.println("Unknown type: transFunc = " + transFunc);
break;
}
return Env.FALSE();
}
public BDD yieldStatesTrans(PlayerModule responder, BDD trans) {
BDDVarSet responder_prime = responder.modulePrimeVars();
BDDVarSet this_prime = this.modulePrimeVars();
BDD tmpAndBdd = trans.and(responder.trans());
BDD exy = tmpAndBdd.exist(responder_prime);
BDD exyImp = this.trans().imp(exy);
BDD res = exyImp.forAll(this_prime);
tmpAndBdd.free();
exy.free();
exyImp.free();
return res;
}
/**
* <p>
* A state s is included in the returning result if the this module can force the responder to reach a state in
* "to".<br>
* </p>
*
* @param responder
* The module to check for.
* @param to
* The states to reach.
* @return The states which can be controlled by this module.
*/
public BDD controlStates(PlayerModule responder, BDD to) {
BDDVarSet responder_prime = responder.modulePrimeVars();
BDDVarSet this_prime = this.modulePrimeVars();
BDD tmpPrimeBdd = Env.prime(to);
BDD tmpAndBdd = responder.trans().imp(tmpPrimeBdd);
BDD exy = tmpAndBdd.forAll(responder_prime);
BDD exyAnd = this.trans().and(exy);
BDD res = exyAnd.exist(this_prime);
tmpPrimeBdd.free();
tmpAndBdd.free();
exy.free();
exyAnd.free();
return res;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* <p>
* Add a Boolean variable to this module.
* </p>
*
* @param new_var the new variable name
* @param restrictIniTrans if true, then initials and transitions are restricted to the domain of the newly created variable
* @return The newly created field.
* @throws ModuleException
* If an illegal manipulation to the module had been done. e.g. duplicate variable names.
* @throws ModuleVariableException
*/
public ModuleBDDField addVar(String new_var, boolean aux, boolean restrictIniTrans) throws ModuleException,
ModuleVariableException {
return addVar(new_var, VarKind.BOOLEAN, 2, null, Integer.MIN_VALUE, aux, restrictIniTrans);
}
/**
* <p>
* Add a Boolean variable to this module.
* </p>
*
* @param new_var the new variable name
* @return The newly created field.
* @throws ModuleException
* If an illegal manipulation to the module had been done. e.g. duplicate variable names.
* @throws ModuleVariableException
*/
public ModuleBDDField addVar(String new_var, boolean aux) throws ModuleException,
ModuleVariableException {
return addVar(new_var, VarKind.BOOLEAN, 2, null, Integer.MIN_VALUE, aux, true);
}
/**
* <p>
* Add a set of values variable to this module.
* </p>
*
* @param new_var
* The new variable name.
* @param val_names
* The set of values that this variable can be assigned with.
* @param restrictIniTrans if true, then initials and transitions are restricted to the domain of the newly created variable
* @return The newly created field.
* @throws ModuleException
* If an illegal manipulation to the module had been done. e.g. duplicate variable names.
* @throws ModuleVariableException
*/
public ModuleBDDField addVar(String new_var, String[] val_names, boolean aux, boolean restrictIniTrans)
throws ModuleException, ModuleVariableException {
return addVar(new_var, VarKind.ENUMERATION, val_names.length, val_names, Integer.MIN_VALUE, aux, restrictIniTrans);
}
/**
* <p>
* Add a set of values variable to this module.
* </p>
*
* @param new_var
* The new variable name.
* @param val_names
* The set of values that this variable can be assigned with.
* @return The newly created field.
* @throws ModuleException
* If an illegal manipulation to the module had been done. e.g. duplicate variable names.
* @throws ModuleVariableException
*/
public ModuleBDDField addVar(String new_var, String[] val_names, boolean aux)
throws ModuleException, ModuleVariableException {
return addVar(new_var, val_names, aux, true);
}
/**
* <p>
* Add a range variable to this module.
* </p>
*
* @param new_var
* The new variable name.
* @param range_start
* The starting range of the variable.
* @param range_end
* The ending range of the variable.
* @param restrictIniTrans if true, then initials and transitions are restricted to the domain of the newly created variable
* @return The newly created field.
* @throws ModuleException
* If an illegal manipulation to the module had been done. e.g. duplicate variable names.
* @throws ModuleVariableException
*/
public ModuleBDDField addVar(String new_var, int range_start, int range_end, boolean aux, boolean restrictIniTrans)
throws ModuleException, ModuleVariableException {
return addVar(new_var, VarKind.RANGE, (range_end - range_start + 1), null, range_start, aux, restrictIniTrans);
}
/**
* <p>
* Add a range variable to this module.
* </p>
*
* @param new_var
* The new variable name.
* @param range_start
* The starting range of the variable.
* @param range_end
* The ending range of the variable.
* @return The newly created field.
* @throws ModuleException
* If an illegal manipulation to the module had been done. e.g. duplicate variable names.
* @throws ModuleVariableException
*/
public ModuleBDDField addVar(String new_var, int range_start, int range_end, boolean aux)
throws ModuleException, ModuleVariableException {
return addVar(new_var, range_start, range_end, aux, true);
}
/**
* <p>
* Check whether a variable with the given name exists.
* </p>
*
* @param addr
* The variable full name relative to this module.
* @return true if the variable field exists.
*/
public boolean hasVar(String addr) {
if (addr == null || addr.equals("")) {
return false;
}
for (ModuleBDDField coup : this.getAllFields()) {
if (coup.getName().equals(addr)) {
return true;
}
}
return false;
}
// private ModuleBDDField addVar(String new_var, VarKind kind, int values_size,
// String[] val_names, int range_start, boolean aux) throws ModuleException, ModuleVariableException {
// return addVar(new_var, kind, values_size, val_names, range_start, aux, true);
// }
private ModuleBDDField addVar(String new_var, VarKind kind, int values_size,
String[] val_names, int range_start, boolean aux, boolean restrictIniTrans) throws ModuleException, ModuleVariableException {
if (new_var == null || new_var.equals(""))
throw new ModuleException("Couldn't declare a variable with no " + "name.");
ModuleBDDField bdd_var = Env.getVar(new_var);
if (bdd_var != null) {
List<String> evs = Env.getValueNames(new_var);
switch (kind) {
case BOOLEAN:
if (evs.size() != 2 || !evs.contains("true") || !evs.contains("false")) {
throw new ModuleException("Variable " + new_var + " already declared with different domain.");
}
break;
case RANGE:
if (evs.size() != values_size || !evs.contains("" + range_start)
|| !evs.contains("" + (range_start + values_size - 1))) {
throw new ModuleException("Variable " + new_var + " already declared with different domain.");
}
break;
case ENUMERATION:
if (evs.size() != values_size || !evs.containsAll(Arrays.asList(val_names))) {
throw new ModuleException("Variable " + new_var + " already declared with different domain.");
}
break;
}
} else {
bdd_var = Env.newVar(new_var, values_size);
// register value names
switch (kind) {
case BOOLEAN:
Env.addBDDValueLookup(new_var, "false", bdd_var.getDomain().ithVar(0));
Env.addBDDValueLookup(new_var, "true", bdd_var.getDomain().ithVar(1));
Env.addBDDValueLookup(new_var + "'", "false", bdd_var.getOtherDomain().ithVar(0));
Env.addBDDValueLookup(new_var + "'", "true", bdd_var.getOtherDomain().ithVar(1));
break;
case RANGE:
Env.stringer.register_domain_module_values(bdd_var.getDomain(), range_start, values_size);
Env.stringer.register_domain_module_values(bdd_var.getOtherDomain(), range_start, values_size);
for (long i = range_start; i < range_start + values_size; i++) {
Env.addBDDValueLookup(new_var, "" + i, bdd_var.getDomain().ithVar(i - range_start));
Env.addBDDValueLookup(new_var + "'", "" + i, bdd_var.getOtherDomain().ithVar(i - range_start));
}
break;
case ENUMERATION:
if (values_size != val_names.length)
throw new ModuleException("Internal error: values list do " + "not match the size");
Env.stringer.register_domain_module_values(bdd_var.getDomain(), val_names);
Env.stringer.register_domain_module_values(bdd_var.getOtherDomain(), val_names);
for (long i = 0; i < val_names.length; i++) {
Env.addBDDValueLookup(new_var, val_names[(int) i], bdd_var.getDomain().ithVar(i));
Env.addBDDValueLookup(new_var + "'", val_names[(int) i], bdd_var.getOtherDomain().ithVar(i));
}
break;
default:
break;
}
}
this.allFields.add(bdd_var);
if (aux) {
this.auxFields.add(bdd_var);
} else {
this.nonAuxFields.add(bdd_var);
}
// update doms with domains of variables
this.doms.andWith(bdd_var.getDomain().domain());
this.doms.andWith(bdd_var.getOtherDomain().domain());
if(restrictIniTrans) {
// restrict trans to domains
conjunctTrans(doms.id());
// restrict initials to domains
conjunctInitial(bdd_var.getDomain().domain());
}
return bdd_var;
}
/**
* <p>
* Given a set of states, this procedure returns all states which can lead in a single module step to these states.
* </p>
*
* @param to
* The set of state to be reach.
* @return The set of states which can lead in a single module step to the given states.
*/
public BDD pred(BDD to) {
return Env.pred(trans, to);
}
/**
* Given a set of states {@code to}, returns all states from which this and the responder module can reach {@code to} together in a single step.
*
* @param responder
* @param to
* @return
*/
public BDD pred(PlayerModule responder, BDD to) {
return pred(responder, to, null);
}
/**
* <p>Given a set of states {@code to}, returns all states from which this and the responder module can reach {@code to} together in a single step.
* However, as opposed to {@link #pred(PlayerModule, BDD)}, in addition to the transitions of this and the responder module, the single step also respects
* the transitions of the {@link SFAModuleConstraint} associated with the specified existential requirement at position {@code regExpSfaExReqIdx}.</p>
*
* <p>Consequently, the returned set of states are of the form (s,q) where s is over the (unprimed) variables of both modules and q is over
* the variables that encode the states of the specified {@link SFAModuleConstraint}.</p>
*
* @param responder
* @param to
* @param regExpSfaExReqIdx the index of the existential requirement, expected to have a regular expression
* @return
*/
public BDD pred(PlayerModule responder, BDD to, int regExpSfaExReqIdx) {
ExistentialRequirement regExpExReq = this.existReqAt(regExpSfaExReqIdx);
if(!regExpExReq.hasRegExp()) {
throw new RuntimeException("The existential requirement at position " + regExpSfaExReqIdx + " does not have a regular expression (an SFA)");
}
return pred(responder, to, regExpExReq.getRegExpSfaConstraint());
}
/**
* <p>Given a set of states {@code to}, returns all states from which this and the responder module can reach {@code to} together in a single step.
* However, as opposed to {@link #pred(PlayerModule, BDD)}, in addition to the transitions of this and the responder module, the single step also respects
* the transitions of the specified {@link SFAModuleConstraint}, {@code exReqSfa}.</p>
*
* <p>Consequently, the returned set of states are of the form (s,q) where s is over the (unprimed) variables of both modules and q is over
* the variables that encode the states {@code exReqSfa}.</p>
*
* <p>However, if {@code exReqSfa} is {@code null}, it is ignored, and the result is as if {@link #pred(PlayerModule, BDD)} was invoked.</p>
*
* @param responder
* @param to
* @param exReqSfa
* @return
*/
public BDD pred(PlayerModule responder, BDD to, SFAModuleConstraint exReqSfa) {
switch (transFunc) {
case SINGLE_FUNC:
return predSingleTrans(responder, to, exReqSfa);
case DECOMPOSED_FUNC:
return predTransDecomposed(responder,to, exReqSfa);
case PARTIAL_DECOMPOSED_FUNC:
return predTransDecomposed(responder,to, exReqSfa);
default:
System.err.println("Unknown type: transFunc = " + transFunc);
break;
}
return Env.FALSE();
}
private BDD predSingleTrans(PlayerModule responder, BDD to, SFAModuleConstraint exReqSfa) {
BDD modulesTrans = (exReqSfa != null) ? (trans.and(responder.trans())).andWith(exReqSfa.getTrans().id()) : trans.and(responder.trans());
BDD primedTo = Env.prime(to);
BDDVarSet modulesPrimeVars = this.modulePrimeVars().union(responder.modulePrimeVars());
BDD result;
if (simConjunctAbs) {
result = primedTo.relprod(modulesTrans, modulesPrimeVars);
}
else {
BDD transAndTo = modulesTrans.and(primedTo);
result = transAndTo.exist(modulesPrimeVars);
transAndTo.free();
}
if (PlayerModule.TEST_MODE) {
BDD resSCA = primedTo.relprod(modulesTrans, modulesPrimeVars);
BDD transAndTo = modulesTrans.and(primedTo);
BDD resAndEx = transAndTo.exist(modulesPrimeVars);
transAndTo.free();
if (!resSCA.equals(resAndEx)){
System.err.println("resSCA not equals resAndEx" );
assert(false);
}
resSCA.free();
resAndEx.free();
}
modulesTrans.free();
primedTo.free();
modulesPrimeVars.free();
return result;
}
private BDD predTransDecomposed(PlayerModule responder, BDD to, SFAModuleConstraint exReqSfa) {
List<TransQuantPair> responder_transQuantList = responder.getTransQuantList();
BDD res = Env.prime(to);
BDD tmp;
if(exReqSfa != null) {
if(simConjunctAbs) {
tmp = res.relprod(exReqSfa.getTrans(), exReqSfa.getStatesVar().prime().support());
res.free();
res = tmp;
}
else {
tmp = res.and(exReqSfa.getTrans());
res.free();
res = tmp.exist(exReqSfa.getStatesVar().prime().support());
tmp.free();
}
}
for (int i = 0; i < responder_transQuantList.size(); i++) {
if (simConjunctAbs) {
tmp = res.relprod(responder_transQuantList.get(i).partTrans, responder_transQuantList.get(i).quantSet);
res.free();
res = tmp;
} else {
tmp = res.and(responder_transQuantList.get(i).partTrans);
res.free();
res = tmp.exist(responder_transQuantList.get(i).quantSet);
tmp.free();
}
}
for (int i = 0; i < this.transQuantList.size(); i++) {
if (simConjunctAbs) {
tmp = res.relprod(this.transQuantList.get(i).partTrans, this.transQuantList.get(i).quantSet);
res.free();
res = tmp;
}
else {
tmp = res.and(this.transQuantList.get(i).partTrans);
res.free();
res = tmp.exist(this.transQuantList.get(i).quantSet);
tmp.free();
}
}
if (PlayerModule.TEST_MODE) {
BDD singleRes = predSingleTrans(responder, to, exReqSfa);
// System.out.println("-------res.nodeCount = " + res.nodeCount());
if (!singleRes.equals(res)){
System.err.println("singleRes not equals res" );
System.err.println(" singleRes.support() = " + singleRes.support());
System.err.println(" res.support() = " + res.support());
assert(false);
}
singleRes.free();
}
return res;
}
/**
* <p>
* Given a set of state, this procedure return all states which can lead in any number of module steps to these
* states.
* </p>
*
* @param to
* The set of state to be reach.
* @return The set of states which can lead in any number of module step to the given states.
*/
public BDD allPred(BDD to) {
return Env.allPred(trans, to);
}
/**
* <p>
* This procedure return all states which the module can reach in a single step from given a set of state.
* </p>
*
* @param from
* The set of state to start from.
* @return The set of states which the module can reach in a single module step from the given states.
*/
public BDD succ(BDD from) {
return Env.succ(from, trans);
}
/**
* <p>
* This procedure return all states which the module can reach in any number of steps from given a set of state.
* </p>
*
* @param from
* (consumed/freed) The set of state to start from.
* @return The set of states which the module can reach in any number of module steps from the given states.
*/
public BDD allSucc(BDD from) {
return Env.allSucc(from, trans);
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer("PlayerModule ");
if (name != null) {
buf.append(name);
}
buf.append("\n");
buf.append("Variables\n");
for (ModuleBDDField field : allFields) {
String name = field.getName();
buf.append("{");
for (String val : Env.getValueNames(name)) {
buf.append(val + ", ");
}
buf.replace(buf.length() - 2, buf.length(), "");
buf.append("} ");
buf.append(name + "\n");
}
buf.append("\n");
buf.append("Initial\n");
buf.append(Env.toNiceString(initial));
buf.append("\n\n");
buf.append("Safety\n");
buf.append(Env.toNiceString(trans));
buf.append("\n\n");
buf.append("Justice\n");
int i = 0;
for (BDD j : justice) {
buf.append(i++ + ": ");
buf.append(Env.toNiceString(j));
}
buf.append("\n\n");
buf.append("Existential\n");
i = 0;
for(ExistentialRequirement existReq : existential) {
buf.append(i++ + ": ");
if(existReq.hasRegExp()) {
buf.append(existReq.getRegExpSfaConstraint().toString());
}
else {
int j = 0;
buf.append("The following ordered list of assertions:");
for(BDD fAssrt : existReq.getExistFinallyAssrts()) {
buf.append("\n");
buf.append(j++ + ": ");
buf.append(Env.toNiceString(fAssrt));
}
}
buf.append("\n");
}
buf.append("\n\n");
return buf.toString();
}
/**
* fields that are marked as auxiliary
*
* @return
*/
public List<ModuleBDDField> getAuxFields() {
return auxFields;
}
/**
* fields that are not marked as auxiliary
*
* @return
*/
public List<ModuleBDDField> getNonAuxFields() {
return nonAuxFields;
}
/**
* set initial to TRUE (restricted by variable domain constraint)
*/
public void resetInitial() {
this.initial.free();
this.initial = this.doms.exist(this.modulePrimeVars());
}
/**
* set trans to TRUE (restricted by variable domain constraint).
* Always sets the single trans to TRUE; if a decomposed trans is used, then it is also set to TRUE
*/
public void resetTrans() {
//an implementation which assumes that a single transition relation is always constructued
this.trans.free();
this.trans = this.doms.id();
if (transFunc == TransFuncType.DECOMPOSED_FUNC ||
transFunc == TransFuncType.PARTIAL_DECOMPOSED_FUNC) {
this.transList.clear();
this.transList.add(this.doms.id());
this.transQuantList.clear();
}
// if (transFunc == TransFuncType.SINGLE_FUNC) {
// this.trans.free();
// this.trans = this.doms.id();
// } else {
// if (TEST_MODE) {
// this.trans.free();
// this.trans = this.doms.id();
// }
// this.transList.clear();
// this.transList.add(this.doms.id());
// this.transQuantList.clear();
// }
}
/**
* set single trans to TRUE (restricted by variable domain constraint)
*/
public void resetSingleTrans() {
this.trans.free();
this.trans = this.doms.id();
}
/**
* frees and removes all justices
*/
public void resetJustice() {
for (BDD b : justice) {
b.free();
}
justice.clear();
justiceIDs.clear();
}
/**
* calls resetInitial(); resetTrans(); resetJustice(); to free all BDDs and start from clean module with only domain
* restrictions
*
*/
public void reset() {
resetInitial();
resetTrans();
resetJustice();
}
public void free() {
initial.free();
trans.free();
Env.free(justice);
if (cachedPrimeVars != null) {
cachedPrimeVars.free();
}
if (cachedUnprimeVars != null) {
cachedUnprimeVars.free();
}
}
public BDD getDoms() {
return doms;
}
/**
* Used for returning a new module composed of current module and the given module.
*
* Doesn't change current or given module.
*
* @param other
* @return
*/
public PlayerModule compose(PlayerModule other) {
PlayerModule composed = new PlayerModule();
composed.setName(this.name + "_composed_" + other.getName());
composed.doms = this.doms.and(other.doms);
composed.allFields.addAll(this.allFields);
composed.allFields.addAll(other.allFields);
composed.auxFields.addAll(this.auxFields);
composed.auxFields.addAll(other.auxFields);
composed.nonAuxFields.addAll(this.nonAuxFields);
composed.nonAuxFields.addAll(other.nonAuxFields);
composed.conjunctInitial(this.initial().id());
composed.conjunctInitial(other.initial().id());
composed.conjunctTrans(this.trans().id());
composed.conjunctTrans(other.trans().id());
for (int i = 0; i < this.justiceNum(); i++) {
composed.addJustice(this.justiceAt(i).id());
}
for (int i = 0; i < other.justiceNum(); i++) {
composed.addJustice(other.justiceAt(i).id());
}
return composed;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.ui.action;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.IConsoleView;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.part.FileEditorInput;
import tau.smlab.syntech.bddgenerator.BDDGenerator.TraceInfo;
import tau.smlab.syntech.gameinput.kind.PitermanSyntacticReduction;
import tau.smlab.syntech.gameinput.model.GameInput;
import tau.smlab.syntech.gameinputtrans.TranslationException;
import tau.smlab.syntech.gameinputtrans.TranslationProvider;
import tau.smlab.syntech.gameinputtrans.translator.DefaultTranslators;
import tau.smlab.syntech.gameinputtrans.translator.Translator;
import tau.smlab.syntech.spectragameinput.ErrorsInSpectraException;
import tau.smlab.syntech.spectragameinput.SpectraInputProvider;
import tau.smlab.syntech.spectragameinput.SpectraTranslationException;
import tau.smlab.syntech.ui.jobs.CheckRealizabilityJob;
import tau.smlab.syntech.ui.jobs.ChecksJob;
import tau.smlab.syntech.ui.jobs.CounterStrategyJob;
import tau.smlab.syntech.ui.jobs.MarkerKind;
import tau.smlab.syntech.ui.jobs.SyntechBDDEngineExclusiveRule;
import tau.smlab.syntech.ui.jobs.SyntechJob;
import tau.smlab.syntech.ui.jobs.SynthesizeSharedControllerJob;
import tau.smlab.syntech.ui.jobs.SynthesizeConcreteControllerJob;
import tau.smlab.syntech.ui.jobs.SynthesizeJitSymbolicControllerJob;
import tau.smlab.syntech.ui.jobs.SynthesizeSymbolicControllerJob;
import tau.smlab.syntech.ui.logger.SpectraLogger;
import tau.smlab.syntech.ui.preferences.PreferencePage;
import tau.smlab.syntech.ui.preferences.PreferenceConstants;
public class SynthesisAction implements IObjectActionDelegate, IEditorActionDelegate {
private IFile specFile;
private Shell shell;
@Override
public void run(IAction action) {
if (specFile == null) {
MessageDialog.openInformation(shell, "SYNTECH", "Please select one (and only one) Spectra file.");
}
if (!savePage()) {
return;
}
SyntechJob job = null;
closeOldProblemView();
switch (action.getId()) {
case "tau.smlab.syntech.syntSymbAction":
job = new SynthesizeSymbolicControllerJob();
break;
case "tau.smlab.syntech.syntJitSymbAction":
job = new SynthesizeJitSymbolicControllerJob();
break;
case "tau.smlab.syntech.syntSharedSymbAction":
job = new SynthesizeSharedControllerJob();
break;
case "tau.smlab.syntech.syntCmpAction":
job = new SynthesizeConcreteControllerJob();
break;
case "tau.smlab.syntech.checkRealAction":
job = new CheckRealizabilityJob();
// job.setTrace(TraceInfo.ALL);
break;
case "tau.smlab.syntech.checksAction":
job = new ChecksJob();
job.setTrace(TraceInfo.ALL);
break;
case "tau.smlab.syntech.debugCmpAction":
job = new CounterStrategyJob();
break;
default:
System.err.println("Unhandled action id: " + action.getId());
break;
}
MessageConsole console = getConsole();
console.clearConsole();
showConsole();
long setupTime = 0, parsingTime, simplificationTime;
long start = System.currentTimeMillis();
job.setSpecFile(specFile);
job.setConsole(console);
job.setUser(true);
job.clearMarkers();
GameInput gi = null;
try {
gi = SpectraInputProvider.getGameInput(specFile.getFullPath().toString());
} catch (ErrorsInSpectraException e) {
job.printToConsole("Errors in input file:");
job.printToConsole(e.getMessage());
setupTime = System.currentTimeMillis() - start;
job.printToConsole("Setup time: " + setupTime + "ms");
return;
} catch (SpectraTranslationException e) {
job.printToConsole("Problems encountered in input file:");
job.printToConsole(e.getMessage());
setupTime = System.currentTimeMillis() - start;
job.printToConsole("Setup time: " + setupTime + "ms");
job.createMarker(e.getTraceId(), e.getMessage(), MarkerKind.CUSTOM_TEXT_ERROR);
return;
}
parsingTime = System.currentTimeMillis() - start;
job.printToConsole("Parsing: " + parsingTime + "ms");
if (PreferencePage.getSynthesisMethod().equals(PreferenceConstants.SYNTHESIS_METHOD_PITERMAN_REDUCTION))
PitermanSyntacticReduction.doReduction(gi);
if (job.needsBound() && !gi.getWeightDefs().isEmpty()) {
InputDialog d = new InputDialog(shell, "Specify Energy Bound",
"Please specify a suitable bound for the Energy Game:", "20", new IInputValidator() {
@Override
public String isValid(String newText) {
try {
Integer.parseInt(newText);
} catch (Exception e) {
return "Unable to parse integer!";
}
return null;
}
});
if (d.open() == Window.OK) {
gi.setEnergyBound(Integer.parseInt(d.getValue()));
} else {
gi.setEnergyBound(20);
}
job.printToConsole("Bound set to: " + gi.getEnergyBound());
}
start = System.currentTimeMillis();
try {
List<Translator> transList = DefaultTranslators.getDefaultTranslators();
TranslationProvider.translate(gi, transList);
job.setTranslators(transList);
} catch (TranslationException e) {
job.printToConsole(e.getMessage());
if (e.getTraceId() >= 0) {
job.createMarker(e.getTraceId(), e.getMessage(), MarkerKind.CUSTOM_TEXT_ERROR);
}
return;
}
simplificationTime = System.currentTimeMillis() - start;
job.printToConsole("Simplification: " + simplificationTime + "ms");
job.setGameInput(gi);
job.setRule(new SyntechBDDEngineExclusiveRule());
job.schedule();
SpectraLogger.logOperationStart(specFile, action.getId());
}
/**
* Closes problem view(s) (if it was opened) from previous actions.
*/
private void closeOldProblemView() {
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
public void run() {
String[] possibleViewsId = { "unrealizableCoreMarker", "wellSeparatedCoreMarker",
"specAnalysisMarker" };
for (int i = 0; i < possibleViewsId.length; i++) {
// check if possibleViewsId[i] was opened
IViewPart viewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.findView(possibleViewsId[i]);
if (viewPart != null) {
// possibleViewsId[i] was opened. close it.
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().hideView(viewPart);
}
}
}
});
}
@Override
public void selectionChanged(IAction action, ISelection selection) {
if (selection instanceof StructuredSelection && !selection.isEmpty()) {
StructuredSelection s = (StructuredSelection) selection;
if (s.size() > 1) {
specFile = null;
} else {
specFile = (IFile) s.iterator().next();
}
}
}
@Override
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
}
private MessageConsole getConsole() {
String name = "SYNTECH Console";
ConsolePlugin plugin = ConsolePlugin.getDefault();
IConsoleManager conMan = plugin.getConsoleManager();
IConsole[] existing = conMan.getConsoles();
for (int i = 0; i < existing.length; i++)
if (name.equals(existing[i].getName()))
return (MessageConsole) existing[i];
// no console found, so create a new one
MessageConsole myConsole = new MessageConsole(name, null);
conMan.addConsoles(new IConsole[] { myConsole });
return myConsole;
}
/**
* If the page is unsaved, ask user if he wants to save it first
*
* @return false if the user has chosen to abort
*/
private boolean savePage() {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
// check if file is saved
IEditorPart editorPart = page.getActiveEditor();
if (editorPart != null && editorPart.isDirty()) {
boolean isYes = MessageDialog.openQuestion(shell, "SYNTECH",
"The file is not saved. Select 'Yes' to save and 'No' to abort.");
if (isYes) {
editorPart.doSave(null);
} else {
return false;
}
}
return true;
}
private void showConsole() {
try {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IConsoleView view = (IConsoleView) page.showView(IConsoleConstants.ID_CONSOLE_VIEW);
view.display(getConsole());
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void setActiveEditor(IAction action, IEditorPart targetEditor) {
if (targetEditor != null) {
IEditorInput input = targetEditor.getEditorInput();
if (input != null && input instanceof FileEditorInput) {
IFile ifile = ((FileEditorInput) input).getFile();
if (ifile != null) {
if ("spectra".equals(ifile.getFileExtension())) {
specFile = ifile;
}
}
}
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinputtrans.translator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import tau.smlab.syntech.gameinput.model.Constraint;
import tau.smlab.syntech.gameinput.model.Constraint.Kind;
import tau.smlab.syntech.gameinput.model.ExistentialConstraint;
import tau.smlab.syntech.gameinput.model.GameInput;
import tau.smlab.syntech.gameinput.model.Player;
import tau.smlab.syntech.gameinput.model.TypeDef;
import tau.smlab.syntech.gameinput.model.Variable;
import tau.smlab.syntech.gameinput.model.WeightDefinition;
import tau.smlab.syntech.gameinput.spec.Operator;
import tau.smlab.syntech.gameinput.spec.PrimitiveValue;
import tau.smlab.syntech.gameinput.spec.Spec;
import tau.smlab.syntech.gameinput.spec.SpecExp;
import tau.smlab.syntech.gameinput.spec.VariableReference;
import tau.smlab.syntech.gameinputtrans.AuxVariableGenerator;
import tau.smlab.syntech.gameinputtrans.TranslationException;
/**
* translate every operator to a variable added to AUX the SpecExp with the past operator becomes a VariableReference to
* the new variable the variable value is defined by initial and safety constraints that are added to the AUX module
* (details what constraints to add are in code below)
*
* https://smlab.unfuddle.com/svn/smlab_synthesis1/trunk/AspectLTL/net.games.core/src/net/games/core/parser/SpecificationParser.java
*
* Depends on DefinesTranslator, CounterTranslator, MonitorTranslator, PatternConstraintTranslator, PredicateInstanceTranslator
*
*/
public class PastLTLTranslator implements Translator {
private Player auxPlayer;
private Map<Integer, VariableReference> pasLTLSpecsHashMap;
private List<Constraint> auxPastConstraints;
private Map<VariableReference, List<Constraint>> varRefToConstraints;
@Override
public void translate(GameInput input) {
auxPlayer = input.getAux();
pasLTLSpecsHashMap = new HashMap<>();
auxPastConstraints = new ArrayList<Constraint>();
varRefToConstraints = new HashMap<>();
// sys constraints
for (Constraint c : input.getSys().getConstraints()) {
if (c.getSpec().isPastLTLSpec()) {
try {
c.setSpec(replacePastOperators(c.getSpec(), c.getTraceId()));
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// sys existential constraints
for (ExistentialConstraint exC : input.getSys().getExistentialConstraints()) {
Spec currSpec;
if(!exC.isRegExp()) {
for(int i = 0; i < exC.getSize() ; i++) {
currSpec = exC.getSpec(i);
if (currSpec.isPastLTLSpec()) {
try {
exC.replaceSpec(i, replacePastOperators(currSpec, exC.getTraceId()));
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
// env constraints
for (Constraint c : input.getEnv().getConstraints()) {
if (c.getSpec().isPastLTLSpec()) {
try {
c.setSpec(replacePastOperators(c.getSpec(), c.getTraceId()));
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// aux constraints
for (Constraint c : input.getAux().getConstraints()) {
if (c.getSpec().isPastLTLSpec()) {
try {
c.setSpec(replacePastOperators(c.getSpec(), c.getTraceId()));
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// weights
for (WeightDefinition w : input.getWeightDefs()) {
if (w.getDefinition().getSpec().isPastLTLSpec()) {
try {
w.getDefinition().setSpec(replacePastOperators(w.getDefinition().getSpec(), w.getDefinition().getTraceId()));
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
input.getAux().getConstraints().addAll(auxPastConstraints);
}
private Spec replacePastOperators(Spec spec, int traceId) throws CloneNotSupportedException {
if (spec instanceof SpecExp) {
int specHash = -1;
SpecExp se = (SpecExp) spec;
if (se.getOperator().isPastLTLOp()) {
specHash= getHashCode(spec, traceId);
VariableReference hashedReference = pasLTLSpecsHashMap.get(specHash);
if (hashedReference != null) {
return hashedReference;
}
}
for (int i = 0; i < se.getChildren().length; i++) {
se.getChildren()[i] = replacePastOperators(se.getChildren()[i], traceId);
}
if (se.getOperator().isPastLTLOp()) {
// prepare common variables
Variable aux = addFreshAuxVariable(se.getOperator(), traceId);
Spec p_aux = new SpecExp(Operator.PRIME, new VariableReference(aux));
Spec safetySpec;
switch (se.getOperator()) {
case PREV:
// negation of aux var
Spec iniSpec = new SpecExp(Operator.NOT, new VariableReference(aux));
auxPastConstraints.add(new Constraint(Kind.INI, iniSpec, null, traceId));
// update of aux var
safetySpec = new SpecExp(Operator.IFF, p_aux, se.getChildren()[0]);
auxPastConstraints.add(new Constraint(Kind.SAFETY, safetySpec, null, traceId));
break;
case ONCE:
iniSpec = new SpecExp(Operator.IFF, new VariableReference(aux), se.getChildren()[0]);
auxPastConstraints.add(new Constraint(Kind.INI, iniSpec, null, traceId));
Spec auxOrPChild = new SpecExp(Operator.OR, new VariableReference(aux), new SpecExp(Operator.PRIME, se.getChildren()[0].clone()));
safetySpec = new SpecExp(Operator.IFF, p_aux, auxOrPChild);
auxPastConstraints.add(new Constraint(Kind.SAFETY, safetySpec, null, traceId));
break;
case HISTORICALLY:
iniSpec = new SpecExp(Operator.IFF, new VariableReference(aux), se.getChildren()[0]);
auxPastConstraints.add(new Constraint(Kind.INI, iniSpec, null, traceId));
Spec auxAndPChild = new SpecExp(Operator.AND, new VariableReference(aux), new SpecExp(Operator.PRIME, se.getChildren()[0].clone()));
safetySpec = new SpecExp(Operator.IFF, p_aux, auxAndPChild);
auxPastConstraints.add(new Constraint(Kind.SAFETY, safetySpec, null, traceId));
break;
case SINCE:
// aux initially set by second child
iniSpec = new SpecExp(Operator.IFF, new VariableReference(aux), se.getChildren()[1]);
auxPastConstraints.add(new Constraint(Kind.INI, iniSpec, null, traceId));
Spec primedChild1 = new SpecExp(Operator.PRIME, se.getChildren()[0].clone());
Spec primedChild2 = new SpecExp(Operator.PRIME, se.getChildren()[1].clone());
Spec child1AndAux = new SpecExp(Operator.AND, new VariableReference(aux), primedChild1);
Spec child2_Or_Child1AndAux = new SpecExp(Operator.OR,primedChild2, child1AndAux);
safetySpec = new SpecExp(Operator.IFF, p_aux, child2_Or_Child1AndAux);
auxPastConstraints.add(new Constraint(Kind.SAFETY, safetySpec, null, traceId));
break;
case TRIGGERED:
Spec child1OrChild2 = new SpecExp(Operator.OR, se.getChildren()[0], se.getChildren()[1]);
iniSpec = new SpecExp(Operator.IFF, new VariableReference(aux), child1OrChild2);
auxPastConstraints.add(new Constraint(Kind.INI, iniSpec, null, traceId));
primedChild1 = new SpecExp(Operator.PRIME, se.getChildren()[0].clone());
primedChild2 = new SpecExp(Operator.PRIME, se.getChildren()[1].clone());
child1AndAux = new SpecExp(Operator.AND, new VariableReference(aux), primedChild1);
child2_Or_Child1AndAux = new SpecExp(Operator.OR,primedChild2, child1AndAux);
safetySpec = new SpecExp(Operator.IFF, p_aux, child2_Or_Child1AndAux);
auxPastConstraints.add(new Constraint(Kind.SAFETY, safetySpec, null, traceId));
break;
default:
throw new TranslationException("Unsupported PastLTL operator " + se.getOperator(), traceId);
}
VariableReference variableReference = new VariableReference(aux);
pasLTLSpecsHashMap.put(specHash, variableReference);
varRefToConstraints.put(variableReference, new ArrayList<>(auxPastConstraints.subList
(auxPastConstraints.size()-2, auxPastConstraints.size())));
return variableReference;
}
}
return spec;
}
private int getHashCode(Spec spec, int traceId) {
if (spec instanceof VariableReference)
{
VariableReference variableReference = (VariableReference)spec;
return variableReference.getReferenceName().hashCode();
}
else if (spec instanceof PrimitiveValue)
{
PrimitiveValue primitiveValue = (PrimitiveValue)spec;
return primitiveValue.getValue().hashCode();
}
else if (! (spec instanceof SpecExp))
{
throw new TranslationException("PastLTL Spec is not VariableReference / PrimitiveValue / SpecExp", traceId);
}
SpecExp specExp = (SpecExp)spec;
int hashCode = specExp.getOperator().hashCode();
for (int i = 0; i <specExp.getChildren().length; i++)
{
Spec child = specExp.getChildren()[i];
hashCode *= 31;
hashCode += getHashCode(child, traceId);
}
return hashCode;
}
private Variable addFreshAuxVariable(Operator operator, int traceId) {
String varName = operator.toString() + "_aux_" + AuxVariableGenerator.useVar();
Variable aux = new Variable(varName, new TypeDef());
auxPlayer.addVar(aux);
return aux;
}
public List<Constraint> getConstraintsOfVarRef(VariableReference varRef) {
return this.varRefToConstraints.get(varRef);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinput.spec;
import java.util.List;
import tau.smlab.syntech.gameinput.model.Pattern;
public class SpecWrapper {
private Spec spec;
private boolean hasPatternReference;
private Pattern pattern;
private List<Spec> parameters;
/**
* Use this constructor to create a regular spec (without pattern reference)
* @param spec
*/
public SpecWrapper(Spec spec)
{
this.spec = spec;
this.hasPatternReference = false;
this.pattern = null;
this.parameters = null;
}
/**
* Use this constructor to create a spec that describes a pattern reference
* @param pattern
* @param parameters the passed parameters to the pattern (must be a boolean expression)
*/
public SpecWrapper(Pattern pattern, List<Spec> parameters)
{
this.spec = null;
this.hasPatternReference = true;
this.pattern = pattern;
this.parameters = parameters;
}
public Spec getSpec() {
return spec;
}
public boolean isHasPatternReference() {
return hasPatternReference;
}
public Pattern getPattern() {
return pattern;
}
public List<Spec> getParameters() {
return parameters;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.sfa;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
////imports for toString() method (returns a DOT representation of the SFA)
//import org.eclipse.gef.dot.internal.DotAttributes;
//import org.eclipse.gef.dot.internal.DotExport;
//import org.eclipse.gef.dot.internal.language.dot.GraphType;
//import org.eclipse.gef.graph.Graph;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.sfa.PowerSetIterator.PowerSetIteratorType;
/**
*
* @author <NAME>
* @author <NAME>
*
* @param <T> the type of the states the SFA has
*/
@SuppressWarnings("restriction")
public abstract class BaseSFA<T extends BaseSFAState<T>> implements SFA {
final public static String EPS_LABEL = "\u03B5"; //Unicode code point of 'Epsilon'
protected T ini; // the initial state of this automaton
protected PowerSetIteratorType psIterType; // the type of the powerset (of outgoing transitions) iterator used for by the determinization algorithm
protected BaseSFA(SFAState ini, PowerSetIteratorType psIterType) {
this.setIni(ini);
this.psIterType = psIterType;
}
protected BaseSFA() {
this(null, PowerSetIteratorType.EFFICIENT);
}
protected BaseSFA(SFAState ini) {
this(ini, PowerSetIteratorType.EFFICIENT);
}
protected BaseSFA(PowerSetIteratorType psIterType) {
this(null, psIterType);
}
protected abstract BaseSFA<T> newSfaInstance();
protected abstract BaseSFA<T> newSfaInstance(T ini);
@Override
public T getIni() {
return ini;
}
@Override
public boolean enablesEpsTrans() {
return false;
}
@Override
public abstract T newSfaState(boolean isAccepting);
/**
* Returns the type information of the states this automaton has.
*
* @return
*/
protected abstract Class<T> getStatesType();
/**
* Sets the initial state of this automaton.
*/
@SuppressWarnings("unchecked")
@Override
public void setIni(SFAState ini) {
if ((ini != null) && (!ini.getClass().equals(this.getStatesType()))) {
throw new SFAException("The specified state has an invalid type. The initial state must be of type " + this.getStatesType().getSimpleName());
}
this.ini = (T) ini;
}
@Override
public PowerSetIteratorType getPsIterType() {
return psIterType;
}
@Override
public void setPsIterType(PowerSetIteratorType powerSetIteratorType) {
this.psIterType = powerSetIteratorType;
}
@Override
public Set<T> finalStates() {
Queue<T> worklist = new LinkedList<>();
Set<T> seen = new LinkedHashSet<>();
Set<T> finalStates = new LinkedHashSet<>();
worklist.add(ini);
seen.add(ini);
while (!worklist.isEmpty()) {
T s = worklist.remove();
if (s.isAccepting()) {
finalStates.add(s);
}
// add successors which have not been checked yet
for (T succ : s.getSuccessors()) {
if (!seen.contains(succ)) {
worklist.add(succ);
seen.add(succ);
}
}
}
return finalStates;
}
@Override
public void free() {
Queue<T> worklist = new LinkedList<>();
Set<T> seen = new LinkedHashSet<>();
worklist.add(ini);
seen.add(ini);
while (!worklist.isEmpty()) {
T s = worklist.remove();
// free the guards of all outgoing transitions
for (BDD guard : s.getSucc().values()) {
if (!guard.isFree()) {
guard.free();
}
}
// add successors which have not been searched
for (T succ : s.getSuccessors()) {
if (!seen.contains(succ)) {
worklist.add(succ);
seen.add(succ);
}
}
}
}
@Override
public boolean isDeterministic() {
Queue<T> worklist = new LinkedList<>();
Set<T> seen = new LinkedHashSet<>();
worklist.add(ini);
seen.add(ini);
while (!worklist.isEmpty()) {
T s = worklist.remove();
// check determinism of outgoing transitions
if (hasOverlap(s.getSucc().values())) {
return false;
}
// add successors not checked yet
for (T succ : s.getSuccessors()) {
if (!seen.contains(succ)) {
worklist.add(succ);
seen.add(succ);
}
}
}
return true;
}
@Override
public boolean hasOneFinalState() {
return false;
}
@Override
public SFAState getFinalState() {
throw new SFAException("This automaton does not have a single, unique final state.");
}
@Override
public void setFinalState(SFAState finalState) {
throw new SFAException("This automaton does not have a single, unique final state.");
}
@Override
public abstract BaseSFA<T> copy();
@Override
public BaseSFA<T> eliminateEpsTrans() {
return this.copy();
}
@Override
public boolean hasEpsTrans() {
return false;
}
@Override
public BaseSFA<T> determinize() {
return this.buildDetAutomaton();
}
/**
* Returns a deterministic SFA (DSFA) that is equivalent to this SFA,
* which is assumed to be without epsilon transitions.
*
* @return
*/
protected BaseSFA<T> buildDetAutomaton() {
// create a fresh copy of this automaton and remove all the dead states from the
// fresh copy
BaseSFA<T> copySfa = this.copy();
copySfa.removeDeadStates();
// check if the removal of dead states has resulted in a deterministic automaton
if (copySfa.isDeterministic()) {
return copySfa; // we have a deterministic automaton so we are done
}
// we have that copySfa is non-deterministic so we need to determinize it
BaseSFA<T> deterministicAutomaton = this.newSfaInstance();
/*
* To distinguish between different states in the DSFA, we need to remember a
* mapping between sets of states in this SFA to the new states in the DSFA that
* we create.
*/
Map<Set<T>, T> stateSubsetsToDeterministicStatesMapping = new HashMap<>();
Set<T> iniSingletonSet = new HashSet<>(Arrays.asList(copySfa.ini));
/*
* The initial state in the DSFA is a singleton containing the SFA's initial
* state.
*/
T determinsticAutomatonInitialState = copySfa.ini.cloneWithoutSucc();
stateSubsetsToDeterministicStatesMapping.put(iniSingletonSet, determinsticAutomatonInitialState);
deterministicAutomaton.setIni(determinsticAutomatonInitialState);
/*
* We use a stack to do a DFS search on (the copy without dead states of) this
* SFA. It will contain the state sets of the DSFA that we create.
*/
List<Set<T>> workStack = new Stack<>();
workStack.add(0, iniSingletonSet);
while (!workStack.isEmpty()) {
Map<T, BDD> allTransitionsMap = new HashMap<>();
Set<T> currentStateSet = workStack.remove(0), tautologySuccs = new HashSet<>();
for (T state : currentStateSet) {
for (Map.Entry<T, BDD> transition : state.getSucc().entrySet()) {
/*
* Optimization 1: We don't need to add to the transitions set (denoted by
* delta_A(q) in the paper) unsatisfiable transitions, since each subset t of
* delta_A(q) that contains that transition will result a unsatisfiable formula
* phi_t, since the left conjunction will not be satisfiable.
*
* Optimization 2: If a subset t of delta_A(q) DOESN'T contains a tautology
* transition, then the resulting phi_t will be unsatisfiable, since the right
* conjunction will be unsatisfiable. Thus, it suffice to go over delta_A(q)'s
* subsets that contain all delta_A(q)'s tautology transitions, which is
* equivalent to going over all the subsets of delta_A(q)\{tautologies} and
* adding to each subset {tautologies} (the set of all tautology transitions).
*
* Optimization 3: If there are multiple transitions to the SAME target state,
* then we can transform them into a single transition by taking their
* disjunction. This may save (exponentially many but redundant) iterations over
* subsets of delta_A(q) that contain different combinations of transitions to
* the SAME successor state. In case the disjunction evaluates to a tautology
* (i.e., it is trivially true), then we treat the "new" transition as in
* Optimization 2.
*
*/
if (!transition.getValue().isZero()) {
if (allTransitionsMap.containsKey(transition.getKey())) {
allTransitionsMap.get(transition.getKey()).orWith(transition.getValue().id());
if (allTransitionsMap.get(transition.getKey()).isOne()) {
// the guard of the transition to the successor state transition.getKey() is
// TRUE
allTransitionsMap.get(transition.getKey()).free();
allTransitionsMap.remove(transition.getKey());
tautologySuccs.add(transition.getKey());
}
} else if (!tautologySuccs.contains(transition.getKey())) {
// this is the first time a transition to this target/successor state is seen
if (transition.getValue().isOne()) {
// tautology transition
tautologySuccs.add(transition.getKey());
} else {
allTransitionsMap.put(transition.getKey(), transition.getValue().id());
}
}
}
}
}
/*
* Optimization 3: If delta_A(q) contains two transitions with semantically equivalent guards, psi_1 and psi_2, then a subset t that only contains
* one of them would yield an unsatisfiable phi_t (since psi_1 and not(psi_2) is unsatisfiable).
* Thus, we only consider subsets of delta_A(q) that either contain ALL the transitions in delta_A(q) that have
* equivalent guards or contain none of them. To achieve this, we only iterate over satisfiable subsets of delta_A(q) that contain
* at most one (arbitrarily chosen) representative of each subset of equivalent transitions in delta_A(q).
*
*/
//Map each "representative" successor state to all other successor states that have semantically equivalent transitions' guards (BDDs)
//Note: this might be an empty set
Map<T, Set<T>> reprSuccToSameGuardSuccs = new HashMap<>();
Set<T> sameGuardSuccs, seenSuccs = new HashSet<>();
BDD succGuard;
for(T succ : allTransitionsMap.keySet()) {
if(!seenSuccs.contains(succ)) {
seenSuccs.add(succ);
sameGuardSuccs = new HashSet<>();
reprSuccToSameGuardSuccs.put(succ, sameGuardSuccs);
succGuard = allTransitionsMap.get(succ);
for(T otherSucc : allTransitionsMap.keySet()) {
if(succ != otherSucc && allTransitionsMap.get(otherSucc).equals(succGuard)) {
sameGuardSuccs.add(otherSucc);
seenSuccs.add(otherSucc);
}
}
}
}
Map<T, BDD> reprTransitionsMap = new HashMap<>();
for(T repr : reprSuccToSameGuardSuccs.keySet()) {
reprTransitionsMap.put(repr, allTransitionsMap.get(repr));
}
allTransitionsMap = reprTransitionsMap;
Set<Map.Entry<T, BDD>> allTransitionsSet = allTransitionsMap.entrySet();
Iterator<Pair<Set<Map.Entry<T, BDD>>, BDD>> psIter = PowerSetIterator.getIterator(this.psIterType, allTransitionsSet);
Pair<Set<Map.Entry<T, BDD>>, BDD> nextPair;
Set<Map.Entry<T, BDD>> transitionsSubset, transitionsSubsetComplement;
boolean newDeterministicStateIsAccepting;
Set<T> allSuccStatesSet, missingSameGuardSuccs;
BDD transitionsGuardsConjunction;
T detCurrentState = stateSubsetsToDeterministicStatesMapping.get(currentStateSet), detSuccessorState;
while (psIter.hasNext()) {
nextPair = psIter.next();
transitionsSubset = nextPair.getLeft();
/*
* An empty transitions set is not interesting since its successor states set is
* empty (this corresponds to taking no transitions at all).
*/
if (!transitionsSubset.isEmpty() || !tautologySuccs.isEmpty()) {
transitionsGuardsConjunction = nextPair.getRight();
transitionsSubsetComplement = SFAUtil.getComplementOfTransSet(allTransitionsSet, transitionsSubset);
for (Map.Entry<T, BDD> t : transitionsSubsetComplement) {
if (transitionsGuardsConjunction.isZero()) {
break;
}
transitionsGuardsConjunction.andWith(t.getValue().not());
}
if (!transitionsGuardsConjunction.isZero()) {
allSuccStatesSet = SFAUtil.getTransitionsTargetStates(transitionsSubset);
//Add successor states that we removed/omitted, each of which has a transition guard equivalent to that of
//a "representative" successor state in allSuccStatesSet (See Optimization 3 above)
missingSameGuardSuccs = new HashSet<>();
for(T repr : allSuccStatesSet) {
missingSameGuardSuccs.addAll(reprSuccToSameGuardSuccs.get(repr));
}
allSuccStatesSet.addAll(missingSameGuardSuccs);
//Add successor states with TRUE (tautology) guards (see Optimization 2 above)
allSuccStatesSet.addAll(tautologySuccs);
if (!stateSubsetsToDeterministicStatesMapping.containsKey(allSuccStatesSet)) {
/*
* If some state in successorStatesSet is an accepting SFA state, then the
* corresponding new DFSA state should be an accepting state (as indicated by
* 'newDeterministicStateIsAccepting').
*/
newDeterministicStateIsAccepting = SFAUtil.containsAcceptingState(allSuccStatesSet);
detSuccessorState = this.newSfaState(newDeterministicStateIsAccepting);
stateSubsetsToDeterministicStatesMapping.put(allSuccStatesSet, detSuccessorState);
workStack.add(0, allSuccStatesSet);
} else {
detSuccessorState = stateSubsetsToDeterministicStatesMapping.get(allSuccStatesSet);
}
detCurrentState.addTrans(transitionsGuardsConjunction, detSuccessorState);
} else {
transitionsGuardsConjunction.free();
}
}
}
SFAUtil.freeTransitionsSet(allTransitionsSet);
}
copySfa.free();
return deterministicAutomaton;
}
@Override
public void completeTransitionFunction() {
// Create a black hole, sink state, from where we are stuck forever.
T sinkState = this.newSfaState(false);
sinkState.addTrans(Env.TRUE(), sinkState);
Queue<T> worklist = new LinkedList<>();
List<T> seen = new ArrayList<>();
worklist.add(ini);
seen.add(ini);
while (!worklist.isEmpty()) {
T s = worklist.remove();
// add successors not checked yet and complete the transition function
BDD blackHoleTransGuard = Env.TRUE();
for (Map.Entry<T, BDD> transition : s.getSucc().entrySet()) {
if (!seen.contains(transition.getKey())) {
worklist.add(transition.getKey());
seen.add(transition.getKey());
}
blackHoleTransGuard.andWith(transition.getValue().not());
}
// if there is an undefined transition for some assignment
if (!blackHoleTransGuard.isZero()) {
s.addTrans(blackHoleTransGuard, sinkState);
} else {
blackHoleTransGuard.free();
}
}
}
@Override
public BaseSFA<T> minimize() {
if (this.isEmptyLanguage()) {
T initialState = this.newSfaState(false);
initialState.addTrans(Env.TRUE(), initialState);
return this.newSfaInstance(initialState);
}
BaseSFA<T> deterministicAutomaton = this.determinize();
deterministicAutomaton.completeTransitionFunction();
// Moore’s minimization algorithm (a.k.a. the standard algorithm) lifted to SFAs
// find all reachable states
List<T> reachableStates = deterministicAutomaton.reachableStates();
// remember each seen state's index in the seen list
Map<T, Integer> seenStatesIndices = new HashMap<>();
for (int i = 0; i < reachableStates.size(); ++i) {
seenStatesIndices.put(reachableStates.get(i), i);
}
// initialize the equivalence relation E
Set<Pair<T, T>> e = new HashSet<>();
for (int i = 0; i < reachableStates.size(); ++i) {
for (int j = 0; j < i; ++j) {
T p = reachableStates.get(i);
T q = reachableStates.get(j);
if ((p.isAccepting() && q.isAccepting()) || (!p.isAccepting() && !q.isAccepting())) {
e.add(new Pair<T, T>(p, q));
}
}
}
// refine E
Set<Pair<T, T>> pairsToDelete = new HashSet<>();
while (true) {
for (Pair<T, T> pair : e) {
T p = pair.getLeft();
T q = pair.getRight();
for (Map.Entry<T, BDD> pTransition : p.getSucc().entrySet()) {
for (Map.Entry<T, BDD> qTransition : q.getSucc().entrySet()) {
T p1 = pTransition.getKey();
T q1 = qTransition.getKey();
if (!p1.equals(q1) && !e.contains(new Pair<T, T>(p1, q1))
&& !e.contains(new Pair<T, T>(q1, p1))) {
BDD pTransitionBdd = pTransition.getValue();
BDD qTransitionBdd = qTransition.getValue();
BDD conjunctionBdd = pTransitionBdd.and(qTransitionBdd);
if(!conjunctionBdd.isZero()) {
pairsToDelete.add(pair);
}
conjunctionBdd.free();
}
}
}
}
if (pairsToDelete.isEmpty()) {
// reached a fixed point!
break;
}
e.removeAll(pairsToDelete);
pairsToDelete.clear();
}
// compute E-equivalence classes using a union find data structure
QuickUnionPathCompressionUF unionFindDataStructure = new QuickUnionPathCompressionUF(reachableStates.size());
for (Pair<T, T> pair : e) {
unionFindDataStructure.union(seenStatesIndices.get(pair.getLeft()), seenStatesIndices.get(pair.getRight()));
}
// build the minimal automaton
Map<T, T> eClassReprStateToMinimalSfaStateMap = new HashMap<>();
T initialStateRepresentative = reachableStates
.get(unionFindDataStructure.find(seenStatesIndices.get(deterministicAutomaton.ini)));
eClassReprStateToMinimalSfaStateMap.put(initialStateRepresentative,
initialStateRepresentative.cloneWithoutSucc());
Queue<T> worklist = new LinkedList<>();
worklist.add(initialStateRepresentative);
while (!worklist.isEmpty()) {
T s = worklist.remove();
// add successors not checked yet
for (Map.Entry<T, BDD> transition : s.getSucc().entrySet()) {
T succStateRepresentative = reachableStates
.get(unionFindDataStructure.find(seenStatesIndices.get(transition.getKey())));
if (!eClassReprStateToMinimalSfaStateMap.containsKey(succStateRepresentative)) {
eClassReprStateToMinimalSfaStateMap.put(succStateRepresentative,
succStateRepresentative.cloneWithoutSucc());
worklist.add(succStateRepresentative);
}
eClassReprStateToMinimalSfaStateMap.get(s).addTrans(transition.getValue().id(),
eClassReprStateToMinimalSfaStateMap.get(succStateRepresentative));
}
}
BaseSFA<T> minimalAutomaton = this.newSfaInstance();
minimalAutomaton.setIni(eClassReprStateToMinimalSfaStateMap.get(initialStateRepresentative));
minimalAutomaton.removeDeadStates();
return minimalAutomaton;
}
@Override
public List<T> reachableStates() {
Queue<T> worklist = new LinkedList<>();
List<T> seen = new ArrayList<>();
worklist.add(ini);
seen.add(ini);
while (!worklist.isEmpty()) {
T s = worklist.remove();
// add successors not checked yet
for (T nextState : s.getSuccessors()) {
if (!seen.contains(nextState)) {
worklist.add(nextState);
seen.add(nextState);
}
}
}
return seen;
}
@Override
public int numStates() {
return reachableStates().size();
}
/**
* Computes this Automaton's complement, by determinizing it and flipping its
* states' acceptance.
*
* NOTE: IN ORDER FOR THIS ALGORITHM TO WORK, WE MUST MAKE SURE THAT THE
* TRANSITION FUNCTION IS COMPLETE, AND THAT WE ACHIVE WITH THE
* completeTransitionFunction() METHOD!
*/
@Override
public BaseSFA<T> complement() {
BaseSFA<T> deterministicAutomaton = this.determinize();
deterministicAutomaton.completeTransitionFunction();
Queue<T> worklist = new LinkedList<>();
List<T> seen = new ArrayList<>();
worklist.add(deterministicAutomaton.ini);
seen.add(deterministicAutomaton.ini);
while (!worklist.isEmpty()) {
T s = worklist.remove();
// Flip each accepting (final) state to a non-accepting one, and vice-versa
s.flipAcceptance();
// Add successors not checked yet
for (T nextState : s.getSuccessors()) {
if (!seen.contains(nextState)) {
worklist.add(nextState);
seen.add(nextState);
}
}
}
return deterministicAutomaton;
}
@Override
public void removeDeadStates() {
// search for all final states, while building the reversed automaton
Set<T> finalStates = new HashSet<>();
Map<T, T> originalToReversedStatesMapping = new HashMap<>();
Queue<T> worklist = new LinkedList<>();
worklist.add(ini);
originalToReversedStatesMapping.put(ini, ini.cloneWithoutSucc());
BDD dummyGuard = Env.TRUE();
while (!worklist.isEmpty()) {
T s = worklist.remove();
if (s.isAccepting()) {
finalStates.add(s);
}
// add successors not checked yet
for (T nextState : s.getSuccessors()) {
if (!originalToReversedStatesMapping.containsKey(nextState)) {
worklist.add(nextState);
originalToReversedStatesMapping.put(nextState, nextState.cloneWithoutSucc());
}
// build reversed edges in the reversed automaton
// the transitions' guards don't really matter so we add the SAME dummy TRUE
// guard for all transitions (to save memory and avoid memory leaks in the BDD
// engine)
// originalToReversedStatesMapping.get(nextState).addTrans(Env.TRUE(),
// originalToReversedStatesMapping.get(s));
originalToReversedStatesMapping.get(nextState).getSucc().put(originalToReversedStatesMapping.get(s),
dummyGuard);
}
}
// search for reachable states from the final states in the reversed automaton
List<T> seen = new ArrayList<>();
Set<T> reachableFromFinalStatesInReversed = new HashSet<>();
for (T finalState : finalStates) {
worklist.clear();
worklist.add(originalToReversedStatesMapping.get(finalState));
seen.clear();
seen.add(originalToReversedStatesMapping.get(finalState));
while (!worklist.isEmpty()) {
T sRev = worklist.remove();
// add successors not checked yet
for (T nextStateRev : sRev.getSuccessors()) {
if (!seen.contains(nextStateRev)) {
worklist.add(nextStateRev);
seen.add(nextStateRev);
}
}
}
reachableFromFinalStatesInReversed.addAll(seen);
}
// free the dummy guard
dummyGuard.free();
// delete all states in the original automaton which are reachable from the
// initial state but from which no accepting state can be reached
worklist.clear();
seen.clear();
worklist.add(ini);
seen.add(ini);
while (!worklist.isEmpty()) {
T s = worklist.remove();
// mark all transitions to dead states
Set<T> nextSatesToRemove = new HashSet<>();
for (T nextState : s.getSuccessors()) {
if (!reachableFromFinalStatesInReversed.contains(originalToReversedStatesMapping.get(nextState))) {
nextSatesToRemove.add(nextState);
}
}
// delete all dead transitions
for (T nextState : nextSatesToRemove) {
s.removeTrans(nextState);
}
// add successors not checked yet
for (T nextState : s.getSuccessors()) {
if (!seen.contains(nextState)) {
worklist.add(nextState);
seen.add(nextState);
}
}
}
}
@Override
public boolean isEmptyLanguage() {
if (ini.isAccepting()) {
return false;
}
Queue<T> worklist = new LinkedList<>();
List<T> seen = new ArrayList<>();
worklist.add(ini);
seen.add(ini);
while (!worklist.isEmpty()) {
T s = worklist.remove();
for (T succ : s.getSuccessors()) {
if (succ.isAccepting()) {
return false;
}
// add the current successor if it has not been searched yet
if (!seen.contains(succ)) {
worklist.add(succ);
seen.add(succ);
}
}
}
return true;
}
@Override
public boolean isSubsetOf(SFA other) {
SFA notOtherSfa = other.complement();
SFA thisAndNotOtherSfa = SFAs.productSfa(this, notOtherSfa);
boolean isSubset = thisAndNotOtherSfa.isEmptyLanguage();
//Free BDDs
notOtherSfa.free();
thisAndNotOtherSfa.free();
return isSubset;
}
@Override
public boolean isEquivalent(SFA other) {
return this.isSubsetOf(other) && other.isSubsetOf(this);
}
@Override
public boolean isTrueStarLanguage() {
SFA trueStarSfa = SFAs.trueStarSimpleSfa();
boolean thisIsTrueStar = trueStarSfa.isSubsetOf(this);
trueStarSfa.free();
return thisIsTrueStar;
}
@Override
public boolean acceptsTheEmptyString() {
return this.ini.isAccepting();
}
/*
* Creates a string representation of this SFA in the DOT language.
*/
// @Override
// public String toString() {
// if(ini == null) {return super.toString(); }
//
// Graph.Builder builder = new Graph.Builder().attr(DotAttributes::_setType, GraphType.DIGRAPH).attr(DotAttributes::setRankdir, "LR");
//
// Queue<T> worklist = new LinkedList<>();
// List<T> seen = new ArrayList<>();
// worklist.add(ini);
// seen.add(ini);
// addDotNode(builder, ini, 0);
//
// while (!worklist.isEmpty()) {
// T s = worklist.remove();
//
// // add successors not checked yet
// for (Map.Entry<T, BDD> transition : s.getSucc().entrySet()) {
// if (!seen.contains(transition.getKey())) {
// worklist.add(transition.getKey());
// seen.add(transition.getKey());
// addDotNode(builder, transition.getKey(), seen.size()-1);
// }
// builder.edge(s, transition.getKey()).attr(DotAttributes::setLabel, Env.toNiceString(transition.getValue()));
// }
//
// if(s.hasEpsSuccessors()) {
// for(T epsSucc : s.getEpsSucc()) {
// if (!seen.contains(epsSucc)) {
// worklist.add(epsSucc);
// seen.add(epsSucc);
// addDotNode(builder, epsSucc, seen.size()-1);
// }
// builder.edge(s, epsSucc).attr(DotAttributes::setLabel, BaseSFA.EPS_LABEL);
// }
// }
// }
// return new DotExport().exportDot(builder.build());
// }
/*
*
*
*
*
*
*
*
**************************************************************
* Private methods*********************************************
**************************************************************
*
*
*
*
*
*
*
*
*/
// private void addDotNode(Graph.Builder builder, T sfaState, int stateIdx) {
// if(sfaState.isAccepting()) {
// builder.node(sfaState).attr(DotAttributes::_setName, "s" + stateIdx).attr(DotAttributes::setLabel, "s" + stateIdx).attr(DotAttributes::setShape, "doublecircle");
// }
// else {
// builder.node(sfaState).attr(DotAttributes::_setName, "s" + stateIdx).attr(DotAttributes::setLabel, "s" + stateIdx).attr(DotAttributes::setShape, "circle");
// }
// if(sfaState == ini) {
// T dummyState = this.newSfaState(false);
// builder.node(dummyState).attr(DotAttributes::_setName, "start").attr(DotAttributes::setShape, "point");
// builder.edge(dummyState, sfaState);
// }
// }
/**
* Checks whether the given collection of BDDs has no overlap between any two.
*
* @param values
* @return
*/
private boolean hasOverlap(Collection<BDD> values) {
BDD seen = Env.FALSE(), inter;
for (BDD b : values) {
inter = b.and(seen);
if (!inter.isZero()) {
inter.free();
seen.free();
return true;
}
inter.free();
seen.orWith(b.id());
}
seen.free();
return false;
}
/*
*
*
*
*
* ***********************************
* Private nested classes
* **********************************
*
*
*
*
*
*
*
*
*
*/
/**
* CODE COPIED FROM:
* https://algs4.cs.princeton.edu/15uf/QuickUnionPathCompressionUF.java.html
*
* The {@code QuickUnionPathCompressionUF} class represents a union find data
* structure. It supports the <em>union</em> and <em>find</em> operations, along
* with methods for determining whether two sites are in the same component and
* the total number of components.
* <p>
* This implementation uses quick union (no weighting) with full path
* compression. Initializing a data structure with <em>n</em> sites takes linear
* time. Afterwards, <em>union</em>, <em>find</em>, and <em>connected</em> take
* logarithmic amortized time <em>count</em> takes constant time.
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/15uf">Section 1.5</a> of
* <i>Algorithms, 4th Edition</i> by <NAME> and <NAME>.
*
* @author <NAME>
* @author <NAME>
*/
@SuppressWarnings("unused")
static private class QuickUnionPathCompressionUF {
private int[] id; // id[i] = parent of i
private int count; // number of components
/**
* Initializes an empty union�find data structure with n isolated components 0
* through n-1.
*
* @param n
* the number of sites
* @throws java.lang.IllegalArgumentException
* if n < 0
*/
QuickUnionPathCompressionUF(int n) {
count = n;
id = new int[n];
for (int i = 0; i < n; i++) {
id[i] = i;
}
}
/**
* Returns the number of components.
*
* @return the number of components (between {@code 1} and {@code n})
*/
int count() {
return count;
}
/**
* Returns the component identifier for the component containing site {@code p}.
*
* @param p
* the integer representing one object
* @return the component identifier for the component containing site {@code p}
* @throws IllegalArgumentException
* unless {@code 0 <= p < n}
*/
int find(int p) {
int root = p;
while (root != id[root])
root = id[root];
while (p != root) {
int newp = id[p];
id[p] = root;
p = newp;
}
return root;
}
/**
* Returns true if the the two sites are in the same component.
*
* @param p
* the integer representing one site
* @param q
* the integer representing the other site
* @return {@code true} if the two sites {@code p} and {@code q} are in the same
* component; {@code false} otherwise
* @throws IllegalArgumentException
* unless both {@code 0 <= p < n} and {@code 0 <= q < n}
*/
boolean connected(int p, int q) {
return find(p) == find(q);
}
/**
* Merges the component containing site {@code p} with the the component
* containing site {@code q}.
*
* @param p
* the integer representing one site
* @param q
* the integer representing the other site
* @throws IllegalArgumentException
* unless both {@code 0 <= p < n} and {@code 0 <= q < n}
*/
void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ)
return;
id[rootP] = rootQ;
count--;
}
}
/*
*
*
*
*
*
*
*
*
*
*
*
* Deprecated code for documentation and validation
*
*
*
*
*
*
*
*
*
*/
// /**
// * Returns a string representation of the automaton, which describes its states
// * and transitions.
// */
// @Override
// public String toString() {
// Queue<T> worklist = new LinkedList<>();
// List<T> seen = new ArrayList<>();
// worklist.add(ini);
// seen.add(ini);
// int numTransitions = 0;
// List<String> acceptingTransitionsList = new ArrayList<>();
// StringBuilder transitionsStr = new StringBuilder();
// while (!worklist.isEmpty()) {
// T s = worklist.remove();
// if (s.isAccepting()) {
// acceptingTransitionsList.add("s" + seen.indexOf(s));
// }
//
// // add successors not checked yet
// for (Map.Entry<T, BDD> transition : s.getSucc().entrySet()) {
// if (!seen.contains(transition.getKey())) {
// worklist.add(transition.getKey());
// seen.add(transition.getKey());
// }
//
// transitionsStr.append("s" + seen.indexOf(s) + " -> s" + seen.indexOf(transition.getKey()) + " : "
// + transition.getValue().toString() + System.lineSeparator());
// ++numTransitions;
// }
// }
//
// StringBuilder prefix = new StringBuilder();
// prefix.append("Number of states: " + seen.size() + System.lineSeparator());
// prefix.append("Number of accepting states: " + acceptingTransitionsList.size() + System.lineSeparator());
// prefix.append("Accepting states:" + System.lineSeparator() + acceptingTransitionsList + System.lineSeparator());
// prefix.append("Number of transitions: " + numTransitions + System.lineSeparator());
// prefix.append("Transitions description:" + System.lineSeparator());
//
// return prefix.append(transitionsStr).toString();
// }
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinput.triggers;
import java.util.List;
import dk.brics.automaton.Automaton;
import tau.smlab.syntech.gameinput.spec.SpecRegExp;
/** The trigger class
* @param traceId
* @param init - The trigger's init regular expression
* @param effect - The trigger's effect regular expression
* @param initAutomaton - A bricks automaton that matches the regular expression: init
* @param effectAutomaton - A bricks automaton that matches the regular expression: effect
* @param symbols - a list of all variables that appear in the automatons, init and effect
* @param isBoolean - specifies which variables in 'symbols' are boolean
* @param from - specifies for each variable the minimal value of its range.
* <br> For a variable var, this value is stored in from.symbols.getindexof(var).
* @param to - specifies for each variable the maximal value of its range.
* <br> For a variable var, this value is stored in to.symbols.getindexof(var).<p>
* Hence, if var is stored at index 'i' in the list symbols, var get values in the range from[i]...to[i].
*/
@Deprecated
public class DeprecatedTrigger {
private SpecRegExp init;
private Automaton initAutomaton;
private SpecRegExp effect;
// private Map<Spec, SpecSymbols> specSymbolsMap;
private Automaton effectAutomaton;
private int traceId;
private List<String> symbols;
private List<Boolean> isBoolean;
private List<Integer> from;
private List<Integer> to;
// private String initString;
// private String effectString;
// private Map<VarDecl, String> varSymbolMap;
// public Trigger(SpecRegExp init, SpecRegExp effect, int traceId) {
// this.init = init;
// this.effect = effect;
// this.traceId = traceId;
// }
// A constructor. Receives the init and effect regular expressions as SpecRegExps,
// and a list that includes all (names of the) boolean variables that appear in the regular expressions
public DeprecatedTrigger(SpecRegExp init, SpecRegExp effect, List<String> symbols, List<Boolean> isBoolean,
List<Integer> from , List<Integer> to, int traceId ) {
this.init = init;
this.effect = effect;
this.symbols = symbols;
this.isBoolean = isBoolean;
this.from = from;
this.to = to;
this.traceId = traceId;
}
// to create the trigger with Strings that match brics regular expressions
// public Trigger(String init, String effect, Map<VarDecl, String> varSymolMap, int traceId) {
// this.initString = init;
// this.effectString = effect;
// this.traceId = traceId;
// this.varSymbolMap = varSymolMap;
// }
/**
* @param traceId
* @param init
* @param effect
*/
// public Trigger(SpecWrapper init, SpecWrapper effect, int traceId) {
// this.init = init.getRegExp();
// this.effect = effect.getRegExp();
// this.traceId = traceId;
// }
// public Map<Spec, SpecSymbols> getSpecSymbolsMap() {
// return specSymbolsMap;
// }
public void setTraceId(int traceId) {
this.traceId = traceId;
}
// public void setSpecSymbolsMap(Map<Spec, SpecSymbols> specSymbolsMap) {
// this.specSymbolsMap = specSymbolsMap;
// }
public SpecRegExp getInitiator() {
return this.init;
}
public Automaton getInitAutomaton() {
return initAutomaton;
}
public void setInitAutomaton(Automaton initAutomaton) {
this.initAutomaton = initAutomaton;
}
public Automaton getEffectAutomaton() {
return effectAutomaton;
}
public void setEffectAutomaton(Automaton effectAutomaton) {
this.effectAutomaton = effectAutomaton;
}
public SpecRegExp getEffect() {
return this.effect;
}
public int getTraceId() {
return this.traceId;
}
public boolean hasInitEffectAutomatons() {
return this.effectAutomaton != null &&
this.initAutomaton != null;
}
public List<String> getSymbols() {
return this.symbols;
}
public List<Boolean> getBooleans() {
return this.isBoolean;
}
public List<Integer> getFrom() {
return this.from;
}
public List<Integer> getTo() {
return this.to;
}
}<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.jits;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;
public class JitContext {
private BDD envIni;
private BDD envTrans;
private BDD sysIni;
private BDD sysTrans;
private BDD[][] mY;
private BDD[][][] mX;
private BDD[][] mYunprimed;
private BDD[][][] mXunprimed;
// The transition BDD to be used during the execution
private BDD trans;
private BDD ini;
public JitContext(BDD envIni, BDD envTrans, BDD sysIni, BDD sysTrans) {
super();
this.envIni = envIni;
this.envTrans = envTrans;
this.sysIni = sysIni;
this.sysTrans = sysTrans;
}
public BDD getEnvIni() {
return envIni;
}
public BDD getEnvTrans() {
return envTrans;
}
public BDD getSysIni() {
return sysIni;
}
public BDD getSysTrans() {
return sysTrans;
}
public BDD getTrans() {
return trans;
}
public void setTrans(BDD trans) {
this.trans = trans;
}
public BDD getIni() {
return ini;
}
public void setIni(BDD ini) {
this.ini = ini;
}
public void free() {
Env.free(mY);
Env.free(mX);
Env.free(mYunprimed);
Env.free(mXunprimed);
this.envIni.free();
this.envTrans.free();
this.sysIni.free();
this.sysTrans.free();
if (this.ini != null) {
this.ini.free();
}
if (this.trans != null) {
this.trans.free();
}
}
public int rank(int j) {
return mY[j].length;
}
public BDD Y(int j, int r) {
if (r == -1) {
return Env.FALSE();
}
return mY[j][r];
}
public BDD Yunprimed(int j, int r) {
if (r == -1) {
return Env.FALSE();
}
return mYunprimed[j][r];
}
public BDD X(int j, int i, int r) {
return mX[j][i][r];
}
public BDD Xunprimed(int j, int i, int r) {
return mXunprimed[j][i][r];
}
public void setMX(BDD[][][] mX) {
this.mX = mX;
}
public void setMY(BDD[][] mY) {
this.mY = mY;
}
public void setMXunprimed(BDD[][][] mX) {
this.mXunprimed = mX;
}
public void setMYunprimed(BDD[][] mY) {
this.mYunprimed = mY;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.sf.javabdd;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Stack;
import tau.smlab.syntech.jtlv.Env;
/**
* <p>
* Binary Decision Diagrams (BDDs) {@code Interface}
* </p>
* .
**/
public interface BDD {
/**
* <p>
* Returns the factory that created this BDD.
* </p>
*
* @return factory that created this BDD
*/
public BDDFactory getFactory();
/**
* <p>
* Returns true if this BDD is the zero (false) BDD.
* </p>
*
* @return true if this BDD is the zero (false) BDD
*/
public boolean isZero();
/**
* <p>
* Returns true if this BDD is the one (true) BDD.
* </p>
*
* @return true if this BDD is the one (true) BDD
*/
public boolean isOne();
/**
* <p>
* Returns true if this BDD is the universe BDD. The universal BDD differs from the one BDD in ZDD mode.
* </p>
*
* @return true if this BDD is the universe BDD
*/
public boolean isUniverse();
/**
* <p>
* Converts this BDD to a new BDDVarSet.
* </p>
*
* <p>
* This BDD must be a boolean function that represents the all-true minterm of the BDD variables of interest.
* </p>
*
* @return the contents of this BDD as a new BDDVarSet
*/
public BDDVarSet toVarSet();
/**
* <p>
* Gets the variable labeling the BDD.
* </p>
*
* <p>
* Compare to bdd_var.
* </p>
*
* @return the index of the variable labeling the BDD
*/
public abstract int var();
/**
* <p>
* Returns true if this BDD is an ADD
* </p>
*
* @return true if this BDD is an ADD
*/
public boolean isADD();
/**
* <p>
* Gets the level of this BDD.
* </p>
*
* <p>
* Compare to LEVEL() macro.
* </p>
*
* @return the level of this BDD
*/
public int level();
/**
* <p>
* Gets the true branch of this BDD. If this DD is a constant, then null is returned.
* </p>
*
* <p>
* Compare to bdd_high.
* </p>
*
* @return null if this is a constant DD; Otherwise,true branch of this BDD
*/
public abstract BDD high();
/**
* <p>
* Gets the false branch of this BDD. If this DD is a constant, then null is returned.
* </p>
*
* <p>
* Compare to bdd_low.
* </p>
*
* @return null if this is a constant DD; Otherwise, false branch of this BDD
*/
public abstract BDD low();
/**
* <p>
* Identity function. Returns a copy of this BDD. Use as the argument to the "xxxWith" style operators when you do not
* want to have the argument consumed.
* </p>
*
* <p>
* Compare to bdd_addref.
* </p>
*
* @return copy of this BDD
*/
public abstract BDD id();
/**
* <p>
* Negates this BDD by exchanging all references to the zero-terminal with references to the one-terminal and
* vice-versa.
* </p>
*
* <p>
* Compare to bdd_not.
* </p>
*
* @return the negated BDD
*/
public abstract BDD not();
/**
* like not() but adds domain restrictions afterwards
* @return
*/
public abstract BDD notWithDoms();
/**
* <p>
* Returns the logical 'and' of two BDDs. This is a shortcut for calling "apply" with the "and" operator.
* </p>
*
* <p>
* Compare to bdd_and.
* </p>
*
* @param that
* BDD to 'and' with
* @return the logical 'and' of two BDDs
*/
public BDD and(BDD that);
/**
* <p>
* Makes this BDD be the logical 'and' of two BDDs. The "that" BDD is consumed, and can no longer be used. This is a
* shortcut for calling "applyWith" with the "and" operator.
* </p>
*
* <p>
* Compare to bdd_and and bdd_delref.
* </p>
*
* @param that
* the BDD to 'and' with
*/
public BDD andWith(BDD that);
/**
* <p>
* Returns the logical 'or' of two BDDs. This is a shortcut for calling "apply" with the "or" operator.
* </p>
*
* <p>
* Compare to bdd_or.
* </p>
*
* @param that
* the BDD to 'or' with
* @return the logical 'or' of two BDDs
*/
public BDD or(BDD that);
/**
* <p>
* Makes this BDD be the logical 'or' of two BDDs. The "that" BDD is consumed, and can no longer be used. This is a
* shortcut for calling "applyWith" with the "or" operator.
* </p>
*
* <p>
* Compare to bdd_or and bdd_delref.
* </p>
*
* @param that
* the BDD to 'or' with
*/
public BDD orWith(BDD that);
/**
* <p>
* Returns the logical 'xor' of two BDDs. This is a shortcut for calling "apply" with the "xor" operator.
* </p>
*
* <p>
* Compare to bdd_xor.
* </p>
*
* @param that
* the BDD to 'xor' with
* @return the logical 'xor' of two BDDs
*/
public BDD xor(BDD that);
/**
* <p>
* Makes this BDD be the logical 'xor' of two BDDs. The "that" BDD is consumed, and can no longer be used. This is a
* shortcut for calling "applyWith" with the "xor" operator.
* </p>
*
* <p>
* Compare to bdd_xor and bdd_delref.
* </p>
*
* @param that
* the BDD to 'xor' with
*/
public BDD xorWith(BDD that);
/**
* <p>
* Returns the logical 'implication' of two BDDs. This is a shortcut for calling "apply" with the "imp" operator.
* </p>
*
* <p>
* Compare to bdd_imp.
* </p>
*
* @param that
* the BDD to 'implication' with
* @return the logical 'implication' of two BDDs
*/
public BDD imp(BDD that);
/**
* <p>
* Makes this BDD be the logical 'implication' of two BDDs. The "that" BDD is consumed, and can no longer be used.
* This is a shortcut for calling "applyWith" with the "imp" operator.
* </p>
*
* <p>
* Compare to bdd_imp and bdd_delref.
* </p>
*
* @param that
* the BDD to 'implication' with
*/
public BDD impWith(BDD that);
/**
* <p>
* Returns the logical 'bi-implication' of two BDDs. This is a shortcut for calling "apply" with the "biimp" operator.
* </p>
*
* <p>
* Compare to bdd_biimp.
* </p>
*
* @param that
* the BDD to 'bi-implication' with
* @return the logical 'bi-implication' of two BDDs
*/
public BDD biimp(BDD that);
/**
* <p>
* Makes this BDD be the logical 'bi-implication' of two BDDs. The "that" BDD is consumed, and can no longer be used.
* This is a shortcut for calling "applyWith" with the "biimp" operator.
* </p>
*
* <p>
* Compare to bdd_biimp and bdd_delref.
* </p>
*
* @param that
* the BDD to 'bi-implication' with
*/
public BDD biimpWith(BDD that);
/**
* <p>
* if-then-else operator, i.e. computes: (this and then) or (not(this) and else)
* </p>
*
* <p>
* Compare to bdd_ite.
* </p>
*
* @param thenBDD
* the 'then' BDD
* @param elseBDD
* the 'else' BDD
* @return the result of the if-then-else operator on the three BDDs
*/
public BDD ite(BDD thenBDD, BDD elseBDD);
/**
* <p>
* Relational product. Calculates the relational product of the two BDDs as this AND that with the variables in var
* quantified out afterwards. Identical to applyEx(that, and, var).
* </p>
*
* <p>
* Compare to bdd_relprod.
* </p>
*
* @param that
* the BDD to 'and' with
* @param var
* the BDDVarSet to existentially quantify with
* @return the result of the relational product
* @see net.sf.javabdd.BDDDomain#set()
*/
public BDD relprod(BDD that, BDDVarSet var);
/**
* <p>
* Functional composition. Substitutes the variable var with the BDD that in this BDD: result = f[g/var].
* </p>
*
* <p>
* Compare to bdd_compose.
* </p>
*
* @param g
* the function to use to replace
* @param var
* the variable number to replace
* @return the result of the functional composition
*/
public BDD compose(BDD g, int var);
/**
* <p>
* Simultaneous functional composition. Uses the pairs of variables and BDDs in pair to make the simultaneous
* substitution: f [g1/V1, ... gn/Vn]. In this way one or more BDDs may be substituted in one step. The BDDs in pair
* may depend on the variables they are substituting. BDD.compose() may be used instead of BDD.replace() but is not as
* efficient when gi is a single variable, the same applies to BDD.restrict(). Note that simultaneous substitution is
* not necessarily the same as repeated substitution.
* </p>
*
* <p>
* Compare to bdd_veccompose.
* </p>
*
* @param pair
* the pairing of variables to functions
* @return BDD the result of the simultaneous functional composition
*/
public BDD veccompose(BDDPairing pair);
/**
* <p>
* Generalized cofactor. Computes the generalized cofactor of this BDD with respect to the given BDD.
* </p>
*
* <p>
* Compare to bdd_constrain.
* </p>
*
* @param that
* the BDD with which to compute the generalized cofactor
* @return the result of the generalized cofactor
*/
public BDD constrain(BDD that);
/**
* <p>
* Existential quantification of variables. Removes all occurrences of this BDD in variables in the set var by
* existential quantification.
* </p>
*
* <p>
* Compare to bdd_exist.
* </p>
*
* @param var
* BDDVarSet containing the variables to be existentially quantified
* @return the result of the existential quantification
* @see net.sf.javabdd.BDDDomain#set()
*/
public BDD exist(BDDVarSet var);
/**
* <p>
* Universal quantification of variables. Removes all occurrences of this BDD in variables in the set var by universal
* quantification.
* </p>
*
* <p>
* Compare to bdd_forall.
* </p>
*
* @param var
* BDDVarSet containing the variables to be universally quantified
* @return the result of the universal quantification
* @see net.sf.javabdd.BDDDomain#set()
*/
public BDD forAll(BDDVarSet var);
/**
* <p>
* Unique quantification of variables. This type of quantification uses a XOR operator instead of an OR operator as in
* the existential quantification.
* </p>
*
* <p>
* Compare to bdd_unique.
* </p>
*
* @param var
* BDDVarSet containing the variables to be uniquely quantified
* @return the result of the unique quantification
* @see net.sf.javabdd.BDDDomain#set()
*/
public BDD unique(BDDVarSet var);
/**
* <p>
* Restrict a set of variables to constant values. Restricts the variables in this BDD to constant true if they are
* included in their positive form in var, and constant false if they are included in their negative form.
* </p>
*
* <p>
* <i>Note that this is quite different than Coudert and Madre's restrict function.</i>
* </p>
*
* <p>
* Compare to bdd_restrict.
* </p>
*
* @param var
* BDD containing the variables to be restricted
* @return the result of the restrict operation
* @see net.sf.javabdd.BDD#simplify(BDD)
*/
public BDD restrict(BDD var);
/**
* <p>
* Mutates this BDD to restrict a set of variables to constant values. Restricts the variables in this BDD to constant
* true if they are included in their positive form in var, and constant false if they are included in their negative
* form. The "that" BDD is consumed, and can no longer be used.
* </p>
*
* <p>
* <i>Note that this is quite different than Coudert and Madre's restrict function.</i>
* </p>
*
* <p>
* Compare to bdd_restrict and bdd_delref.
* </p>
*
* @param var
* BDD containing the variables to be restricted
* @see net.sf.javabdd.BDDDomain#set()
*/
public BDD restrictWith(BDD var);
/**
* <p>
* Coudert and Madre's restrict function. Tries to simplify the BDD f by restricting it to the domain covered by d. No
* checks are done to see if the result is actually smaller than the input. This can be done by the user with a call
* to nodeCount().
* </p>
*
* <p>
* Compare to bdd_simplify.
* </p>
*
* @param d
* BDDVarSet containing the variables in the domain
* @return the result of the simplify operation
*/
public BDD simplify(BDDVarSet d);
/**
* <p>
* Returns the variable support of this BDD. The support is all the variables that this BDD depends on.
* </p>
*
* <p>
* Compare to bdd_support.
* </p>
*
* @return the variable support of this BDD
*/
public BDDVarSet support();
/**
* <p>
* Returns the result of applying the binary operator <tt>opr</tt> to the two BDDs.
* </p>
* <p>
* Note that some operators might not be valid for every type of decision diagram (BDD, ADD, 0-1 ADD). It is the
* caller's responsibility to check for the binary operator's validity.
* </p>
*
* <p>
* Compare to bdd_apply.
* </p>
*
* @see {@link net.sf.javabdd.BDDFactory.BDDOp}
* @param that
* the BDD to apply the operator on
* @param opr
* the operator to apply
* @return the result of applying the operator
*/
public BDD apply(BDD that, BDDFactory.BDDOp opr);
/**
* <p>
* Makes this BDD be the result of the binary operator <tt>opr</tt> of two BDDs. The "that" BDD is consumed, and can
* no longer be used. Attempting to use the passed in BDD again will result in an exception being thrown.
* </p>
*
* <p>
* Note that some operators might not be valid for every type of decision diagram (BDD, ADD, 0-1 ADD). It is the
* caller's responsibility to check for the binary operator's validity.
* </p>
*
* @see {@link net.sf.javabdd.BDDFactory.BDDOp}
* @param that
* the BDD to apply the operator on
* @param opr
* the operator to apply
*/
public BDD applyWith(BDD that, BDDFactory.BDDOp opr);
/**
* <p>
* Applies the binary operator <tt>opr</tt> to two BDDs and then performs a universal quantification of the variables
* from the variable set <tt>var</tt>.
* </p>
*
* <p>
* Compare to bdd_appall.
* </p>
*
* @param that
* the BDD to apply the operator on
* @param opr
* the operator to apply
* @param var
* BDDVarSet containing the variables to quantify
* @return the result
* @see net.sf.javabdd.BDDDomain#set()
*/
public BDD applyAll(BDD that, BDDFactory.BDDOp opr, BDDVarSet var);
/**
* <p>
* Applies the binary operator <tt>opr</tt> to two BDDs and then performs an existential quantification of the
* variables from the variable set <tt>var</tt>.
* </p>
*
* <p>
* Compare to bdd_appex.
* </p>
*
* @param that
* the BDD to apply the operator on
* @param opr
* the operator to apply
* @param var
* BDDVarSet containing the variables to quantify
* @return the result
* @see net.sf.javabdd.BDDDomain#set()
*/
public BDD applyEx(BDD that, BDDFactory.BDDOp opr, BDDVarSet var);
/**
* <p>
* Applies the binary operator <tt>opr</tt> to two BDDs and then performs a unique quantification of the variables
* from the variable set <tt>var</tt>.
* </p>
*
* <p>
* Compare to bdd_appuni.
* </p>
*
* @param that
* the BDD to apply the operator on
* @param opr
* the operator to apply
* @param var
* BDDVarSet containing the variables to quantify
* @return the result
* @see net.sf.javabdd.BDDDomain#set()
*/
public BDD applyUni(BDD that, BDDFactory.BDDOp opr, BDDVarSet var);
/**
* <p>
* Finds one satisfying variable assignment of this BDD which restricts each variable of the set <tt>var</tt>.
* The only variables mentioned in the result are those of <tt>var</tt>. All other variables would be undefined, i.e., don't
* cares, in the resulting BDD.
* </p>
*
* @param var
* BDDVarSet the set of variables that are mentioned in the result
* @return one satisfying variable assignment
* @see net.sf.javabdd.BDDDomain#set()
*/
public BDD satOne(BDDVarSet var);
/**
* <p>
* Finds all satisfying variable assignments.
* </p>
*
* <p>
* Compare to bdd_allsat.
* </p>
*
* @return all satisfying variable assignments
*/
public AllSatIterator allsat();
/**
* Iterator that returns all satisfying assignments as byte arrays. In the byte arrays, -1 means dont-care, 0 means 0,
* and 1 means 1.
*/
public static class AllSatIterator implements Iterator<byte[]> {
protected final BDDFactory f;
protected BDD original;
protected byte[] allsatProfile;
protected Stack<Integer> choices;
protected LinkedList<Integer> freeVars;
/**
* Constructs a satisfying-assignment iterator on the given BDD. next() will returns a byte array, the byte array
* will be indexed by BDD variable number.
*
* @param r
* BDD to iterate over
*/
public AllSatIterator(BDD r) {
f = r.getFactory();
if (f.isZDD()) {
throw new RuntimeException("Sorry, lost ZDD compatibility.");
}
original = r.id();
if (original.isZero()) {
freeVars = null;
return;
}
allsatProfile = new byte[f.varNum()];
Arrays.fill(allsatProfile, (byte)-1);
choices = new Stack<Integer>();
// find relevant variables (not don't cares)
freeVars = new LinkedList<>();
for (int v : original.support().toArray()) {
freeVars.add(v);
}
Collections.sort(freeVars);
if (!r.isOne()) {
if (!gotoNext()) {
allsatProfile = null;
original.free();
}
}
}
public void free() {
if (!original.isFree()) {
original.free();
}
}
/**
* compute next assignment of allsatProfile
*
* @return true if there is a next assignment false otherwise
*/
private boolean gotoNext() {
if (original.isZero() || original.isOne()) {
return false;
}
BDD next = Env.FALSE();
do {
if (next.isZero() && !choices.isEmpty()) {
// pop all dead-ends
int var = choices.pop();
while (var > 0 && !choices.isEmpty()) {
// remember to later set this variable
freeVars.addFirst(var - 1);
var = choices.pop();
}
if (var > 0 && choices.isEmpty()) {
return false;
}
// now we have a negaive var and can try alternative
var = -var - 1;
choices.push(var + 1);
} else if (!freeVars.isEmpty()){
// add negated var choice
choices.push(-(freeVars.removeFirst() + 1));
}
// prepare next BDD based on choices
next.free();
next = original.id();
for (int i : choices) {
if (i < 0) {
next.andWith(f.nithVar(-i - 1));
} else {
next.andWith(f.ithVar(i - 1));
}
}
} while (!freeVars.isEmpty() || next.isZero());
next.free();
// assign value to every variable
for (int v = 0; v < allsatProfile.length; v++) {
if (choices.contains(v+1)) {
allsatProfile[v] = 1;
} else if (choices.contains(-(v+1))) {
allsatProfile[v] = 0;
} else {
// v is don't care
allsatProfile[v] = -1;
}
}
return true;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return allsatProfile != null;
}
/**
* Return the next satisfying var setting.
*
* @return byte[]
*/
public byte[] nextSat() {
if (allsatProfile == null)
throw new NoSuchElementException();
byte[] b = new byte[allsatProfile.length];
System.arraycopy(allsatProfile, 0, b, 0, b.length);
if (!gotoNext()) {
allsatProfile = null;
original.free();
}
return b;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#next()
*/
public byte[] next() {
return nextSat();
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* <p>
* Finds one satisfying assignment of the domain <tt>d</tt> in this BDD and returns that value.
* </p>
*
* <p>
* Compare to fdd_scanvar.
* </p>
*
* @param d
* domain to scan
* @return one satisfying assignment for that domain
*/
public BigInteger scanVar(BDDDomain d);
/**
* <p>
* Finds one satisfying assignment in this BDD of all the defined BDDDomain's. Each value is stored in an array which
* is returned. The size of this array is exactly the number of BDDDomain's defined.
* </p>
*
* <p>
* Compare to fdd_scanallvar.
* </p>
*
* @return array containing one satisfying assignment of all the defined domains
*/
public BigInteger[] scanAllVar();
/**
* <p>
* Returns an iteration of the satisfying assignments of this BDD. Returns an iteration of minterms. The <tt>var</tt>
* argument is the set of variables that will be mentioned in the result.
* </p>
*
* @param var
* set of variables to mention in result
* @return an iteration of minterms
* @see net.sf.javabdd.BDDDomain#set()
*/
public BDDIterator iterator(final BDDVarSet var);
public static class BDDIterator implements Iterator<BDD> {
final BDDFactory f;
AllSatIterator i;
// Reference to the initial BDD object, used to support the remove() operation.
final BDD initialBDD;
BDD remainder;
/**
* relevant variables numbers
*/
final int[] vars;
/**
* Current bit assignmentof variables in vars.
*/
final boolean[] varVals;
/**
* Latest result from allsat iterator. Here, array indexed by variable number. Can contain don't cares (-1).
*/
byte[] allSatRes;
/**
* Last BDD returned. Used to support the remove() operation.
*/
BDD lastReturned;
/**
* Construct a new BDDIterator on the given BDD. The var argument is the set of variables that will be mentioned in
* the result.
*
* @param bdd
* BDD to iterate over
* @param var
* variable set to mention in result
*/
public BDDIterator(BDD bdd, BDDVarSet var) {
initialBDD = bdd;
remainder = bdd.id();
f = bdd.getFactory();
i = new AllSatIterator(bdd);
vars = var.toArray();
varVals = new boolean[vars.length];
gotoNext();
}
protected void gotoNext() {
if (i.hasNext()) {
// here we need to remove everything we have seen before for the current VarSet (by removing lastReturned)
i.free();
i = new AllSatIterator(remainder);
if (!i.hasNext()) {
allSatRes = null;
return;
}
allSatRes = (byte[]) i.next();
} else {
allSatRes = null;
return;
}
for (int i = 0; i < vars.length; ++i) {
if (allSatRes[vars[i]] == 1) {
varVals[i] = true;
} else {
varVals[i] = false;
}
}
}
protected boolean gotoNextA() {
for (int i = vars.length - 1; i >= 0; --i) {
if (allSatRes[vars[i]] != -1)
continue;
if (varVals[i] == false) {
varVals[i] = true;
return true;
}
varVals[i] = false;
}
return false;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return allSatRes != null;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#next()
*/
public BDD next() {
return nextBDD();
}
/**
* next value in the given domain (encoding of the bools in varVals into a number)
*
* @param dom
* @return null if the domain was not in the varset when the iterator was created
*/
public BigInteger nextValue(BDDDomain dom) {
if (allSatRes == null) {
throw new NoSuchElementException();
}
if (lastReturned != null) {
lastReturned.free();
}
lastReturned = null;
BigInteger val = BigInteger.ZERO;
int[] ivar = dom.vars();
for (int m = dom.varNum() - 1; m >= 0; m--) {
val = val.shiftLeft(1);
int varPos = Arrays.binarySearch(vars, ivar[m]);
if (varPos < 0) {
val = null;
break;
}
if (varVals[varPos]) {
val = val.add(BigInteger.ONE);
}
}
if (!gotoNextA()) {
gotoNext();
}
return val;
}
/**
* Return the next BDD in the iteration.
*
* @return the next BDD in the iteration
*/
public BDD nextBDD() {
if (allSatRes == null) {
throw new NoSuchElementException();
}
if (lastReturned != null) {
lastReturned.free();
}
lastReturned = f.universe();
for (int i = 0; i < varVals.length; i++) {
if (varVals[i] == true) {
lastReturned.andWith(f.ithVar(vars[i]));
} else {
lastReturned.andWith(f.nithVar(vars[i]));
}
}
remainder.andWith(lastReturned.not());
if (!gotoNextA()) {
gotoNext();
}
return lastReturned.id();
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/
public void remove() {
if (lastReturned == null)
throw new IllegalStateException();
initialBDD.applyWith(lastReturned, BDDFactory.diff);
lastReturned = null;
}
/**
* <p>
* Returns true if the given BDD variable number is a dont-care. <tt>var</tt> must be a variable in the iteration
* set.
* </p>
*
* @param var
* variable number to check
* @return if the given variable is a dont-care
*/
public boolean isDontCare(int var) {
if (allSatRes == null) {
return false;
}
return allSatRes[var] == -1;
}
/**
* <p>
* Returns true if the BDD variables in the given BDD domain are all dont-care's.
* <p>
*
* @param d
* domain to check
* @return if the variables are all dont-cares
* @throws BDDException
* if d is not in the iteration set
*/
public boolean isDontCare(BDDDomain d) {
if (allSatRes == null) {
return false;
}
int[] vars = d.vars();
for (int i = 0; i < vars.length; ++i) {
if (!isDontCare(vars[i]))
return false;
}
return true;
}
/**
* Fast-forward the iteration such that the given variable number is true.
*
* @param var
* number of variable
*/
public void fastForward(int var) {
if (allSatRes == null) {
throw new BDDException();
}
int varPos = Arrays.binarySearch(vars, var);
if (varPos < 0 || allSatRes[var] != -1) {
throw new BDDException();
}
varVals[varPos] = true;
}
/**
* Fast-forward the iteration such that the given set of variables are true.
*
* @param vars
* set of variable indices
*/
public void fastForward(int[] vars) {
for (int i = 0; i < vars.length; ++i) {
fastForward(vars[i]);
}
}
/**
* Assuming <tt>d</tt> is a dont-care, skip to the end of the iteration for <tt>d</tt>
*
* @param d
* BDD domain to fast-forward past
*/
public void skipDontCare(BDDDomain d) {
int[] vars = d.vars();
fastForward(vars);
if (!gotoNextA()) {
gotoNext();
}
}
public void free() {
i.free();
if (lastReturned != null) {
lastReturned.free();
}
}
}
/**
* <p>
* Returns a BDD where all variables are replaced with the variables defined by pair. Each entry in pair consists of a
* old and a new variable. Whenever the old variable is found in this BDD then a new node with the new variable is
* inserted instead.
* </p>
*
* <p>
* Compare to bdd_replace.
* </p>
*
* @param pair
* pairing of variables to the BDDs that replace those variables
* @return result of replace
*/
public BDD replace(BDDPairing pair);
/**
* <p>
* Replaces all variables in this BDD with the variables defined by pair. Each entry in pair consists of a old and a
* new variable. Whenever the old variable is found in this BDD then a new node with the new variable is inserted
* instead. Mutates the current BDD.
* </p>
*
* <p>
* Compare to bdd_replace and bdd_delref.
* </p>
*
* @param pair
* pairing of variables to the BDDs that replace those variables
*/
public BDD replaceWith(BDDPairing pair);
/**
* <p>
* Prints the set of truth assignments specified by this BDD.
* </p>
*
* <p>
* Compare to bdd_printset.
* </p>
*/
public void printSet();
/**
* <p>
* Prints this BDD in dot graph notation.
* </p>
*
* <p>
* Compare to bdd_printdot.
* </p>
*/
public void printDot();
/**
* <p>
* Counts the number of distinct nodes used for this BDD.
* </p>
*
* <p>
* Compare to bdd_nodecount.
* </p>
*
* @return the number of distinct nodes used for this BDD
*/
public int nodeCount();
/**
* <p>
* Counts the number of paths leading to the true terminal.
* </p>
*
* <p>
* Compare to bdd_pathcount.
* </p>
*
* @return the number of paths leading to the true terminal
*/
public double pathCount();
/**
* <p>
* Calculates the number of satisfying variable assignments.
* </p>
*
* <p>
* Compare to bdd_satcount.
* </p>
*
* @return the number of satisfying variable assignments
*/
public double satCount();
/**
* <p>
* Calculates the number of satisfying variable assignments to the variables in the given varset. ASSUMES THAT THE BDD
* DOES NOT HAVE ANY ASSIGNMENTS TO VARIABLES THAT ARE NOT IN VARSET. You will need to quantify out the other
* variables first.
* </p>
*
* <p>
* Compare to bdd_satcountset.
* </p>
*
* @return the number of satisfying variable assignments
*/
public double satCount(BDDVarSet varset);
/**
* <p>
* Calculates the logarithm of the number of satisfying variable assignments.
* </p>
*
* <p>
* Compare to bdd_satcount.
* </p>
*
* @return the logarithm of the number of satisfying variable assignments
*/
public double logSatCount();
/**
* <p>
* Calculates the logarithm of the number of satisfying variable assignments to the variables in the given varset.
* </p>
*
* <p>
* Compare to bdd_satcountset.
* </p>
*
* @return the logarithm of the number of satisfying variable assignments
*/
public double logSatCount(BDDVarSet varset);
/**
* <p>
* Counts the number of times each variable occurs in this BDD. The result is stored and returned in an integer array
* where the i'th position stores the number of times the i'th printing variable occurred in the BDD.
* </p>
*
* <p>
* Compare to bdd_varprofile.
* </p>
*/
public abstract int[] varProfile();
/**
* <p>
* Returns true if this BDD equals that BDD, false otherwise.
* </p>
*
* @param that
* the BDD to compare with
* @return true iff the two BDDs are equal
*/
public boolean equals(BDD that);
/**
* <p>
* Returns a string representation of this BDD on the defined domains, using the given BDDToString converter.
* </p>
*
* @see net.sf.javabdd.BDD.BDDToString
*
* @return string representation of this BDD using the given BDDToString converter
*/
public String toStringWithDomains(BDDToString ts);
/**
* <p>
* BDDToString is used to specify the printing behavior of BDDs with domains. Subclass this type and pass it as an
* argument to toStringWithDomains to have the toStringWithDomains function use your domain names and element names,
* instead of just numbers.
* </p>
*/
public static class BDDToString {
/**
* <p>
* Singleton instance that does the default behavior: domains and elements are printed as their numbers.
* </p>
*/
public static final BDDToString INSTANCE = new BDDToString();
/**
* <p>
* Protected constructor.
* </p>
*/
protected BDDToString() {
}
/**
* <p>
* Given a domain index and an element index, return the element's name. Called by the toStringWithDomains()
* function.
* </p>
*
* @param i
* the domain number
* @param j
* the element number
* @return the string representation of that element
*/
public String elementName(int i, BigInteger j) {
return j.toString();
}
/**
* <p>
* Given a domain index and an inclusive range of element indices, return the names of the elements in that range.
* Called by the toStringWithDomains() function.
* </p>
*
* @param i
* the domain number
* @param lo
* the low range of element numbers, inclusive
* @param hi
* the high range of element numbers, inclusive
* @return the string representation of the elements in the range
*/
public String elementNames(int i, BigInteger lo, BigInteger hi) {
return lo.toString() + "-" + hi.toString();
}
}
/**
* <p>
* Converts this BDD into a 0-1 ADD.<br>
* If this is an ADD then it is equivalent to {@link #id() id}.
* </p>
*
* @return the converted 0-1 ADD
*/
public ADD toADD();
/**
* <p>
* Frees this BDD. Further use of this BDD will result in an exception being thrown.
* </p>
*/
public abstract void free();
/**
* Checks whether this BDD has already been freed.
*
* @return true if this BDD is freed
*/
public abstract boolean isFree();
public long rootId();
/**
* <p>Returns a deterministic version of this BDD. It is assumed that this BDD represents a controller or a strategy.<br>
* The controller is deterministic such that for every combination of variable assignments that are not in d, there is at most one assignment of variables in d
* that goes to 1 constant, i.e there is at most one valid choice for the module that controls the variables that appear in d.</p>
*
* @param d BDD containing the variables of the module whose choices should be deterministic
* @return A deterministic version of this controller
*/
public BDD determinizeController(BDDVarSet d);
}<file_sep># Spectra Synthesizer
This repository contains the code of the GR(1) synthesizer, which is based on the Spectra specification language that can be found in `spectra-lang` repository.
## Packaged Version
To download a packaged version of Eclipse with spectra tools installed, go to http://smlab.cs.tau.ac.il/syntech/spectra/index.html.
We provide also an update site to install occasional updates in the following link: `http://smlab.cs.tau.ac.il/syntech/spectra/tools/update/`.
## Installation
The synthesizer and its tools are developed over the Eclipse framework, therefore a working installation of Eclipse IDE for Java and DSL Developers (preferably version above or equals 2022-09) is a prerequisite.
In order to compile Spectra synthesizer from source code:
- As a prerequisite, follow the instructions in the `spectra-lang` repository.
- `git clone` this repository into your computer.
- Import all existing projects from both repositories into an Eclipse workspace. After the clone you should have two folders called `spectra-lang` and `spectra-synt` in your file system, containing many Java projects. `spectra-lang` projects should be already imported into your workspace. Import the projects of this repository by 'Import -> Projects from Folder or Archive', the choosing `spectra-synt` directory, and selecting all the projects from there *except* the spectra-synt folder itself (it is not a real project and it might cause problems if imported together with the other real projects).
- Run an Eclipse instance by creating a new `Eclipse Application` configuration in the `Run Configurations` window.
## Documentation
Information about Spectra language and tools can be found here: http://smlab.cs.tau.ac.il/syntech/.
A comprehensive hands-on tutorial can be found here: https://smlab.cs.tau.ac.il/syntech/tutorial/.
A detailed user guide can be downloaded from here: http://smlab.cs.tau.ac.il/syntech/spectra/userguide202210.pdf.
## Licensing
Spectra project is licensed under BSD-3-Clause. It uses CUDD library, which is also licensed under BSD-3-Clause, and whose modified code can be found in `spectra-cudd` repository. It also uses Brics automaton library, licensed under BSD-2-Clause and available here: https://www.brics.dk/automaton/.
<file_sep>source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
cudd.dll,\
libcudd.so,\
lib/automaton.jar,\
src/
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.rabin;
import java.util.Stack;
import java.util.Vector;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDVarSet;
import net.sf.javabdd.BDD.BDDIterator;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.games.AbstractGamesException;
import tau.smlab.syntech.games.GamesStrategyException;
import tau.smlab.syntech.games.controller.enumerate.ConcreteControllerConstruction;
import tau.smlab.syntech.games.controller.enumerate.EnumStateI;
import tau.smlab.syntech.games.controller.enumerate.EnumStrategyI;
import tau.smlab.syntech.games.controller.enumerate.EnumStrategyImpl;
import tau.smlab.syntech.jtlv.Env;
public class RabinConcreteControllerConstruction extends ConcreteControllerConstruction {
protected RabinMemory mem;
public RabinConcreteControllerConstruction(RabinMemory mem, GameModel m) {
super(mem, m);
this.mem = mem;
}
@Override
public EnumStrategyI calculateConcreteController() throws AbstractGamesException {
return this.calculateConcreteController(false);
}
public EnumStrategyI calculateConcreteController(boolean calcLongestSimplePath) throws AbstractGamesException {
System.out.println("extract strategy - Start");
if (mem.getWin() == null || mem.getWin().isFree()) {
throw new GamesStrategyException("BDD of winning states invalid.");
}
Stack<EnumStateI> st_stack = new Stack<EnumStateI>();
EnumStrategyI aut = new EnumStrategyImpl(calcLongestSimplePath);
BDD sysDeadOrEnvWin = sys.initial().imp(mem.getWin());
BDD allIni = env.initial().id().andWith(sysDeadOrEnvWin.forAll(sys.moduleUnprimeVars()));
sysDeadOrEnvWin.free();
if (allIni.isZero()) {
throw new GamesStrategyException("No environment winning states.");
}
// select one env choice
BDD ini = (BDD) allIni.iterator(env.moduleUnprimeVars()).next();
allIni.free();
// add all system choices
ini.andWith(sys.initial().id());
for (BDDIterator iter = ini.iterator(allUnprime()); iter.hasNext();) {
BDD cand = iter.nextBDD();
int iniZ = mem.getZRank(cand);
int iniK = 0;
int iniX = mem.getXRank(iniZ, iniK, cand);
RabinRankInfo iniR = new RabinRankInfo(iniZ, iniK, iniX);
st_stack.push(aut.getState(cand, iniR));
}
try {
// int state_counter = 0;
while (!st_stack.isEmpty()) {
// System.out.println("num of states is: " + state_counter++);
EnumStateI st = st_stack.pop();
st_stack.addAll(getSysStepsToEnvChoice(aut, st));
}
} catch (AbstractGamesException e) {
System.err.println("failed generating counter strategy");
e.printStackTrace();
}
System.out.println("extract strategy - End");
return aut;
}
// returns a vector of states representation of the next environment step
// from a given state, and the possible set of system responses.
private Vector<EnumStateI> getSysStepsToEnvChoice(EnumStrategyI aut, EnumStateI state)
throws AbstractGamesException {
if (!(state.get_rank_info() instanceof RabinRankInfo))
throw new GamesStrategyException("cannot build rabin automata for" + "streett state");
RabinRankInfo rri = (RabinRankInfo) state.get_rank_info();
// int zRank = rri.get_row_count();
// int kGoal = rri.get_env_goal();
// int kRank = rri.get_env_goal_count();
//
// System.out.println("is state " + state.get_id() + " winning? "
// + !state.get_state().and(player1_winning).isZero() + " env"
// + kGoal + ":" + kRank + " sys rank:" + zRank);
// System.out.println("for state " + state.get_id()
// + " the row ranks is :" + zRank + " the conjunct rank is:"
// + kRank);
//
// ////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////
// The general idea is the first try to move as low as possible in the
// vector of z (the lowest possible zRank). If not possible then trying
// to move as low as possible in the relevant vector of K, and if
// reached the lowest K, moving to the next K. Namely:
// 1) lowering Z. // not a relevant value... can return immediately.
// 2) if reached lowest K moving to the next K.
// 3) try to lower K.
// 4) not found good choice yet.
// int priority = 4;
// ////////////////////////////////////////////////////////////////////
Vector<EnumStateI> ret = null;
BDD envSuccs = env.succ(state.getData());
BDD bestSuccs = Env.FALSE();
int bestKind = 4;
for (BDDIterator iter = envSuccs.iterator(env.moduleUnprimeVars()); iter.hasNext();) {
BDD envSucc = (BDD) iter.next();
BDD sysSuccs = sys.succ(state.getData()).and(envSucc);
BDD succSysWin = sysSuccs.and(mem.getWin().not());
if (!succSysWin.isZero()) {
succSysWin.free();
continue; // not one of the relevant environment choices.
}
succSysWin.free();
int kind = getBestKind(state, rri, sysSuccs);
if (kind == -1)
// not a relevant env choice - one of the sys choices leads to a higher z-rank
continue;
if (kind == 1)
// all sys choices for this env choice lead to a lower z-rank - this env choice
// can force to a lower z-rank
return calcResponses(aut, state, rri, sysSuccs, kind);
if (kind < bestKind) {
bestKind = kind;
bestSuccs = sysSuccs;
}
}
if (bestKind == -1)
throw new GamesStrategyException(
"No environment successor found from" + " state " + state.getData().toString());
ret = calcResponses(aut, state, rri, bestSuccs, bestKind);
if (ret == null)
throw new GamesStrategyException(
"No environment successor found from" + " state " + state.getData().toString());
return ret;
// throw new
// GameException("we have a problem in succs of state "
// + state.get_state().toString() + ". One of the next "
// + "step Z rank is not decreasing");
// throw new GameException("we have a problem in succs of state "
// + state.get_state().toString() + ". One of the next "
// + "step X rank is not decreasing (the Z is identical)");
}
// Kinds:
// 1 - all system choices for this env choice lead to a lower z-rank
// 2 - all system choices for this env choice either lead to a lower z-rank or
// not,
// and at least one sys choice doesn't lead to lower z-rank and we've reached
// the final cell
// (cell 0) in the current x-matrix row.
// 3 - At least one sys choice for this env choice doesn't lead to lower z-rank
// and we're in
// the middle of the current x-matrix row, and this sys choice leads to some
// lower x-cell in this
// row
// -1 - at least one sys choice leads to a higher z-rank
private int getBestKind(EnumStateI state, RabinRankInfo rri, BDD succs) {
int ret_kind = 1;
for (BDDIterator iter = succs.iterator(allUnprime()); iter.hasNext();) {
BDD cand = iter.nextBDD();
int nextZ, nextK, nextX;
nextZ = mem.getZRank(cand);
if (nextZ > rri.get_row_count())
return -1;
if (nextZ < rri.get_row_count())
continue;
if (rri.get_env_goal_count() == 0) {
// TODO - I think this internal if is redundant - add some assert to ensure
// it indeed can't be > 2 and remove this internal if (just set ret_kind = 2)
if (ret_kind <= 2)
ret_kind = 2;
continue;
}
nextK = rri.get_env_goal();
nextX = mem.getXRank(nextZ, nextK, cand);
if (nextX >= rri.get_env_goal_count())
return -1;
ret_kind = 3;
}
return ret_kind;
}
/**
* @param aut
* @param state
* @param rri
* @param succs
* @param kind
* the priority from which this next step is allowed (or below). 1 -
* dec row, 2 - next K, 3 - dec K.
* @param monitoring_expr
* @return The vector of next states, or null if not a valid set of succ.
* @throws GameException
*/
private Vector<EnumStateI> calcResponses(EnumStrategyI aut, EnumStateI state, RabinRankInfo rri, BDD succs,
int kind) throws AbstractGamesException {
Vector<EnumStateI> ret = new Vector<EnumStateI>();
for (BDDIterator iter = succs.iterator(allUnprime()); iter.hasNext();) {
BDD cand = iter.nextBDD();
int nextZ, nextK, nextX;
RabinRankInfo nextR;
nextZ = mem.getZRank(cand);
// if cannot move forward
if (nextZ > rri.get_row_count())
return null;
// else if reducing Z rank
if (nextZ < rri.get_row_count()) {
nextK = 0;
nextX = mem.getXRank(nextZ, nextK, cand);
nextR = new RabinRankInfo(nextZ, nextK, nextX);
EnumStateI newSt = aut.addSuccessorState(state, cand, nextR);
if (newSt != null) // really a new state.
ret.add(newSt);
continue;
}
if (kind <= 1)
return null;
// else nextZRank == rri.get_row_count(), namely, cannot reduce Z,
// and if we reached the K goal (suppose to satisfy the environment
// justice K)
if (rri.get_env_goal_count() == 0) {
nextK = (rri.get_env_goal() + 1) % env.justiceNum();
nextX = mem.getXRank(nextZ, nextK, cand);
nextR = new RabinRankInfo(nextZ, nextK, nextX);
EnumStateI newSt = aut.addSuccessorState(state, cand, nextR);
if (newSt != null) // really a new state.
ret.add(newSt);
continue;
}
if (kind <= 2)
return null;
// else still did not reach the K goal
nextK = rri.get_env_goal();
nextX = mem.getXRank(nextZ, nextK, cand);
if (nextX >= rri.get_env_goal_count())
return null;
nextR = new RabinRankInfo(nextZ, nextK, nextX);
EnumStateI newSt = aut.addSuccessorState(state, cand, nextR);
if (newSt != null) // really a new state.
ret.add(newSt);
continue;
}
return ret;
}
private BDDVarSet allUnprime() {
return sys.moduleUnprimeVars().union(env.moduleUnprimeVars());
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinput.spec;
import java.util.List;
public class InExpSpec implements Spec {
/**
*
*/
private static final long serialVersionUID = -8081328673447088736L;
private Spec variable; // The main var of the expression
private boolean isNot;
private List<String> setOfvalues;
public InExpSpec(Spec variable, boolean isNot, List<String> setOfvalues) {
this.variable = variable;
this.setNot(isNot);
this.setSetOfvalues(setOfvalues);
}
public String toString() {
return this.getVariable().toString() + (this.isNot() ? " not " : " ") + Operator.IN.toString() + " expr : " + this.getSetOfvalues();
}
@Override
public boolean isPastLTLSpec() {
return false;
}
@Override
public boolean isPropSpec() {
return false;
}
@Override
public boolean hasTemporalOperators() {
return false;
}
@Override
public Spec clone() throws CloneNotSupportedException {
return new InExpSpec(this.variable, this.isNot(), this.getSetOfvalues());
}
public Spec getVariable() {
return variable;
}
public void setVariable(Spec variable) {
this.variable = variable;
}
public boolean isNot() {
return isNot;
}
public void setNot(boolean isNot) {
this.isNot = isNot;
}
public List<String> getSetOfvalues() {
return setOfvalues;
}
public void setSetOfvalues(List<String> setOfvalues) {
this.setOfvalues = setOfvalues;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.modelchecker;
import java.util.Vector;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDVarSet;
import tau.smlab.syntech.gamemodel.PlayerModule;
import tau.smlab.syntech.jtlv.CoreUtil;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.lib.FixPoint;
public class FeasibilityChecker {
public void FeasiblityChecker() {}
/**
* <p>
* Eliminate states from scc which have no successors within scc. scc is
* supposed to be a strongly connected component, however, it also contains
* chains of states which exit the scc, but are not in it. This procedure
* eliminates these chains.
* </p>
*
* @param scc
* The set of states to find scc for.
* @return The scc of the given set of states.
*/
private BDD elimSuccChains(PlayerModule module, BDD scc) {
BDD res = scc.id();
for (FixPoint iscc = new FixPoint(true /*freeOnAdvance*/); iscc.advance(res);) {
res = res.and(Env.pred(module.trans(), res));
}
return res;
}
/**
* <p>
* Get the subset of states which has successor to the other given set of
* states.
* </p>
*
* @param module
* The relevant PlayerModule
* @param state
* The first set of states.
* @param to
* The second set of states.
* @return the subset of "state" which has successors to "to".
*/
public BDD hasSuccessorsTo(PlayerModule module, BDD state, BDD to) {
return state.and(Env.prime(to)).and(module.trans()).exist(Env.globalPrimeVars());
}
/**
* <p>
* This is essentially algorithm "FEASIBLE", from the article: <br>
* <NAME>, <NAME>, <NAME>, <NAME>, "Model checking with
* strong fairness".
* </p>
* <p>
* The line numbers are the line numbers of that algorithm. Read the article
* for further details.
* </p>
*
*
* @return Returns a set of states which induce a graph which contains all
* the fair SCS's reachable from an initial state.
*/
public BDD check(PlayerModule module) {
// saving the previous restriction state.
BDD trans = module.trans().id();
// Line 2
BDD res = Env.allSucc(module.initial().id(), module.trans().id());
BDD reachable = res.id();
// Determine whether fairness conditions refer to primed variables.
// If so, they are treated differently.
boolean[] has_primed_j = new boolean[module.justiceNum()];
BDDVarSet primes = Env.globalPrimeVars();
for (int i = 0; i < has_primed_j.length; i++) {
has_primed_j[i] = !module.justiceAt(i).biimp(
module.justiceAt(i).exist(primes)).isUniverse();
}
// Line 3
module.conjunctTrans(res.id());
// Lines 4-11
for (FixPoint ires = new FixPoint(true /*freeOnAdvance*/); ires.advance(res);) {
// Lines 6-7
// Eliminate states from res which have no successors within res.
res = elimSuccChains(module, res);
module.conjunctTrans(res.id());
// Lines 8-9
// Ensure fulfillment of justice requirements.
// Remove from "res" all states which are not R^*-successors
// of some justice state.
for (int i = module.justiceNum() - 1; i >= 0; i--) {
BDD localj = has_primed_j[i] ? hasSuccessorsTo(module, module.justiceAt(i), res) : module.justiceAt(i);
res = Env.allPred(module.trans().id(), res.and(localj));
module.conjunctTrans(res.id());
}
}
module.resetTrans();
module.conjunctTrans(trans.id());
// Line 12
module.conjunctTrans(reachable);
res = Env.allPred(module.trans().id(), res);
module.resetTrans();
module.conjunctTrans(trans.id());
// Line 13
return res;
}
/**
* <p>
* Compute the shortest path from source to destination. <br>
* Algorithm from: <NAME>, <NAME>, <NAME>, <NAME>,
* "Model Checking with Strong Fairness".
* </p>
*
* @param source
* The states to start look for path.
* @param dest
* The states to reach in the path.
* @return An array representing a path, null if the algorithm could not
* find a path.
*/
public BDD[] shortestPath(PlayerModule module, BDD source, BDD dest) {
BDD statesPassed = Env.FALSE(), last = dest.id();
Vector<BDD> blurredPath = new Vector<BDD>();
// blurredPath.add(last);
while (last.and(source).isZero()) { // found source
blurredPath.add(last);
statesPassed = statesPassed.id().or(last);
last = Env.pred(module.trans().id(), last).and(statesPassed.not());
if (last.isZero()) // failed to find a path.
return null;
}
blurredPath.add(last);
BDD[] res = new BDD[blurredPath.size()];
BDD blurredSt = blurredPath.elementAt(blurredPath.size() - 1);
res[0] = CoreUtil.satOne(source.and(blurredSt), module.moduleUnprimeVars());
for (int i = 1; i < res.length; i++) {
blurredSt = blurredPath.elementAt(blurredPath.size() - i - 1);
res[i] = CoreUtil.satOne(Env.succ(res[i - 1], module.trans().id()).and(blurredSt),
module.moduleUnprimeVars());
}
return res;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinput.spec;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import tau.smlab.syntech.gameinput.model.TypeDef;
import tau.smlab.syntech.gameinput.model.Variable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
/**
* A class that represents a regular expression.
*
*
* @author <NAME>
* @author <NAME>
*
*/
public class SpecRegExp implements Spec {
/**
*
*/
private static final long serialVersionUID = 5557869841294255345L;
private static final String FALSE = "false";
private static final String TRUE = "true";
private SpecRegExp left; //the left (resp. only) sub regular expression in case this is a binary (resp. an unary) expression
private SpecRegExp right; //the right sub regular expression in case this is a binary expression
private List<String> values; //if this is a variable or a Boolean constant regular expression, these are the values this expression accepts
private VariableReference varRef; //if this is a variable regular expression, that is the variable reference that appears in this expression
private Spec predicate; //if this is a Boolean term (formula/predicate) regular expression, that is the predicate that appears in the expression
private RegExpKind kind; //the kind (i.e., either the main operator or the base kind) of this regular expression
private RegExpQuantifier quantifier; //if this is a 'REPEAT' unary regular expression, that is its quantifier
public enum RegExpKind {
UNION(true, false), INTERSECTION(true, false), CONCAT(true, false), REPEAT(false, false), COMPLEMENT(false, false), EMPTY_STR(false, true),
VAR(false, true), PREDICATE(false, true), BOOLEAN_CONST(false, true);
private static final List<RegExpKind> NULLARY_KINDS =
Collections.unmodifiableList(Arrays.stream(RegExpKind.values()).filter(RegExpKind::isNullary).collect(Collectors.toList()));
private static final List<RegExpKind> UNARY_KINDS =
Collections.unmodifiableList(Arrays.stream(RegExpKind.values()).filter(RegExpKind::isUnary).collect(Collectors.toList()));
private static final List<RegExpKind> BINARY_KINDS =
Collections.unmodifiableList(Arrays.stream(RegExpKind.values()).filter(RegExpKind::isBinary).collect(Collectors.toList()));
private boolean isNullary; //true if this kind of regular expression is nullary
private boolean isBinary; //true if this kind of regular expression is binary
private RegExpKind(boolean isBinary, boolean isNullary) {
this.isNullary = isNullary;
this.isBinary = isBinary;
}
public boolean isNullary() {
return this.isNullary;
}
public boolean isBinary() {
return this.isBinary;
}
public boolean isUnary() {
return !this.isBinary && !this.isNullary;
}
public static List<RegExpKind> nullaryKinds() {
return NULLARY_KINDS;
}
public static List<RegExpKind> unaryKinds() {
return UNARY_KINDS;
}
public static List<RegExpKind> binaryKinds() {
return BINARY_KINDS;
}
}
/**
*
* An enum class that represents types of regular expressions' quantifier operators.
*
*/
public enum QuantifierType {
ZERO_OR_MORE, ONE_OR_MORE, ZERO_OR_ONE, EXACT_REPETITION,
AT_LEAST, RANGE;
};
/**
* A class that represents regular expressions' quantifier operators.
*
*/
public static class RegExpQuantifier implements Spec {
/**
*
*/
private static final long serialVersionUID = 3852513999102523898L;
private QuantifierType type;
private int least, most;
private RegExpQuantifier(QuantifierType type, int least, int most) {
this.type = type;
this.least = least;
this.most = most;
}
public QuantifierType getType() {
return this.type;
}
public int getLeastRepetitionsNum() {
return this.least;
}
public int getMaxRepetitionsNum() {
return this.most;
}
public void setLeastRepetitionsNum(int least) {
this.least = least;
}
public void setMaxRepetitionsNum(int most) {
this.most = most;
}
/**
*
* @return Kleene star '*' quantifier
*/
public static RegExpQuantifier zeroOrMoreRepetitions() {
return new RegExpQuantifier(QuantifierType.ZERO_OR_MORE, 0, Integer.MAX_VALUE);
}
/**
*
* @return '+' quantifier
*/
public static RegExpQuantifier oneOrMoreRepetitions() {
return new RegExpQuantifier(QuantifierType.ONE_OR_MORE, 1, Integer.MAX_VALUE);
}
/**
*
* @return '?' quantifier
*/
public static RegExpQuantifier zeroOrOneRepetition() {
return new RegExpQuantifier(QuantifierType.ZERO_OR_ONE, 0, 1);
}
/**
*
* @param exactNum the number of occurrences/repetitions
* @return '{{@code exactNum}}' quantifier
*/
public static RegExpQuantifier exactRepetitions(int exactNum) {
return new RegExpQuantifier(QuantifierType.EXACT_REPETITION, exactNum, exactNum);
}
/**
*
* @param atLeastNum the least number of occurrences/repetitions
* @return '{{@code atLeastNum},}' quantifier
*/
public static RegExpQuantifier atLeastRepetitions(int atLeastNum) {
return new RegExpQuantifier(QuantifierType.AT_LEAST, atLeastNum, Integer.MAX_VALUE);
}
/**
*
* @param atLeastNum the least number of occurrences/repetitions
* @param atMostNum the maximal number of occurrences/repetitions (inclusive)
* @return '{{@code atLeastNum},{@code atMostNum}}' quantifier
*/
public static RegExpQuantifier repetitionsInRange(int atLeastNum, int atMostNum) {
return new RegExpQuantifier(QuantifierType.RANGE, atLeastNum, atMostNum);
}
@Override
public String toString() {
switch(this.type) {
case AT_LEAST:
return "{" + this.least + ",}";
case EXACT_REPETITION:
return "{" + this.least + "}";
case ONE_OR_MORE:
return "+";
case RANGE:
return "{" + this.least + "," + this.most + "}";
case ZERO_OR_MORE:
return "*";
case ZERO_OR_ONE:
return "?";
default:
break;
}
return "INVALID QUANTIFIER TYPE";
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
RegExpQuantifier other = (RegExpQuantifier) obj;
if(this.type == null) {
if(other.type != null) {
return false;
}
return true; //both quantifiers are of type null;
}
else {
if(!this.type.equals(other.type)) {
return false;
}
//both quantifiers have the same type
return this.least == other.least &&
this.most == other.most;
}
}
@Override
public boolean isPastLTLSpec() {
return false;
}
@Override
public boolean isPropSpec() {
return false;
}
@Override
public boolean hasTemporalOperators() {
return false;
}
@Override
public RegExpQuantifier clone() throws CloneNotSupportedException {
return new RegExpQuantifier(this.type, this.least, this.most);
}
}
/**
*
* Use a {@link RandomGenerator} to randomly generate
* instances of {@link SpecRegExp}.
*
*
* @author <NAME>
*
*/
public static class RandomGenerator {
private static final boolean GENERATE_PREDICATE_KIND = true;
private static final List<RegExpKind> REGEXP_NULLARY_KINDS = GENERATE_PREDICATE_KIND ? RegExpKind.nullaryKinds() : Arrays.asList(new RegExpKind[] {RegExpKind.EMPTY_STR, RegExpKind.BOOLEAN_CONST, RegExpKind.VAR});
private static final int NULLARY_KIND_NUM = REGEXP_NULLARY_KINDS.size();
private static final List<RegExpKind> REGEXP_KINDS = initRegExpKinds();
private static final int REGEXP_KIND_NUM = REGEXP_KINDS.size();
private static final List<QuantifierType> QUANTIFIER_TYPES = Arrays.asList(QuantifierType.values());
private static final int QUANTIFIER_TYPE_NUM = QUANTIFIER_TYPES.size();
enum SpecKind {INEQ_OP(false), EQ_OP(false), ARITH_OP(false), PROP_OP(false), INT_VAR(true), INT_CONST(true), BOOLEAN_VAR(true), BOOLEAN_CONST(true);
private static Operator[] propOps = {Operator.AND, Operator.OR, Operator.IFF, Operator.IMPLIES, Operator.NOT, Operator.XOR};
private static Operator[] arithOps = {Operator.ADD, Operator.SUBSTRACT, Operator.MULTIPLY};
private static Operator[] arithOpsWithMod = {Operator.ADD, Operator.SUBSTRACT, Operator.MOD, Operator.MULTIPLY};
private static Operator[] ineqOps = Operator.inqOp;
private boolean isNullary;
private SpecKind(boolean isNullary) {
this.isNullary = isNullary;
}
public boolean isNullary() {
return this.isNullary;
}
public static Operator[] getOps(SpecKind opKind) {
return getOps(opKind, false);
}
public static Operator[] getOps(SpecKind opKind, boolean excludeMod) {
if(INEQ_OP.equals(opKind)) {
return ineqOps;
}
if(ARITH_OP.equals(opKind)) {
return excludeMod ? arithOps : arithOpsWithMod;
}
if(PROP_OP.equals(opKind)) {
return propOps;
}
return null;
}
}
private final List<Variable> variables, booleanVariables, intVariables, nonZeroIntVariables, enumVariables;
private final List<SpecKind> propSpecKinds, nullaryPropSpecKinds, arithSpecKinds, nullaryArithSpecKinds;
private final Random random;
private int maxDepth, predMaxDepth, maxLeastRepNum, maxRepRange, maxIntConst;
private static List<RegExpKind> initRegExpKinds() {
List<RegExpKind> regExpKinds = new ArrayList<>();
regExpKinds.addAll(RegExpKind.unaryKinds());
regExpKinds.addAll(RegExpKind.binaryKinds());
regExpKinds.addAll(REGEXP_NULLARY_KINDS);
return regExpKinds;
}
/**
* Returns a new {@link RandomGenerator} that randomly generates
* instances of {@link SpecRegExp}, which may have atomic
* subexpressions that exclusively use the variables in {@code variables}.
*
* @param variables
* @param maxDepth the maximal depth of the generated regular expressions
* @param predMaxDepth the maximal depth of each predicate that appears in the generated regular expression
* @param maxLeastRepNum the maximal value that may appear in repetition quantifiers as the least number of repetitions
* @param maxRepRange the maximal interval size that "repetitions in range" {@link QuantifierType#RANGE} quantifiers may have
*/
public RandomGenerator(int maxDepth, int predMaxDepth, List<Variable> variables,
int maxLeastRepNum, int maxRepRange) {
this.variables = variables;
this.booleanVariables = variables.stream().filter(var -> var.getType().isBoolean()).collect(Collectors.toList());
this.intVariables = variables.stream().filter(var -> var.getType().isInteger()).collect(Collectors.toList());
this.nonZeroIntVariables = variables.stream().filter(var -> (var.getType().isInteger() && var.getType().getLower() > 0)).collect(Collectors.toList());
this.enumVariables = variables.stream().filter(var -> (!var.getType().isInteger() && !var.getType().isBoolean())).collect(Collectors.toList());
this.propSpecKinds = new ArrayList<>();
this.arithSpecKinds = new ArrayList<>();
this.nullaryPropSpecKinds = new ArrayList<>();
this.nullaryArithSpecKinds = new ArrayList<>();
this.fillSpecKindsLists();
this.maxIntConst = getMaxIntConstValue();
this.random = new Random();
this.maxDepth = maxDepth;
this.predMaxDepth = predMaxDepth;
this.maxLeastRepNum = maxLeastRepNum;
this.maxRepRange = maxRepRange;
}
private int getMaxIntConstValue() {
if(this.intVariables.isEmpty()) {return 0;}
int minMaxUpperValue = this.intVariables.get(0).getType().getUpper();
for(int i = 1; i < this.intVariables.size(); i++) {
if(this.intVariables.get(i).getType().getUpper() < minMaxUpperValue) {
minMaxUpperValue = this.intVariables.get(i).getType().getUpper();
}
}
return minMaxUpperValue;
}
private void fillSpecKindsLists() {
this.propSpecKinds.add(SpecKind.BOOLEAN_CONST);
this.nullaryPropSpecKinds.add(SpecKind.BOOLEAN_CONST);
if(!this.enumVariables.isEmpty() || !this.intVariables.isEmpty() || !this.booleanVariables.isEmpty()) {
this.propSpecKinds.add(SpecKind.PROP_OP);
}
if(!this.enumVariables.isEmpty() || !this.intVariables.isEmpty()) {
this.propSpecKinds.add(SpecKind.EQ_OP);
}
if(!this.intVariables.isEmpty()) {
this.propSpecKinds.add(SpecKind.INEQ_OP);
this.arithSpecKinds.add(SpecKind.INT_CONST);
this.nullaryArithSpecKinds.add(SpecKind.INT_CONST);
this.arithSpecKinds.add(SpecKind.INT_VAR);
this.nullaryArithSpecKinds.add(SpecKind.INT_VAR);
this.arithSpecKinds.add(SpecKind.ARITH_OP);
}
if(!this.booleanVariables.isEmpty()) {
this.propSpecKinds.add(SpecKind.BOOLEAN_VAR);
this.nullaryPropSpecKinds.add(SpecKind.BOOLEAN_VAR);
}
}
public SpecRegExp nextSpecRegExp() {
SpecRegExp res = this.genRandRegExp(this.maxDepth);
if(res == null) {
System.out.println("null regexp");
}
return res;
}
public List<Variable> getVariables() {
return variables;
}
public int getMaxDepth() {
return maxDepth;
}
public void setMaxDepth(int maxDepth) {
this.maxDepth = maxDepth;
}
public int getMaxLeastRepNum() {
return maxLeastRepNum;
}
public void setMaxLeastRepNum(int maxLeastRepNum) {
this.maxLeastRepNum = maxLeastRepNum;
}
public int getMaxRepRange() {
return maxRepRange;
}
public void setMaxRepRange(int maxRepRange) {
this.maxRepRange = maxRepRange;
}
private SpecRegExp genRandRegExp(int maxDepth) {
if(maxDepth == 0) {
return genRandNullaryRegExp(REGEXP_NULLARY_KINDS.get(this.random.nextInt(NULLARY_KIND_NUM)));
}
RegExpKind regExpKind = REGEXP_KINDS.get(this.random.nextInt(REGEXP_KIND_NUM));
if(regExpKind.isNullary()) {
return genRandNullaryRegExp(regExpKind);
}
if(regExpKind.isUnary()) {
return genRandUnaryRegExp(maxDepth, regExpKind);
}
if(regExpKind.isBinary()) {
return genRandBinaryRegExp(maxDepth, regExpKind);
}
throw new RuntimeException("The regexp kind " + regExpKind + " is unsupported");
}
private SpecRegExp genRandNullaryRegExp(RegExpKind nullaryKind) {
switch(nullaryKind) {
case EMPTY_STR:
return SpecRegExp.newEmptyStringRegExp();
case BOOLEAN_CONST:
return SpecRegExp.newBooleanConstRegExp(this.random.nextBoolean());
case VAR:
VariableReference varRef = new VariableReference(variables.get(this.random.nextInt(this.variables.size())));
TypeDef variableType = varRef.getVariable().getType();
List<String> values = new ArrayList<>();
int varDomainSize;
if(variableType.isBoolean()) {
varDomainSize = 2;
values.add(String.valueOf(this.random.nextBoolean()));
}
else if(variableType.isInteger()) {
for(int value = variableType.getLower(); value <= variableType.getUpper(); value++) {
if(this.random.nextBoolean()) {
values.add(String.valueOf(value));
}
}
varDomainSize = variableType.getUpper()-variableType.getLower()+1;
}
else { //Enum
for(String value : variableType.getValues()) {
if(this.random.nextBoolean()) {
values.add(value);
}
}
varDomainSize = variableType.getValues().size();
}
return SpecRegExp.newVariableRegExp(varRef, values, getAcceptValues(values, varDomainSize));
case PREDICATE:
return SpecRegExp.newPredicateRegExp(genRandPredicate(this.predMaxDepth));
default:
throw new RuntimeException("The nullary regexp kind " + nullaryKind + " is unsupported");
}
}
private Spec genRandPredicate(int predMaxDepth) {
SpecKind propKind = predMaxDepth > 0 ? this.propSpecKinds.get(this.random.nextInt(this.propSpecKinds.size())) :
this.nullaryPropSpecKinds.get(this.random.nextInt(this.nullaryPropSpecKinds.size()));
if(propKind.isNullary()) { //predMaxDepth >= 0
switch(propKind) {
case BOOLEAN_CONST:
return new PrimitiveValue(this.random.nextBoolean() ? TRUE : FALSE);
case BOOLEAN_VAR:
return new VariableReference(this.booleanVariables.get(this.random.nextInt(this.booleanVariables.size())));
default:
throw new RuntimeException("The nullary propositional spec kind " + propKind + " is unsupported");
}
}
else { //predMaxDepth > 0
switch(propKind) {
case EQ_OP:
boolean enumComparison = this.intVariables.isEmpty() || (!this.enumVariables.isEmpty() && this.random.nextBoolean());
if(enumComparison) { //Create a spec of the form 'enumVar = enumConstantValue'
Variable enumVariable = this.enumVariables.get(this.random.nextInt(this.enumVariables.size()));
String enumValue = enumVariable.getType().getValues().get(this.random.nextInt(enumVariable.getType().getValues().size()));
return new SpecExp(Operator.EQUALS, new VariableReference(enumVariable), new PrimitiveValue(enumValue));
}
else { //Integer comparison: create a spec of the form 'arithmetic expression = integer constant'
Spec leftArithExp = genRandArithmeticSpec(predMaxDepth-1, false);
int randValue = randEvalArithSpec(leftArithExp); //choose a random value to which the LHS can evaluate
return new SpecExp(Operator.EQUALS, leftArithExp, new PrimitiveValue(randValue));
}
case INEQ_OP: //Integer comparison: create a spec of the form 'arithmetic expression (> | < | >= | <=) integer constant'
Operator ineqOp = SpecKind.getOps(SpecKind.INEQ_OP)[this.random.nextInt(SpecKind.getOps(SpecKind.INEQ_OP).length)];
Spec leftArithExp = genRandArithmeticSpec(predMaxDepth-1, false);
int randValue = randEvalArithSpec(leftArithExp); //choose a random value to which the LHS can evaluate
return new SpecExp(ineqOp, leftArithExp, new PrimitiveValue(randValue));
case PROP_OP:
Operator propOp = SpecKind.getOps(SpecKind.PROP_OP)[this.random.nextInt(SpecKind.getOps(SpecKind.PROP_OP).length)];
Spec leftPropSpec = genRandPredicate(predMaxDepth-1);
if(propOp.isBinary()) {
return new SpecExp(propOp, leftPropSpec, genRandPredicate(predMaxDepth-1));
}
//Unary propositional operator
return new SpecExp(propOp, leftPropSpec);
default:
throw new RuntimeException("The propositional spec operator kind " + propKind + " is unsupported");
}
}
}
private Spec genRandArithmeticSpec(int predMaxDepth, boolean modOpDivisor) {
SpecKind arithKind;
if(modOpDivisor && this.nonZeroIntVariables.isEmpty()) {
arithKind = SpecKind.INT_CONST;
}
else {
arithKind = (predMaxDepth > 0 && !modOpDivisor) ? this.arithSpecKinds.get(this.random.nextInt(this.arithSpecKinds.size())) :
this.nullaryArithSpecKinds.get(this.random.nextInt(this.nullaryArithSpecKinds.size()));
}
if(arithKind.isNullary()) { //predMaxDepth >= 0
switch(arithKind) {
case INT_CONST:
int intVal = this.random.nextInt(this.maxIntConst+1);
if(modOpDivisor && intVal == 0) { //Avoid a zero divisor
intVal+=1;
}
return new PrimitiveValue(intVal);
case INT_VAR:
Variable intVariable;
if(modOpDivisor) {
intVariable = this.nonZeroIntVariables.get(this.random.nextInt(this.nonZeroIntVariables.size()));
}
else {
intVariable = this.intVariables.get(this.random.nextInt(this.intVariables.size()));
}
return new VariableReference(intVariable);
default:
throw new RuntimeException("The arithmetic spec operator kind " + arithKind + " is unsupported");
}
}
else { //predMaxDepth > 0
switch(arithKind) {
case ARITH_OP:
Operator arithOp = SpecKind.getOps(SpecKind.ARITH_OP)[this.random.nextInt(SpecKind.getOps(SpecKind.ARITH_OP).length)];
Spec leftArithSpec = genRandArithmeticSpec(predMaxDepth-1, false);
Spec rightArithSpec = genRandArithmeticSpec(predMaxDepth-1, Operator.MOD.equals(arithOp));
return new SpecExp(arithOp, leftArithSpec, rightArithSpec);
default:
throw new RuntimeException("The arithmetic spec operator kind " + arithKind + " is unsupported");
}
}
}
private int randEvalArithSpec(Spec arithSpec) {
if (arithSpec instanceof PrimitiveValue) {
PrimitiveValue intVal = (PrimitiveValue) arithSpec;
try {
return Integer.parseInt(intVal.getValue());
} catch (NumberFormatException e) {
throw new RuntimeException("The arithmetic spec " + arithSpec + " cannot be evaluated");
}
}
else if (arithSpec instanceof VariableReference) {
VariableReference varRef = (VariableReference) arithSpec;
int domSize = varRef.getVariable().getType().getUpper() - varRef.getVariable().getType().getLower() + 1;
return this.random.nextInt(domSize) + varRef.getVariable().getType().getLower();
}
else if (arithSpec instanceof SpecExp) {
SpecExp specExp = (SpecExp) arithSpec;
Operator arithOp = specExp.getOperator();
int leftRandEval = randEvalArithSpec(specExp.getChildren()[0]);
int rightRandEval = randEvalArithSpec(specExp.getChildren()[1]);
if (Operator.MOD.equals(arithOp)) {
return leftRandEval % rightRandEval;
}
if (Operator.ADD.equals(arithOp)) {
return leftRandEval + rightRandEval;
}
if (Operator.SUBSTRACT.equals(arithOp)) {
return leftRandEval - rightRandEval;
}
if (Operator.MULTIPLY.equals(arithOp)) {
return leftRandEval * rightRandEval;
}
}
throw new RuntimeException("The arithmetic spec " + arithSpec + " cannot be evaluated");
}
private boolean getAcceptValues(List<String> values, int varDomainSize) {
boolean acceptValues;
if(values.size() == varDomainSize) {
acceptValues = true;
}
else if (values.isEmpty()){
acceptValues = false;
}
else {
acceptValues = this.random.nextBoolean();
}
return acceptValues;
}
private SpecRegExp genRandBinaryRegExp(int maxDepth, RegExpKind binaryKind) {
SpecRegExp leftSubExp = genRandRegExp(maxDepth-1);
SpecRegExp rightSubExp = genRandRegExp(maxDepth-1);
switch(binaryKind) {
case UNION:
return SpecRegExp.newUnionRegExp(leftSubExp, rightSubExp);
case INTERSECTION:
return SpecRegExp.newIntersectionRegExp(leftSubExp, rightSubExp);
case CONCAT:
return SpecRegExp.newConcatRegExp(leftSubExp, rightSubExp);
default:
throw new RuntimeException("The binary regexp kind " + binaryKind + " is unsupported");
}
}
private SpecRegExp genRandUnaryRegExp(int maxDepth, RegExpKind unaryKind) {
SpecRegExp subExp = genRandRegExp(maxDepth-1);
switch(unaryKind) {
case REPEAT:
return genRandRepRegExp(subExp);
case COMPLEMENT:
return SpecRegExp.newComplementationRegExp(subExp);
default:
throw new RuntimeException("The unary regexp kind " + unaryKind + " is unsupported");
}
}
private SpecRegExp genRandRepRegExp(SpecRegExp subRegExp) {
QuantifierType quantifierType = QUANTIFIER_TYPES.get(this.random.nextInt(QUANTIFIER_TYPE_NUM));
int repRangeSize = -1, leastRepNum = -1;
switch(quantifierType) {
case ZERO_OR_MORE:
return SpecRegExp.newZeroOrMoreRepRegExp(subRegExp);
case ONE_OR_MORE:
return SpecRegExp.newOneOrMoreRepRegExp(subRegExp);
case ZERO_OR_ONE:
return SpecRegExp.newZeroOrOneRepRegExp(subRegExp);
case RANGE:
repRangeSize = 1 + this.random.nextInt(this.maxRepRange);
default:
leastRepNum = this.random.nextInt(this.maxLeastRepNum+1);
}
switch(quantifierType) {
case RANGE:
return SpecRegExp.newRepInRangeRegExp(subRegExp, leastRepNum, leastRepNum + repRangeSize - 1);
case AT_LEAST:
return SpecRegExp.newAtLeastRepRegExp(subRegExp, leastRepNum);
case EXACT_REPETITION:
return SpecRegExp.newExactRepRegExp(subRegExp, leastRepNum);
default:
throw new RuntimeException("The regexp repetition quantifier " + quantifierType + " is unsupported");
}
}
}
/*
*
* Public methods
*
*/
public RegExpKind getRegExpKind(){
return this.kind;
}
public boolean isNullaryRegExp() {
if(this.kind != null) {
return this.kind.isNullary();
}
return false;
}
public boolean isBinaryRegExp() {
if(this.kind != null) {
return this.kind.isBinary() && this.left != null && this.right != null;
}
return false;
}
public boolean isUnaryRegExp() {
if(this.kind != null) {
return this.kind.isUnary();
}
return false;
}
public boolean hasLeft() {
return this.left != null;
}
public boolean hasRight() {
return this.right != null;
}
/**
* Checks whether this regular expression consists of a variable and asserts that this variable
* should be equal to at least one value.
*
* @return
*/
public boolean isVariable() {
return RegExpKind.VAR.equals(this.kind)
&& this.varRef != null
&& this.varRef.getReferenceName() != null
&& this.varRef.getVariable() != null
&& this.varRef.getVariable().getName() != null
&& this.values != null
&& !this.values.isEmpty();
}
public boolean isPredicate() {
return RegExpKind.PREDICATE.equals(this.kind)
&& this.predicate != null;
}
public Spec getPredicate() {
return this.predicate;
}
public void setPredicate(Spec predicate) {
this.predicate = predicate;
}
/**
* Serializes this {@link SpecRegExp} object in the specified file.
*
* @param fileName the file name
*/
public void save(String fileName) throws IOException {
//Saving of this regexp in a file
FileOutputStream file = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(file);
//Serialization of this regexp
out.writeObject(this);
out.close();
file.close();
}
/**
*
* Deserializes the {@link SpecRegExp} object serialized in the file with the name {@code fileName}.
*
*
* @param fileName the file name
* @return The {@link SpecRegExp} object serialized in the file
* @throws IOException
* @throws ClassNotFoundException
*/
public static SpecRegExp loadRegExp(String fileName) throws IOException, ClassNotFoundException {
//Reading the object from a file
FileInputStream file = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(file);
//Deserialization of the current regexp object
SpecRegExp regExp = (SpecRegExp)in.readObject();
in.close();
file.close();
return regExp;
}
/**
* Returns a list that consists of all the subexpressions of the form '[Boolean term (assertion)]'
* in this regular expression.
*
* @return
*/
public List<SpecRegExp> getPredicateSubExps() {
List<SpecRegExp> predicateExps = new ArrayList<>();
this.addAllPredicateSubExps(predicateExps);
return predicateExps;
}
/**
* Returns a list that consists of all the variables referenced in the atomic subexpressions
* of this regular expression. Each variable appears in the returned list exactly once.
*
* @return
*/
public List<Variable> getVariables() {
List<Variable> regExpVars = new ArrayList<>();
this.addAllVariables(regExpVars);
return regExpVars;
}
/**
* <p>Returns a mapping of all the variable references (reference names) that appear in this regular expression
* to the referenced variable objects.</p>
*
* <p>Note: The reference name may be different than the name of the referenced variable in case the variable
* is an array. For example, 'arrVar[0][2]' references the two-dimensional array variable 'arrVar'.</p>
*
* @return
*/
public Map<String, Variable> getRefToVarMapping() {
Map<String, Variable> refToVar = new HashMap<>();
fillRefToVarMapping(refToVar);
return refToVar;
}
/**
* Checks whether this regular expression contains a subexpression with a complementation/negation operator.
*
* @return
*/
public boolean containsComplement() {
if(RegExpKind.COMPLEMENT.equals(this.kind)) {
return true;
}
if(this.hasLeft() && this.left.containsComplement()) {
return true;
}
if(this.hasRight() && this.right.containsComplement()) {
return true;
}
return false;
}
/**
* Checks whether this regular expression consists of a Boolean constant, either TRUE or FALSE.
*
* @return
*/
public boolean isBooleanConst() {
return isBooleanConstKind() && (hasSingleBooleanValue(true) || hasSingleBooleanValue(false));
}
/**
* Checks whether this regular expression is the TRUE Boolean constant.
*
* @return
*/
public boolean isTrueBooleanConst() {
return isBooleanConstKind() && hasSingleBooleanValue(true);
}
/**
* Checks whether this regular expression is the FALSE Boolean constant.
*
* @return
*/
public boolean isFalseBooleanConst() {
return isBooleanConstKind() && hasSingleBooleanValue(false);
}
public boolean isEmptyString() {
return RegExpKind.EMPTY_STR.equals(this.kind);
}
public boolean isComplementation() {
return isUnaryKind(RegExpKind.COMPLEMENT);
}
/**
* Checks whether this regular expression asserts a repetition (via a quantifier) of a
* sub-expression.
*
* @return
* @see #getQuantifier()
* @see #getQuantifierType()
* @see QuantifierType
* @see RegExpQuantifier
*/
public boolean isRepetition() {
return isUnaryKind(RegExpKind.REPEAT) && this.quantifier != null;
}
/**
* Checks whether this regular expression is a concatenation of two regular expressions.
*
* @return
*/
public boolean isConcat() {
return isBinaryKind(RegExpKind.CONCAT);
}
/**
* Checks whether this regular expression is a union of two regular expressions.
*
* @return
*/
public boolean isUnion() {
return isBinaryKind(RegExpKind.UNION);
}
/**
* Checks whether this regular expression is an intersection of two regular expressions.
*
* @return
*/
public boolean isIntersection() {
return isBinaryKind(RegExpKind.INTERSECTION);
}
public QuantifierType getQuantifierType() {
return isRepetition() ? this.quantifier.type : null;
}
public RegExpQuantifier getQuantifier() {
return this.quantifier;
}
public SpecRegExp getLeft(){
return left;
}
public SpecRegExp getRight(){
return right;
}
public Variable getVariable() {
return this.isVariable() ? this.varRef.getVariable() : null;
}
public VariableReference getVariableReference() {
return this.varRef;
}
public String getVariableName() {
return this.isVariable() ? this.varRef.getVariable().getName() : null;
}
public String getVariableReferenceName() {
return this.isVariable() ? this.varRef.getReferenceName() : null;
}
/**
* Checks whether this regular expression consists of a Boolean variable and asserts that this variable
* should be equal to either TRUE or FALSE (or both).
*
* @return
*/
public boolean isBooleanVariable() {
return this.isVariable()
&& this.varRef.getVariable().getType() != null
&& this.varRef.getVariable().getType().isBoolean()
&& allValuesAreBooleans();
}
/**
* Checks whether this regular expression consists of an integer variable and asserts that this variable
* should be equal to an element in a non-empty set of integer values.
* @return
*/
public boolean isIntegerVariable() {
return this.isVariable()
&& this.varRef.getVariable().getType() != null
&& this.varRef.getVariable().getType().isInteger()
&& allValuesAreInts();
}
/**
* Checks whether this regular expression consists of an enumeration variable and asserts that this variable
* should be equal to an element in a non-empty set of values.
* @return
*/
public boolean isEnumVariable() {
return this.isVariable()
&& this.varRef.getVariable().getType() != null
&& !this.varRef.getVariable().getType().isInteger()
&& !this.varRef.getVariable().getType().isBoolean();
}
/**
* If this is a regular expression which is a Boolean constant,
* returns the underlying Boolean value. Otherwise, returns {@code null}.
* @return
*/
public String getBooleanValue() {
if(this.isBooleanConst()) {
return this.values.get(0);
}
return null;
}
public Set<String> getValues(){
return new HashSet<>(this.values);
}
@Override
public boolean isPastLTLSpec() {
return false;
}
@Override
public boolean isPropSpec() {
return false;
}
@Override
public boolean hasTemporalOperators() {
return false;
}
@Override
public SpecRegExp clone() throws CloneNotSupportedException {
return new SpecRegExp(this.left != null ? this.left.clone() : null, this.right != null ? this.right.clone() : null, this.values != null ? new ArrayList<>(this.values) : null,
this.varRef != null ? this.varRef.clone() : null, this.predicate != null ? this.predicate.clone() : null, this.kind,
this.quantifier != null ? this.quantifier.clone() : null);
}
@Override
public String toString() {
if(this.isEmptyString()) { //regExp = '()'
return "()";
}
if(this.isTrueBooleanConst()) { //regExp = 'TRUE'
return "true";
}
if(this.isFalseBooleanConst()) { //regExp = 'FALSE'
return "false";
}
if(this.isVariable()) { //regExp = '[var in {set of values}]'
StringBuilder res = new StringBuilder();
res.append("[");
res.append(this.getVariableReferenceName());
res.append(" in {");
this.values.subList(0, this.values.size()-1).forEach(s -> res.append(s + ", "));
res.append(this.values.get(this.values.size()-1));
res.append("}]");
return res.toString();
}
if(this.isPredicate()) { //regExp = '[Boolean term (assertion)]'
return "[" + this.predicate.toString() + "]";
}
if(!this.hasLeft()) {
return "INVALID REGEXP: expected non-null left subexpession attribute";
}
String leftRes = this.left.toString();
if(this.isRepetition()) {
return "(" + leftRes + ")" + this.quantifier.toString();
}
if(this.isComplementation()) {
return "~(" + leftRes + ")";
}
if(!this.hasRight()) {
return "INVALID REGEXP: expected non-null right subexpession attribute";
}
String rightRes = this.right.toString();
if(this.isConcat()) {
return "(" + leftRes + ") (" + rightRes + ")";
}
if(this.isUnion()) {
return "(" + leftRes + ")|(" + rightRes + ")";
}
if(this.isIntersection()) {
return "(" + leftRes + ")&(" + rightRes + ")";
}
return "INVALID REGEXP KIND: cannot generate string for this regular expression";
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
SpecRegExp other = (SpecRegExp) obj;
if(this.kind != other.kind) {return false;}
//this.kind == other.kind
if(this.kind == null || RegExpKind.EMPTY_STR.equals(this.kind)) {return true;}
if(RegExpKind.BOOLEAN_CONST.equals(this.kind)) { //Both kinds are Boolean constants
if(this.values != null) {
return this.values.equals(other.values);
}
else {
return other.values == null;
}
}
if(RegExpKind.VAR.equals(this.kind)) { //Both kinds are variables
if(this.varRef != null) {
if(other.varRef == null) {
return false;
}
if(this.varRef.getReferenceName() != null) {
if(!this.varRef.getReferenceName().equals(other.varRef.getReferenceName())) {
return false;
}
if(this.values != null) {
if(other.values == null) {
return false;
}
//Compare the two values' lists, but ignore the elements' order
Set<String> thisValSet = new HashSet<>(this.values);
Set<String> otherValSet = new HashSet<>(other.values);
return thisValSet.equals(otherValSet);
}
else {
return other.values == null;
}
}
else {
return other.varRef.getReferenceName() == null;
}
}
else {
return other.varRef == null;
}
}
if(RegExpKind.PREDICATE.equals(this.kind)) { //Both kinds are predicates
if(this.predicate != null) {
return this.predicate.equals(other.predicate);
}
else {
return other.predicate == null;
}
}
if(this.kind.isUnary()) { //Both kinds are unary
if(RegExpKind.REPEAT.equals(this.kind)) { //Check that both have the same repetition quantifier
if(this.quantifier != null) {
if(!this.quantifier.equals(other.quantifier)) {return false;}
}
else if(other.quantifier != null) {return false;}
}
//Check that the (left and only) subexpressions are equal
if(this.left != null) {
return this.left.equals(other.left);
}
else {
return this.left == null;
}
}
else { //Both kinds are binary
boolean leftEquals;
//Check that the left subexpressions are equal
if(this.left != null) {
leftEquals = this.left.equals(other.left);
}
else {
leftEquals = (other.left == null);
}
if(!leftEquals) {
//The left subexpressions are not equal
return false;
}
//Check that the right subexpressions are equal
if(this.right != null) {
return this.right.equals(other.right);
}
else {
return other.right == null;
}
}
}
/*
*
*
*
*
*
*
* Static factory methods
*
*
*
*
*
*
*
*
*/
public static SpecRegExp newVariableRegExp(VariableReference varRef, List<String> values, boolean acceptValues) {
if(varRef == null || varRef.getVariable() == null || varRef.getVariable().getType() == null || values == null || (acceptValues && values.isEmpty())) {
throw new RuntimeException("Could not create a new variable SpecRegExp object."
+ " The given arguments would lead to the creation of an invalid regular expression");
}
SpecRegExp newRegExp = new SpecRegExp(varRef, values, acceptValues);
if(!acceptValues && newRegExp.values.isEmpty()) {
//the complementation of the values set has resulted in an empty set of values
//this is an invalid regular expression (as it requires that the variable should not be equal to any value)
return null;
}
return newRegExp;
}
public static SpecRegExp newPredicateRegExp(Spec predicate) {
if(predicate == null){
throw new RuntimeException("Could not create a new predicate SpecRegExp object."
+ " The predicate (a Spec object) that has been specified is null");
}
return new SpecRegExp(predicate);
}
public static SpecRegExp newBooleanConstRegExp(boolean booleanValue) {
return new SpecRegExp(booleanValue);
}
public static SpecRegExp newEmptyStringRegExp() {
return new SpecRegExp();
}
public static SpecRegExp newUnionRegExp(SpecRegExp leftSubExp, SpecRegExp rightSubExp) {
if(leftSubExp == null || rightSubExp == null) {
throw new RuntimeException("Could not create a new union SpecRegExp object. "
+ (leftSubExp == null ? "The left" : "The right") + " subexpression that has been specified is null");
}
return new SpecRegExp(leftSubExp, rightSubExp, RegExpKind.UNION);
}
public static SpecRegExp newConcatRegExp(SpecRegExp leftSubExp, SpecRegExp rightSubExp) {
if(leftSubExp == null || rightSubExp == null) {
throw new RuntimeException("Could not create a new concatenation SpecRegExp object. "
+ (leftSubExp == null ? "The left" : "The right") + " subexpression that has been specified is null");
}
return new SpecRegExp(leftSubExp, rightSubExp, RegExpKind.CONCAT);
}
public static SpecRegExp newIntersectionRegExp(SpecRegExp leftSubExp, SpecRegExp rightSubExp) {
if(leftSubExp == null || rightSubExp == null) {
throw new RuntimeException("Could not create a new intersection SpecRegExp object. "
+ (leftSubExp == null ? "The left" : "The right") + " subexpression that has been specified is null");
}
return new SpecRegExp(leftSubExp, rightSubExp, RegExpKind.INTERSECTION);
}
public static SpecRegExp newComplementationRegExp(SpecRegExp subExp) {
if(subExp == null) {
throw new RuntimeException("Could not create a new complement SpecRegExp object."
+ " The subexpression that has been specified is null");
}
return new SpecRegExp(subExp, RegExpKind.COMPLEMENT);
}
public static SpecRegExp newZeroOrOneRepRegExp(SpecRegExp subExp) {
if(subExp == null) {
throw new RuntimeException("Could not create a new 'zero or one' repetitions SpecRegExp object."
+ " The quantified subexpression that has been specified is null");
}
return new SpecRegExp(subExp);
}
public static SpecRegExp newZeroOrMoreRepRegExp(SpecRegExp subExp) {
if(subExp == null) {
throw new RuntimeException("Could not create a new 'zero or more' repetitions SpecRegExp object."
+ " The quantified subexpression that has been specified is null");
}
return new SpecRegExp(subExp, true);
}
public static SpecRegExp newOneOrMoreRepRegExp(SpecRegExp subExp) {
if(subExp == null) {
throw new RuntimeException("Could not create a new 'one or more' repetitions SpecRegExp object."
+ " The quantified subexpression that has been specified is null");
}
return new SpecRegExp(subExp, false);
}
public static SpecRegExp newExactRepRegExp(SpecRegExp subExp, int repNum) {
if(subExp == null) {
throw new RuntimeException("Could not create a new 'exact' repetitions SpecRegExp object."
+ " The quantified subexpression that has been specified is null");
}
if(repNum < 0) {
throw new RuntimeException("Could not create a new 'exact' repetitions SpecRegExp object."
+ " The number of repetitions that has been specified is negative (must be non-negative)");
}
return new SpecRegExp(subExp, true, repNum);
}
public static SpecRegExp newAtLeastRepRegExp(SpecRegExp subExp, int repNum) {
if(subExp == null) {
throw new RuntimeException("Could not create a new 'at least' repetitions SpecRegExp object."
+ " The quantified subexpression that has been specified is null");
}
if(repNum < 0) {
throw new RuntimeException("Could not create a new 'at least' repetitions SpecRegExp object."
+ " The number of repetitions that has been specified is negative (must be non-negative)");
}
return new SpecRegExp(subExp, false, repNum);
}
public static SpecRegExp newRepInRangeRegExp(SpecRegExp subExp, int leastRepNum, int maxRepNum) {
//if(subExp == null || leastRepNum < 0 || maxRepNum < leastRepNum) {return null;}
if(subExp == null) {
throw new RuntimeException("Could not create a new 'repetitions in range' SpecRegExp object."
+ " The quantified subexpression that has been specified is null");
}
if(leastRepNum < 0) {
throw new RuntimeException("Could not create a new 'repetitions in range' SpecRegExp object."
+ " The least number of repetitions that has been specified is negative (must be non-negative)");
}
if(maxRepNum < leastRepNum) {
throw new RuntimeException("Could not create a new 'repetitions in range' SpecRegExp object."
+ " The maximal number of repetitions that has been specified is smaller than the least one");
}
return new SpecRegExp(subExp, leastRepNum, maxRepNum);
}
/*
*
*
*
*
*
* Private constructors
*
*
*
*
*
*/
/**
*
*
* Constructor for a regular expression that consists of a Boolean term/formula/predicate.
*
* @param predicate the Boolean predicate/formula
*/
private SpecRegExp(Spec predicate) {
this.kind = RegExpKind.PREDICATE;
this.predicate = predicate;
}
/**
*
* Constructor for a regular expression that specifies a variable and a set of values, either of which should be assigned to that variable.
*
* @param varRef the variable reference
* @param values non-empty set of the values, each of which is ASSUMED to be in the domain of {@code variable}
* @param acceptValues {@code true} (resp. {@code false}) if either (resp. neither) of the values in {@code values} should be accepted by the regular expression
*/
private SpecRegExp(VariableReference varRef, List<String> values, boolean acceptValues) {
this.kind = RegExpKind.VAR;
this.varRef = varRef;
if(acceptValues) {
this.values = values;
}
else { //we assume that (varRef != null && varRef.getVariable() != null && varRef.getVariable().getType() != null && values != null)
//this.values should be the complement of the given list of values (w.r.t. the domain of the variable)
if(varRef.getVariable().getType().isBoolean()) {
//Boolean variable
this.values = new ArrayList<>();
this.values.add(TRUE);
this.values.add(FALSE);
}
else if (varRef.getVariable().getType().isInteger()) {
this.values = IntStream.rangeClosed(varRef.getVariable().getType().getLower(), varRef.getVariable().getType().getUpper()).
mapToObj(String::valueOf).collect(Collectors.toList());
}
else { //Enum variable
this.values = new ArrayList<>(varRef.getVariable().getType().getValues());
}
//this.values now contains all the values in the domain of the given variable
//thus to obtain the complement list, we remove all the values that are in the given list
this.values.removeAll(values);
}
}
/**
*
* Constructor for a regular expression of a constant Boolean value, either 'true' or 'false'.
*
* @param booleanValue the Boolean value
*/
private SpecRegExp(boolean booleanValue) {
this.kind = RegExpKind.BOOLEAN_CONST;
String constValue = booleanValue ? TRUE : FALSE;
this.values = new ArrayList<>();
this.values.add(constValue);
}
/**
*
* Constructor for the empty string regular expression.
*
*/
private SpecRegExp() {
this.kind = RegExpKind.EMPTY_STR;
}
/**
* Constructor for an unary regular expression.
*
* @param left the sub regular expression
* @param kind the kind of the unary operator, e.g., complementation
*/
private SpecRegExp(SpecRegExp left, RegExpKind kind) {
this(left, null, kind);
}
/**
*
* Constructor for a binary regular expression.
*
* @param left the left sub regular expression
* @param right the right sub regular expression
* @param kind the kind of the binary operator, e.g., union, intersection, concatenation.
*/
private SpecRegExp(SpecRegExp left, SpecRegExp right, RegExpKind kind) {
this(left, right, null, null, null, kind, null);
}
/**
*
* Constructor for a regular expression of any kind.
*
* @param left the left sub regular expression
* @param right the right sub regular expression
* @param values set of the values
* @param varRef the variable reference
* @param predicate the Boolean predicate/formula
* @param kind the kind of the regular expression
* @param quantifier the repetitions quantifier
*/
private SpecRegExp(SpecRegExp left, SpecRegExp right, List<String> values,
VariableReference varRef, Spec predicate, RegExpKind kind, RegExpQuantifier quantifier) {
this.left = left;
this.right = right;
this.values = values;
this.varRef = varRef;
this.predicate = predicate;
this.kind = kind;
this.quantifier = quantifier;
}
/**
* Constructor for an unary regular expression with a 'zero or one repetitions' quantifier ('?').
*
* @param left the sub regular expression
*/
private SpecRegExp(SpecRegExp left) {
this(left, RegExpKind.REPEAT);
this.quantifier = RegExpQuantifier.zeroOrOneRepetition();
}
/**
* Constructor for an unary regular expression with either of the following two quantifiers:<br>
*
* - 'Zero or more repetitions' (Kleene iteration, '*')<br>
* - 'One or more repetitions' ('+')
*
* @param left the sub regular expression
* @param zeroOrMore whether the regular expression has a Kleene iteration quantifier
*/
private SpecRegExp(SpecRegExp left, boolean zeroOrMore) {
this(left, RegExpKind.REPEAT);
if(zeroOrMore) {
this.quantifier = RegExpQuantifier.zeroOrMoreRepetitions();
}
else {
this.quantifier = RegExpQuantifier.oneOrMoreRepetitions();
}
}
/**
* Constructor for an unary regular expression with either of the following quantifiers:<br>
*
* - 'Exact repetitions' ('{{@code n}}') <br>
* - 'At least repetitions' ('{{@code n},}')
*
* @param left the sub regular expression
* @param isExact whether the regular expression has an 'exact repetitions' quantifier
* @param n the number of repetitions
*/
private SpecRegExp(SpecRegExp left, boolean isExact, int n) {
this(left, RegExpKind.REPEAT);
if(isExact) {
this.quantifier = RegExpQuantifier.exactRepetitions(n);
}
else {
this.quantifier = RegExpQuantifier.atLeastRepetitions(n);
}
}
/**
* Constructor for an unary regular expression with 'repetitions in range' ('{{@code n},{@code m}}') quantifier.
*
*
* @param left the sub regular expression
* @param n the least number of repetitions
* @param m the maximal number of repetitions (inclusive)
*/
private SpecRegExp(SpecRegExp left, int n, int m) {
this(left, RegExpKind.REPEAT);
this.quantifier = RegExpQuantifier.repetitionsInRange(n, m);
}
/*
*
* Private methods
*
*
*
*/
private void addAllPredicateSubExps(List<SpecRegExp> predicateExps) {
if(this.isPredicate()) {
if(!predicateExps.contains(this)) { //regExp = '[Boolean term (assertion)]'
predicateExps.add(this);
}
}
else {
if(this.hasLeft()) {
this.left.addAllPredicateSubExps(predicateExps);
}
if(this.hasRight()) {
this.right.addAllPredicateSubExps(predicateExps);
}
}
}
private void addAllVariables(List<Variable> regExpVars) {
if(this.isVariable()) { //regExp = '[variable in {set of values}]'
if(!regExpVars.contains(this.varRef.getVariable())) {
regExpVars.add(this.varRef.getVariable());
}
}
else if(this.isPredicate()) { //regExp = '[Boolean term (instance of Spec)]'
this.addAllSpecVariables(this.predicate, regExpVars);
}
else {
if(this.hasLeft()) {
this.left.addAllVariables(regExpVars);
}
if(this.hasRight()) {
this.right.addAllVariables(regExpVars);
}
}
}
private void addAllSpecVariables(Spec spec, List<Variable> regExpVars) {
if(spec instanceof VariableReference) {
VariableReference vr = (VariableReference) spec;
Variable var = vr.getVariable();
if(var != null && !regExpVars.contains(var)) {
regExpVars.add(var);
}
}
else if(spec instanceof SpecExp) {
SpecExp specExp = (SpecExp) spec;
for(Spec childSpec : specExp.getChildren()) {
addAllSpecVariables(childSpec, regExpVars);
}
}
}
private void fillRefToVarMapping(Map<String, Variable> refToVar) {
if(this.isVariable()) { //regExp = '[variable in {set of values}]'
if(!refToVar.containsKey(this.varRef.getReferenceName())) {
refToVar.put(this.varRef.getReferenceName(), this.varRef.getVariable());
}
}
else if(this.isPredicate()) { //regExp = '[Boolean term (instance of Spec)]'
this.fillSpecRefToVarMapping(this.predicate, refToVar);
}
else {
if(this.hasLeft()) {
this.left.fillRefToVarMapping(refToVar);
}
if(this.hasRight()) {
this.right.fillRefToVarMapping(refToVar);
}
}
}
private void fillSpecRefToVarMapping(Spec spec, Map<String, Variable> refToVar) {
if(spec instanceof VariableReference) {
VariableReference varRef = (VariableReference) spec;
if(!refToVar.containsKey(varRef.getReferenceName())) {
refToVar.put(varRef.getReferenceName(), varRef.getVariable());
}
}
else if(spec instanceof SpecExp) {
SpecExp specExp = (SpecExp) spec;
for(Spec childSpec : specExp.getChildren()) {
fillSpecRefToVarMapping(childSpec, refToVar);
}
}
}
private boolean hasSingleBooleanValue(boolean trueValue) {
return this.values != null && this.values.size() == 1 && (trueValue ? TRUE.equalsIgnoreCase(this.values.get(0)) : FALSE.equalsIgnoreCase(this.values.get(0)));
}
private boolean isBooleanConstKind() {
return RegExpKind.BOOLEAN_CONST.equals(this.kind);
}
private boolean isBinaryKind(RegExpKind kind) {
return kind.equals(this.kind) && this.left != null && this.right != null;
}
private boolean isUnaryKind(RegExpKind kind) {
return kind.equals(this.kind) && this.left != null;
}
private boolean allValuesAreInts() {
for(String val : this.values) {
try {
Integer.valueOf(val);
} catch (NumberFormatException e) {
return false;
}
}
return true;
}
private boolean allValuesAreBooleans() {
for(String val : this.values) {
if(!(TRUE.equalsIgnoreCase(val) || FALSE.equalsIgnoreCase(val))) {
return false;
}
}
return true;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinput.spec;
import java.util.Map;
import tau.smlab.syntech.gameinput.model.Variable;
public class SpecHelper {
// Get underlying variable of temporal expression inside index. We assume that
// there is only one variable
// in each index since it was verified during type check phase
public static void getUnderlyingVariables(Spec index, Map<String, Variable> vars) {
if (index instanceof VariableReference) {
Variable var = ((VariableReference) index).getVariable();
vars.put(var.getName(), var);
} else if (index instanceof SpecExp) {
SpecExp indexExp = (SpecExp) index;
for (Spec child : indexExp.getChildren()) {
getUnderlyingVariables(child, vars);
}
}
}
public static void updateDefineReference(DefineReference defRef, Variable var, PrimitiveValue primVal) throws Exception {
for (int i = 0; i < defRef.getIndexSpecs().size(); i++) {
Spec interpreted = SpecHelper.interpretWithVariable(defRef.getIndexSpecs().get(i), var, primVal);
defRef.getIndexSpecs().set(i, interpreted);
}
defRef.getIndexVars().remove(var.getName());
if (defRef.getIndexVars().isEmpty()) {
for (int i = 0; i < defRef.getIndexSpecs().size(); i++) {
Integer indexValue = SpecHelper.calculateSpec(defRef.getIndexSpecs().get(i));
if (indexValue < 0 || indexValue >= defRef.getIndexDimensions().get(i)) {
throw new Exception(String.format("Index %d out of bounds for variable %s", indexValue,
defRef.getDefine().getName()));
}
}
}
}
public static void updateRefName(VariableReference varRef) throws Exception {
String refName = varRef.getVariable().getName();
if (varRef.getIndexVars().isEmpty()) {
for (int i = 0; i < varRef.getIndexSpecs().size(); i++) {
Integer indexValue = SpecHelper.calculateSpec(varRef.getIndexSpecs().get(i));
if (indexValue < 0 || indexValue >= varRef.getIndexDimensions().get(i)) {
throw new Exception(String.format("Index %d out of bounds for variable %s", indexValue,
varRef.getVariable().getName()));
}
refName += String.format("[%d]", indexValue);
}
}
varRef.setReferenceName(refName);
}
public static Spec interpretWithVariable(Spec spec, Variable var, PrimitiveValue value) throws Exception {
// Assign value to varRef
if (spec instanceof VariableReference) {
VariableReference varRef = (VariableReference) spec;
if (varRef.getVariable().equals(var)) {
return value;
} else {
return varRef;
}
} else if (spec instanceof PrimitiveValue) {
return spec;
} else if (spec instanceof DefineReference) {
DefineReference def = (DefineReference) spec;
// For the time being, cannot interpret define arrays inside index spec
if (def.getDefine().getExpression() != null) {
def.getDefine().setExpression((interpretWithVariable(def.getDefine().getExpression(), var, value)));
return def;
} else {
throw new Exception("Spec cannot be interpreted with variable, has invalid inner specs");
}
} else if (spec instanceof SpecExp) {
SpecExp exp = (SpecExp) spec;
return new SpecExp(exp.getOperator(), interpretWithVariable(exp.getChildren()[0], var, value),
interpretWithVariable(exp.getChildren()[1], var, value));
} else {
throw new Exception("Spec cannot be interpreted with variable, has invalid inner specs");
}
}
public static Integer calculateSpec(Spec spec) throws Exception {
if (spec instanceof PrimitiveValue) {
PrimitiveValue intVal = (PrimitiveValue) spec;
try {
return Integer.parseInt(intVal.getValue());
} catch (NumberFormatException e) {
throw new Exception("Spec cannot be calculated, is non integer");
}
} else if (spec instanceof DefineReference) {
DefineReference def = (DefineReference) spec;
if (def.getDefine().getExpression() != null) {
return calculateSpec(def.getDefine().getExpression());
} else {
throw new Exception("Spec cannot be calculated, contains define references");
}
} else if (spec instanceof SpecExp) {
SpecExp specExp = (SpecExp) spec;
Operator op = specExp.getOperator();
Integer res1 = calculateSpec(specExp.getChildren()[0]);
Integer res2 = calculateSpec(specExp.getChildren()[1]);
if (Operator.MOD.equals(op)) {
return ((res1 % res2) + res2) % res2;
} else if (Operator.ADD.equals(op)) {
return res1 + res2;
} else if (Operator.SUBSTRACT.equals(op)) {
return res1 - res2;
} else if (Operator.MULTIPLY.equals(op)) {
return res1 * res2;
} else if (Operator.DIVIDE.equals(op)) {
return res1 / res2;
} else {
throw new Exception("Spec cannot be calculated, is non integer");
}
} else if (spec instanceof VariableReference) {
throw new Exception("Spec cannot be calculated, contains variable references");
} else {
throw new Exception("Spec cannot be calculated, is non integer");
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.sf.javabdd;
import net.sf.javabdd.BDDFactory.ReorderMethod;
public interface CUDDCaller {
public void initialize0Caller(int nodenum, int cachesize);
public boolean isInitialized0Caller();
public void done0Caller();
public int varNum0Caller();
public int setVarNum0Caller(int num, boolean ADD);
public long ithVar0Caller(int var, boolean ADD);
public int level2Var0Caller(int level);
public int var2Level0Caller(int var);
public void setVarOrder0Caller(int[] neworder);
public int getAllocNum0Caller();
public int getNodeNum0Caller();
public int getCacheSize0Caller();
public int var0Caller(long b);
public long high0Caller(long b, boolean ADD);
public long low0Caller(long b, boolean ADD);
public long not0Caller(long b, boolean ADD);
public long ite0Caller(long b, long c, long d, boolean ADD);
public long relprod0Caller(long b, long c, long d);
public long compose0Caller(long b, long c, int var, boolean ADD);
public long exist0Caller(long b, long c, boolean ADD);
public long forAll0Caller(long b, long c, boolean ADD);
public long restrict0Caller(long b, long var);
public long restrictWith0Caller(long b, long c, boolean deref_other);
public long simplify0Caller(long b, long var, boolean ADD);
public long support0Caller(long b, boolean is_add);
public long apply0Caller(long b, long c, int opr, boolean ADD, boolean apply_with, boolean deref_other);
public long satOne0Caller(long b, long c, boolean ADD);
public int nodeCount0Caller(long b);
public double pathCount0Caller(long b);
public double satCount0Caller(long b);
public void addRefCaller(long p);
public void delRefCaller(long p, boolean ADD);
public long veccompose0Caller(long b, long p, boolean ADD);
public long replace0Caller(long b, long p, boolean ADD);
public long allocCaller(boolean ADD);
public void set0Caller(long p, int oldvar, int newvar, boolean ADD);
public void set2Caller(long p, int oldvar, long newbdd);
public void reset0Caller(long ptr, boolean ADD);
public void free0Caller(long ptr);
public boolean isZeroOneADD0Caller(long ptr);
public long addConst0Caller(double constval);
public boolean isAddConst0Caller(long ptr);
public long addFindMax0Caller(long ptr);
public long addFindMin0Caller(long ptr);
public double retrieveConstValue0Caller(long ptr);
public long addAdditiveNeg0Caller(long ptr);
public long addApplyLog0Caller(long ptr);
public void reorder0Caller(ReorderMethod method);
public void autoReorder0Caller(ReorderMethod method, boolean setmax, int maxval);
public ReorderMethod getreordermethod0Caller();
public void autoReorder1Caller();
public int reorderVerbose0Caller(int v);
public void addVarBlock0Caller(int first, int last, boolean fixed);
public void clearVarBlocks0Caller();
public void printStat0Caller();
public long toADD0Caller(long b);
public long toBDD0Caller(long b);
public long toBDDThresholdCaller(long b, double threshold);
public long toBDDStrictThresholdCaller(long b, double threshold);
public long toBDDIntervalCaller(long b, double lower, double upper);
public long toBDDIthBitCaller(long b, int bit);
public int[] varSupportIndex0Caller(long b);
public void printSet0Caller(long b, int printMode);
public long logicZero0Caller();
public long arithmeticZero0Caller();
public long arithmeticLogicOne0Caller();
public long arithmeticPlusInfinity0Caller();
public long arithmeticMinusInfinity0Caller();
public long replaceWith0Caller(long b, long c, boolean ADD);
public long addMinimizeVal0Caller(long ptr, double val);
public long addAbstractMin0Caller(long b, long c);
public long addAbstractMax0Caller(long b, long c);
public int reorderTimes0Caller();
public void printVarTree0Caller();
public long addEngSubtract0Caller(long a, long b, double maxEnergy);
public long convertToZeroOneADDByThres0Caller(long a, long opType, double thresValue);
public void printDot0Caller(long a);
public long arithmeticExist0Caller(long b, long c);
public long determinizeController0Caller(long b, long c);
public int getSize0Caller(long b);
public long getBddZero();
public long getAddZero();
public long getManager();
public long getOne();
public boolean reorderEnabled0Caller();
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.ui.extension.console;
import java.io.IOException;
import java.io.PrintStream;
import org.eclipse.core.resources.IFile;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.IConsoleView;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import tau.smlab.syntech.ui.logger.SpectraLogger;
public class ConsolePrinter {
public final static int APPEND = 0;
public final static int CLEAR_CONSOLE = 1;
private String pluginName;
private MessageConsole console;
/**
*
* @param activator should be an Activator object.
* @param mode ConsolePrinter.APPEND or ConsolePrinter.CLEAR_CONSOLE
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public ConsolePrinter(String name, int mode)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
this.pluginName = name;
this.console = getConsole();
if (mode == CLEAR_CONSOLE) {
clearConsole();
} else if (mode == APPEND) {
println("");
}
println(pluginName + ":");
println("");
}
public void clearConsole() {
console.clearConsole();
}
private MessageConsole getConsole() {
String name = "SYNTECH Console";
ConsolePlugin plugin = ConsolePlugin.getDefault();
IConsoleManager conMan = plugin.getConsoleManager();
IConsole[] existing = conMan.getConsoles();
for (int i = 0; i < existing.length; i++)
if (name.equals(existing[i].getName())) {
return (MessageConsole) existing[i];
}
// no console found, so create a new one
MessageConsole myConsole = new MessageConsole(name, null);
myConsole.activate();
conMan.addConsoles(new IConsole[] { myConsole });
return myConsole;
}
public void print(String string) {
print(string, false);
}
public void println(String string) {
print(string, true);
}
public void printlnAndLog(IFile specFile, String actionID, String buffer) {
println(buffer);
SpectraLogger.logBuffer(specFile, actionID, buffer);
}
private void print(String string, boolean isPrintln) {
MessageConsoleStream mcs = console.newMessageStream();
if (isPrintln) {
mcs.println(string);
} else {
mcs.print(string);
}
try {
mcs.flush();
mcs.close();
} catch (IOException e) {
}
}
/**
* Call this function to open the console view
*/
public void showConsole(IWorkbenchPage page) {
try {
IConsoleView view = (IConsoleView) page.showView(IConsoleConstants.ID_CONSOLE_VIEW);
view.display(getConsole());
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public PrintStream getPrintStream() {
return new PrintStream(console.newOutputStream());
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.jits;
import java.util.Map;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;
/**
*
* @author ilia
*
*/
public class RecoveryController extends AbstractJitController {
public RecoveryController(JitController jitController) {
super(jitController);
}
@Override
public void load(String folder, String name, Map<String, String[]> sysVars, Map<String, String[]> envVars) {
jitController.load(folder, name, sysVars, envVars);
BDD Z = Env.unprime(getJitContext().Y(0, getJitContext().rank(0) - 1));
// Trans and ini are taken only from sys
jitController.getJitContext().setTrans(jitController.getJitContext().getSysTrans());
jitController.getJitContext().setIni(jitController.getJitContext().getSysIni().exist(Env.globalPrimeVars()).and(Z));
Z.free();
}
@Override
public BDD next(BDD currentState, BDD inputs) {
if (currentState.and(jitController.getJitContext().getEnvTrans()).and(Env.prime(inputs)).isZero()) {
System.out.println("Environment safety violation detected with given inputs. Trying to continue with execution");
}
BDD next = jitController.next(currentState, inputs);
if (next.isZero()) {
throw new IllegalArgumentException("The inputs are a safety violation for the environment and it is impossible for the system to recover");
}
return next;
}
@Override
public void init(BDD currentState) {
if (jitController.getJitContext().getEnvIni().and(currentState).isZero()) {
System.out.println("Environment safety violation detected with given inputs. Trying to continue with execution");
}
jitController.init(currentState);
}
@Override
public void saveState() {
this.controller.saveState();
}
@Override
public void loadState() {
this.controller.loadState();
}
@Override
public BDD succ(BDD from) {
return jitController.succ(from);
}
@Override
public BDD pred(BDD to) {
return jitController.pred(to);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.gamemodel.PlayerModule;
public abstract class GameSolver {
protected GameModel model;
protected PlayerModule env;
protected PlayerModule sys;
public GameSolver(GameModel m) {
this.model = m;
env = m.getEnv();
sys = m.getSys();
}
/**
* check whether player wins
*
* @return
*/
abstract public boolean checkRealizability();
abstract public void free();
/**
* check whether the system player wins from all initial states if <code>winSys</code> are its winning states
*
* @param winSys
* @return
*/
public boolean sysWinAllInitial(BDD winSys) {
BDD sysWin = winSys.and(sys.initial());
BDD result = env.initial().id().impWith(sysWin.exist(sys.moduleUnprimeVars()))
.forAll(env.moduleUnprimeVars());
sysWin.free();
boolean allIni = result.isOne();
result.free();
return allIni;
}
/**
* check whether the environment player wins if <code>win</code> are the winning states
*
* @param winEnv
* @return
*/
public boolean envWinAllInitial(BDD winEnv) {
BDD envWin = env.initial().id().andWith(sys.initial().id().impWith(winEnv).forAll(sys.moduleUnprimeVars()));
boolean winSomeIni = !envWin.isZero();
envWin.free();
return winSomeIni;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinputtrans.translator;
import tau.smlab.syntech.gameinput.model.Constraint;
import tau.smlab.syntech.gameinput.model.GameInput;
import tau.smlab.syntech.gameinput.spec.InExpSpec;
import tau.smlab.syntech.gameinput.spec.Operator;
import tau.smlab.syntech.gameinput.spec.PrimitiveValue;
import tau.smlab.syntech.gameinput.spec.Spec;
import tau.smlab.syntech.gameinput.spec.SpecExp;
import tau.smlab.syntech.gameinput.spec.SpecRegExp;
public class TemporalInTranslator implements Translator {
@Override
public void translate(GameInput input) {
// guarantees
for (Constraint c : input.getSys().getConstraints()) {
c.setSpec(replaceInOperator(c.getSpec(), c.getTraceId()));
}
// assumptions
for (Constraint c : input.getEnv().getConstraints()) {
c.setSpec(replaceInOperator(c.getSpec(), c.getTraceId()));
}
}
private Spec replaceInOperator(Spec spec, int traceId) {
if (spec instanceof SpecRegExp) {
SpecRegExp regexpSpec = (SpecRegExp)spec;
Spec predicate = regexpSpec.getPredicate();
if (predicate instanceof InExpSpec) {
InExpSpec inSpec = (InExpSpec) predicate;
regexpSpec.setPredicate(trsanlateInOperator(inSpec));
return regexpSpec;
}
}
else if (spec instanceof InExpSpec) {
return trsanlateInOperator((InExpSpec)spec);
}
else if (spec instanceof SpecExp) {
SpecExp specExp = (SpecExp) spec;
for (int i = 0; i < specExp.getChildren().length; i++) {
specExp.getChildren()[i] = replaceInOperator(specExp.getChildren()[i], traceId);
}
}
return spec;
}
private Spec trsanlateInOperator(InExpSpec inSpec) {
Operator mainOp = Operator.OR;
if (inSpec.isNot()) {
mainOp = Operator.AND;
}
SpecExp firstEqualExp = new SpecExp(Operator.EQUALS, inSpec.getVariable(), new PrimitiveValue(inSpec.getSetOfvalues().get(0)));
SpecExp translatedSpec = inSpec.isNot() ? new SpecExp(Operator.NOT, firstEqualExp) : firstEqualExp;
for (int i = 1; i < inSpec.getSetOfvalues().size(); i++) {
String value_element = inSpec.getSetOfvalues().get(i);
SpecExp equalExp = new SpecExp(Operator.EQUALS, inSpec.getVariable(), new PrimitiveValue(value_element));
SpecExp finalExp = inSpec.isNot() ? new SpecExp(Operator.NOT, equalExp) : equalExp;
translatedSpec = new SpecExp(mainOp, translatedSpec, finalExp);
}
return translatedSpec;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// BDDFactoryIntImpl.java, created Jul 16, 2006 2:59:55 PM by jwhaley
// Copyright (C) 2004-2006 <NAME> <<EMAIL>>
// Licensed under the terms of the GNU LGPL; see COPYING for details.
package net.sf.javabdd;
import java.util.Collection;
import java.util.Iterator;
/**
* A shared superclass for BDD factories that refer to BDDs as ints.
*
* @author jwhaley
* @version $Id: BDDFactoryIntImpl.java,v 1.2 2009/10/18 19:30:54 uid228351 Exp $
*/
public abstract class BDDFactoryIntImpl extends BDDFactory {
protected abstract void addref_impl(/* bdd */int v);
protected abstract void delref_impl(/* bdd */int v);
protected abstract /* bdd */int zero_impl();
protected abstract /* bdd */int one_impl();
protected /* bdd */int universe_impl() {
return one_impl();
}
protected abstract /* bdd */int invalid_bdd_impl();
protected abstract int var_impl(/* bdd */int v);
protected abstract int level_impl(/* bdd */int v);
protected abstract /* bdd */int low_impl(/* bdd */int v);
protected abstract /* bdd */int high_impl(/* bdd */int v);
protected abstract /* bdd */int ithVar_impl(int var);
protected abstract /* bdd */int nithVar_impl(int var);
protected abstract /* bdd */int makenode_impl(int lev, /* bdd */int lo, /* bdd */int hi);
protected abstract /* bdd */int ite_impl(/* bdd */int v1, /* bdd */int v2, /* bdd */int v3);
protected abstract /* bdd */int apply_impl(/* bdd */int v1, /* bdd */int v2, BDDOp opr);
protected abstract /* bdd */int not_impl(/* bdd */int v1);
protected abstract /* bdd */int applyAll_impl(/* bdd */int v1, /* bdd */int v2, BDDOp opr, /* bdd */int v3);
protected abstract /* bdd */int applyEx_impl(/* bdd */int v1, /* bdd */int v2, BDDOp opr, /* bdd */int v3);
protected abstract /* bdd */int applyUni_impl(/* bdd */int v1, /* bdd */int v2, BDDOp opr, /* bdd */int v3);
protected abstract /* bdd */int compose_impl(/* bdd */int v1, /* bdd */int v2, int var);
protected abstract /* bdd */int constrain_impl(/* bdd */int v1, /* bdd */int v2);
protected abstract /* bdd */int restrict_impl(/* bdd */int v1, /* bdd */int v2);
protected abstract /* bdd */int simplify_impl(/* bdd */int v1, /* bdd */int v2);
protected abstract /* bdd */int support_impl(/* bdd */int v);
protected abstract /* bdd */int exist_impl(/* bdd */int v1, /* bdd */int v2);
protected abstract /* bdd */int forAll_impl(/* bdd */int v1, /* bdd */int v2);
protected abstract /* bdd */int unique_impl(/* bdd */int v1, /* bdd */int v2);
protected abstract /* bdd */int replace_impl(/* bdd */int v, BDDPairing p);
protected abstract /* bdd */int veccompose_impl(/* bdd */int v, BDDPairing p);
protected abstract int nodeCount_impl(/* bdd */int v);
protected abstract double pathCount_impl(/* bdd */int v);
protected abstract double satCount_impl(/* bdd */int v);
protected abstract int nodeCount_impl2(/* bdd */int[] v);
protected abstract int[] varProfile_impl(/* bdd */int v);
protected abstract void printTable_impl(/* bdd */int v);
public class IntBDD extends AbstractBDD {
protected /* bdd */int v;
protected IntBDD(/* bdd */int v) {
this.v = v;
addref_impl(v);
}
public BDD apply(BDD that, BDDOp opr) {
return makeBDD(apply_impl(v, unwrap(that), opr));
}
public BDD applyAll(BDD that, BDDOp opr, BDDVarSet var) {
return makeBDD(applyAll_impl(v, unwrap(that), opr, unwrap(var)));
}
public BDD applyEx(BDD that, BDDOp opr, BDDVarSet var) {
return makeBDD(applyEx_impl(v, unwrap(that), opr, unwrap(var)));
}
public BDD applyUni(BDD that, BDDOp opr, BDDVarSet var) {
return makeBDD(applyUni_impl(v, unwrap(that), opr, unwrap(var)));
}
public BDD applyWith(BDD that, BDDOp opr) {
/* bdd */int v2 = unwrap(that);
/* bdd */int v3 = apply_impl(v, v2, opr);
addref_impl(v3);
delref_impl(v);
if (this != that)
that.free();
v = v3;
return this;
}
public BDD compose(BDD g, int var) {
return makeBDD(compose_impl(v, unwrap(g), var));
}
public BDD constrain(BDD that) {
return makeBDD(constrain_impl(v, unwrap(that)));
}
public boolean equals(BDD that) {
if (that == null) {
return false;
}
return v == unwrap(that);
}
public BDD exist(BDDVarSet var) {
return makeBDD(exist_impl(v, unwrap(var)));
}
public BDD forAll(BDDVarSet var) {
return makeBDD(forAll_impl(v, unwrap(var)));
}
public void free() {
delref_impl(v);
v = invalid_bdd_impl();
}
public BDDFactory getFactory() {
return BDDFactoryIntImpl.this;
}
public int hashCode() {
return v;
}
public BDD high() {
return makeBDD(high_impl(v));
}
public BDD id() {
return makeBDD(v);
}
public boolean isOne() {
return v == one_impl();
}
public boolean isUniverse() {
return v == universe_impl();
}
public boolean isZero() {
return v == zero_impl();
}
public BDD ite(BDD thenBDD, BDD elseBDD) {
return makeBDD(ite_impl(v, unwrap(thenBDD), unwrap(elseBDD)));
}
public BDD low() {
return makeBDD(low_impl(v));
}
public int level() {
return level_impl(v);
}
public int nodeCount() {
return nodeCount_impl(v);
}
public BDD not() {
return makeBDD(not_impl(v));
}
public double pathCount() {
return pathCount_impl(v);
}
public BDD replace(BDDPairing pair) {
return makeBDD(replace_impl(v, pair));
}
public BDD replaceWith(BDDPairing pair) {
/* bdd */int v3 = replace_impl(v, pair);
addref_impl(v3);
delref_impl(v);
v = v3;
return this;
}
public BDD restrict(BDD var) {
return makeBDD(restrict_impl(v, unwrap(var)));
}
public BDD restrictWith(BDD that) {
/* bdd */int v2 = unwrap(that);
/* bdd */int v3 = restrict_impl(v, v2);
addref_impl(v3);
delref_impl(v);
if (this != that)
that.free();
v = v3;
return this;
}
public double satCount() {
return satCount_impl(v);
}
public BDD satOne(BDDVarSet var) {
BDDIterator it = new BDDIterator(this, var);
BDD one = it.nextBDD();
it.free();
return one;
//original implementation: return makeBDD(satOne_impl(v, unwrap(var)));
}
public BDD simplify(BDDVarSet d) {
return makeBDD(simplify_impl(v, unwrap(d)));
}
public BDDVarSet support() {
return makeBDDVarSet(support_impl(v));
}
public BDD unique(BDDVarSet var) {
return makeBDD(unique_impl(v, unwrap(var)));
}
public int var() {
return var_impl(v);
}
public int[] varProfile() {
return varProfile_impl(v);
}
public BDD veccompose(BDDPairing pair) {
return makeBDD(veccompose_impl(v, pair));
}
public BDDVarSet toVarSet() {
return makeBDDVarSet(v);
}
@Override
public boolean isFree() {
return this.v == invalid_bdd_impl();
}
}
protected IntBDD makeBDD(/* bdd */int v) {
return new IntBDD(v);
}
protected static final /* bdd */int unwrap(BDD b) {
return ((IntBDD) b).v;
}
protected static final /* bdd */int[] unwrap(Collection<BDD> c) {
/* bdd */int[] result = new /* bdd */int[c.size()];
int k = -1;
for (Iterator<BDD> i = c.iterator(); i.hasNext();) {
result[++k] = ((IntBDD) i.next()).v;
}
return result;
}
public class IntBDDVarSet extends BDDVarSet {
/* bdd */int v;
protected IntBDDVarSet(/* bdd */int v) {
this.v = v;
addref_impl(v);
}
public boolean equals(BDDVarSet that) {
return v == unwrap(that);
}
public void free() {
delref_impl(v);
v = invalid_bdd_impl();
}
public BDDFactory getFactory() {
return BDDFactoryIntImpl.this;
}
public int hashCode() {
return v;
}
public BDDVarSet id() {
return makeBDDVarSet(v);
}
public BDDVarSet intersectWith(BDDVarSet b) {
BDDVarSet res = intersect(b);
this.free();
this.v = res.hashCode();
return this;
}
public boolean isEmpty() {
return v == one_impl();
}
public int size() {
int result = 0;
for (/* bdd */int p = v; p != one_impl(); p = high_impl(p)) {
if (p == zero_impl())
throw new BDDException("varset contains zero");
++result;
}
return result;
}
public int[] toArray() {
int[] result = new int[size()];
int k = -1;
for (/* bdd */int p = v; p != one_impl(); p = high_impl(p)) {
result[++k] = var_impl(p);
}
return result;
}
public BDD toBDD() {
return makeBDD(v);
}
public int[] toLevelArray() {
int[] result = new int[size()];
int k = -1;
for (int p = v; p != one_impl(); p = high_impl(p)) {
result[++k] = level_impl(p);
}
return result;
}
protected int do_unionvar(int v, int var) {
return apply_impl(v, ithVar_impl(var), and);
}
protected int do_union(int v1, int v2) {
return apply_impl(v1, v2, and);
}
public BDDVarSet union(BDDVarSet b) {
return makeBDDVarSet(do_union(v, unwrap(b)));
}
public BDDVarSet union(int var) {
return makeBDDVarSet(do_unionvar(v, var));
}
public BDDVarSet unionWith(BDDVarSet b) {
/* bdd */int v2 = unwrap(b);
/* bdd */int v3 = do_union(v, v2);
addref_impl(v3);
delref_impl(v);
if (this != b)
b.free();
v = v3;
return this;
}
public BDDVarSet unionWith(int var) {
/* bdd */int v3 = do_unionvar(v, var);
addref_impl(v3);
delref_impl(v);
v = v3;
return this;
}
}
public class IntZDDVarSet extends IntBDDVarSet {
protected IntZDDVarSet(/* bdd */int v) {
super(v);
}
protected int do_intersect(int v1, int v2) {
if (v1 == one_impl())
return v2;
if (v2 == one_impl())
return v1;
int l1, l2;
l1 = level_impl(v1);
l2 = level_impl(v2);
for (;;) {
if (v1 == v2)
return v1;
if (l1 < l2) {
v1 = high_impl(v1);
if (v1 == one_impl())
return v2;
l1 = level_impl(v1);
} else if (l1 > l2) {
v2 = high_impl(v2);
if (v2 == one_impl())
return v1;
l2 = level_impl(v2);
} else {
int k = do_intersect(high_impl(v1), high_impl(v2));
addref_impl(k);
int result = makenode_impl(l1, zero_impl(), k);
delref_impl(k);
return result;
}
}
}
protected int do_union(int v1, int v2) {
if (v1 == v2)
return v1;
if (v1 == one_impl())
return v2;
if (v2 == one_impl())
return v1;
int l1, l2;
l1 = level_impl(v1);
l2 = level_impl(v2);
int vv1 = v1, vv2 = v2, lev = l1;
if (l1 <= l2)
vv1 = high_impl(v1);
if (l1 >= l2) {
vv2 = high_impl(v2);
lev = l2;
}
int k = do_union(vv1, vv2);
addref_impl(k);
int result = makenode_impl(lev, zero_impl(), k);
delref_impl(k);
return result;
}
protected int do_unionvar(int v, int var) {
return do_unionlevel(v, var2Level(var));
}
private int do_unionlevel(int v, int lev) {
if (v == one_impl())
return makenode_impl(lev, zero_impl(), one_impl());
int l = level_impl(v);
if (l == lev) {
return v;
} else if (l > lev) {
return makenode_impl(lev, zero_impl(), v);
} else {
int k = do_unionlevel(high_impl(v), lev);
addref_impl(k);
int result = makenode_impl(l, zero_impl(), k);
delref_impl(k);
return result;
}
}
}
protected IntBDDVarSet makeBDDVarSet(/* bdd */int v) {
if (isZDD()) {
return new IntZDDVarSet(v);
} else {
return new IntBDDVarSet(v);
}
}
protected static final /* bdd */int unwrap(BDDVarSet b) {
return ((IntBDDVarSet) b).v;
}
public class IntBDDBitVector extends BDDBitVector {
protected IntBDDBitVector(int bitnum) {
super(bitnum);
}
public BDDFactory getFactory() {
return BDDFactoryIntImpl.this;
}
}
public BDD ithVar(/* bdd */int var) {
return makeBDD(ithVar_impl(var));
}
public BDD nithVar(/* bdd */int var) {
return makeBDD(nithVar_impl(var));
}
public int nodeCount(Collection<BDD> r) {
return nodeCount_impl2(unwrap(r));
}
public BDD one() {
return makeBDD(one_impl());
}
public BDD universe() {
return makeBDD(universe_impl());
}
public BDDVarSet emptySet() {
return makeBDDVarSet(one_impl());
}
public void printTable(BDD b) {
printTable_impl(unwrap(b));
}
public BDD zero() {
return makeBDD(zero_impl());
}
public void done() {
}
protected void finalize() throws Throwable {
super.finalize();
this.done();
}
protected /* bdd */int[] to_free = new /* bdd */int[8];
protected /* bdd */int to_free_length = 0;
public void deferredFree(int v) {
if (v == invalid_bdd_impl())
return;
synchronized (to_free) {
if (to_free_length == to_free.length) {
/* bdd */int[] t = new /* bdd */int[to_free.length * 2];
System.arraycopy(to_free, 0, t, 0, to_free.length);
to_free = t;
}
to_free[to_free_length++] = v;
}
}
public void handleDeferredFree() {
synchronized (to_free) {
while (to_free_length > 0) {
delref_impl(to_free[--to_free_length]);
}
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.simple;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.games.GameMemory;
import tau.smlab.syntech.games.GameSolver;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.lib.FixPoint;
/**
* This is an implementation of a generalized coBuchi game. <br>
* The objective of the system is to prevent the justices of the environment.
*
* <li>implements a check whether we reached a fixed point early</li>
* <li>computes all winning states</li>
*/
public class CoBuchiGame extends GameSolver {
protected GameMemory mem;
public GameMemory getMem() {
return mem;
}
public CoBuchiGame(GameModel model) {
super(model);
mem = new GameMemory();
}
@Override
public boolean checkRealizability() {
BDD Z = Env.FALSE();
int iterationsWithoutGain = 0;
while (iterationsWithoutGain < env.justiceNum()) {
for (int i = 0; i < env.justiceNum(); i++) {
BDD toPrevWin = env.yieldStates(sys, Z).orWith(env.justiceAt(i).not());
BDD X = toPrevWin.id(); // instead of TRUE start here (at most what is winning now)
FixPoint fX = new FixPoint(true);
while (fX.advance(X)) {
X = toPrevWin.id().andWith(env.yieldStates(sys, X));
}
BDD newZ = Z.or(X);
if (newZ.equals(Z)) {
iterationsWithoutGain++;
} else {
iterationsWithoutGain = 0;
}
Z.free();
toPrevWin.free();
Z = newZ;
}
}
mem.setWin(Z);
return sysWinAllInitial();
}
@Override
public void free() {
mem.free();
}
public boolean sysWinAllInitial() {
return this.sysWinAllInitial(mem.getWin());
}
public BDD sysWinningStates() {
return mem.getWin();
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.jits;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;
/**
* A class for the execution of symbolic controllers in a Just-in-time fashion
* @author ilia
*
*/
public class BasicJitControllerImplC implements JitController {
private BDD transitions;
private BDD initial;
@Override
public BDD next(BDD currentState, BDD inputs) {
return (Env.TRUE().getFactory()).nextStatesJits(currentState, inputs, Env.allCouplesPairing(), Env.globalUnprimeVars());
}
@Override
public void load(String folder, String name, Map<String, String[]> sysVars, Map<String, String[]> envVars) {
try {
String prefix;
if (name == null) {
prefix = folder + File.separator;
} else {
prefix = folder + File.separator + name + ".";
}
BufferedReader sizesReader = new BufferedReader(new FileReader(prefix + "sizes"));
int n = Integer.parseInt(sizesReader.readLine());
int m = Integer.parseInt(sizesReader.readLine());
int[] ranks = new int[n];
for (int j = 0; j < n; j++) {
ranks[j] = Integer.parseInt(sizesReader.readLine());
}
sizesReader.close();
System.out.println(Env.TRUE().getFactory().getNodeNum() + " - Read Sizes");
int[] jindices = Env.getVar("util_Jn").getDomain().vars();
int[] iindices = Env.getVar("util_In").getDomain().vars();
int[] rindices = Env.getVar("util_Rn").getDomain().vars();
int utilindex = Env.getVar("util_0").getDomain().vars()[0];
// Extract justices
BDD justices = Env.loadBDD(prefix + "justice.bdd");
(Env.TRUE().getFactory()).loadJusticesJits(justices, jindices, iindices, utilindex, n, m);
justices.free();
System.out.println(Env.TRUE().getFactory().getNodeNum() + " - Loaded Justice BDD");
// Extract trans and init
BDD trans = Env.loadBDD(prefix + "trans.bdd");
(Env.TRUE().getFactory()).loadTransJits(trans, jindices, iindices, utilindex);
trans.free();
System.out.println(Env.TRUE().getFactory().getNodeNum() + " - Loaded Transition BDD");
// Extract X from fixpoints BDD
BDD fixpoints = Env.loadBDD(prefix + "fixpoints.bdd");
(Env.TRUE().getFactory()).loadFixpointsJits(fixpoints, jindices, iindices, rindices, ranks, Env.allCouplesPairing(), Env.globalPrimeVars());
fixpoints.free();
System.out.println(Env.TRUE().getFactory().getNodeNum() + " - Loaded Fixed-Points BDD");
initial = (Env.TRUE().getFactory()).getInitialJits();
transitions = (Env.TRUE().getFactory()).getTransitionsJits();
} catch (IOException e) {
e.printStackTrace();
}
// Delete vars even though they are not really removed from bdd engine.
// At least they won't show up in next states enumeration
Env.deleteVar("util_In");
Env.deleteVar("util_Jn");
Env.deleteVar("util_Rn");
Env.deleteVar("util_0");
}
@Override
public List<BDD> getJusticeGar() {
return null;
}
@Override
public List<BDD> getJusticeAsm() {
return null;
}
@Override
public JitContext getJitContext() {
return null;
}
@Override
public void free() {
(Env.TRUE().getFactory()).freeControllerJits();
}
@Override
public BDD transitions() {
return transitions;
}
@Override
public JitState getJitState() {
return null;
}
@Override
public BDD initial() {
return initial;
}
@Override
public void init(BDD currentState) {
int result = (Env.TRUE().getFactory()).initControllerJits(currentState, Env.allCouplesPairing());
if (result == -1) {
throw new IllegalArgumentException("Illegal rank reached. Probably initial environment inputs violate the initial assumptions");
}
}
@Override
public void saveState() {
}
@Override
public void loadState() {
}
@Override
public BDD succ(BDD from) {
return null;
}
@Override
public BDD pred(BDD to) {
return null;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.bddgenerator.sfa.regexp;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.bddgenerator.BDDGenerator;
import tau.smlab.syntech.gameinput.spec.SpecRegExp;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.sfa.SFA;
import tau.smlab.syntech.sfa.SFAs;
/**
*
* A class for transforming regular expressions into Symbolic finite automatons (SFAs) using
* only symbolic BDD operations. This implementation adapts Thompson's construction algorithm.
*
* @author <NAME>
*
*/
public class SymRegExpSFAGenerator implements RegExpSFAGenerator {
private SpecRegExp specRegExp; //the regular expression
private SFA sfa; //the SFA that would be created
private int traceId; //the trace ID of the constraint where the regular expression appears
private boolean isPredicate; //indicates whether the regular expression defines a "predicate" language, i.e., a language that only consists
//of words of length 1 that may be characterized by a Boolean predicate/assertion
/**
*
* @param specRegExp the regular expression
* @param traceId
*/
public SymRegExpSFAGenerator(SpecRegExp specRegExp, int traceId) {
this.traceId = traceId;
this.isPredicate = false;
this.specRegExp = specRegExp;
}
@Override
public SFA generateRegExpDSfa(boolean minimal) {
generateRegExpSfa();
SFA resDSfa;
if(minimal) {
resDSfa = this.sfa.minimize();
}
else {
resDSfa = this.sfa.determinize();
}
this.sfa.free();
this.sfa = resDSfa;
return this.sfa;
}
@Override
public SFA generateRegExpSfa() {
if(this.sfa == null) {
SFA oFSfa = this.buildRegExpOFSfa();
this.sfa = oFSfa.eliminateEpsTrans();
this.sfa.removeDeadStates();
oFSfa.free();
}
return this.sfa;
}
@Override
public void freeRegExpSfa() {
if(this.sfa != null) {
this.sfa.free();
}
this.sfa = null;
}
/**
* Checks whether the Epsilon-SFA of this generator either has been freed or
* has not been created.
*
* @see #generateRegExpSfa()
* @see #free()
*
* @return
*/
public boolean isFree() {
return this.sfa == null;
}
/*
*
*
*
*
*
*
*
*
* Private methods
*
*
*
*
*
*
*
*/
/**
* Returns an OFSFA whose language is that of the regular expression of this generator.
* Note that the returned OFSFA may be non-deterministic and have epsilon transitions.
*
* @return
*/
private SFA buildRegExpOFSfa() {
if(this.specRegExp == null) {
throw new RegExpSFAGeneratorException("The regular expression of this transformer is null and thus cannot be translated to an SFA",
this.traceId);
}
if(this.specRegExp.isEmptyString()) { //regExp = '()'
return SFAs.emptyWordOFSfa();
}
if(this.specRegExp.isTrueBooleanConst()) { //regExp = 'TRUE'
this.isPredicate = true;
return SFAs.predicateOFSfa(Env.TRUE());
}
if(this.specRegExp.isFalseBooleanConst()) { //regExp = 'FALSE'
this.isPredicate = true;
return SFAs.predicateOFSfa(Env.FALSE());
}
if(this.specRegExp.isVariable()) { //regExp = 'var in {set of values}'
String varName = this.specRegExp.getVariableReferenceName();
BDD currValue;
BDD valuesAssrt = Env.FALSE();
for(String value : this.specRegExp.getValues()) {
currValue = Env.getBDDValue(varName, value);
if(currValue == null) {
throw new RegExpSFAGeneratorException("Unable to transform the regular expression " + this.specRegExp + " into an Epsilon-SFA since "
+ value + " is not in the domain of the variable " + varName, this.traceId);
}
valuesAssrt.orWith(currValue.id());
}
this.isPredicate = true;
return SFAs.predicateOFSfa(valuesAssrt);
}
if(this.specRegExp.isPredicate()) { //regExp = 'Boolean term (i.e., assertion)'
this.isPredicate = true;
BDD predicate = BDDGenerator.createBdd(this.specRegExp.getPredicate(), this.traceId);
return SFAs.predicateOFSfa(predicate);
}
if(!this.specRegExp.hasLeft()) {
throw new RegExpSFAGeneratorException("Unable to transform the regular expression " + this.specRegExp + " into an Epsilon-SFA as it is expected to have a left sub-expression", this.traceId);
}
//Perform a recursive call on the left subexpression (might be the only subexpression in case this is an unary expression)
SymRegExpSFAGenerator leftSfaGenerator = new SymRegExpSFAGenerator(this.specRegExp.getLeft(), this.traceId);
SFA leftOFSfa = leftSfaGenerator.buildRegExpOFSfa();
if(this.specRegExp.isRepetition()) {
int leastRepNum = this.specRegExp.getQuantifier().getLeastRepetitionsNum();
switch(this.specRegExp.getQuantifierType()) {
case AT_LEAST: //'{n,}'
return SFAs.nOrMoreOFSfa(leftOFSfa, leastRepNum);
case EXACT_REPETITION: //'{n}'
return SFAs.exactNOFSfa(leftOFSfa, leastRepNum);
case ONE_OR_MORE: //'+'
return SFAs.oneOrMoreOFSfa(leftOFSfa);
case RANGE: //'{n,m}'
return SFAs.nToMOFSfa(leftOFSfa, leastRepNum, this.specRegExp.getQuantifier().getMaxRepetitionsNum());
case ZERO_OR_MORE: //'*'
return SFAs.kleeneClosureOFSfa(leftOFSfa);
case ZERO_OR_ONE: //'?'
return SFAs.zeroOrOneOFSfa(leftOFSfa);
default:
throw new RegExpSFAGeneratorException("Unable to transform the repetition regular expression " + this.specRegExp + " into an Epsilon-SFA since the quantifier " +
this.specRegExp.getQuantifierType() + " is not supported", this.traceId);
}
}
if(this.specRegExp.isComplementation()) {
return SFAs.complementOFSfa(leftOFSfa);
}
if(!this.specRegExp.hasRight()) {
throw new RegExpSFAGeneratorException("Unable to transform the unary regular expression " + this.specRegExp + " into an Epsilon-SFA. This regular expression is not supported", this.traceId);
}
//Perform a recursive call on the right subexpression
SymRegExpSFAGenerator rightSfaGenerator = new SymRegExpSFAGenerator(this.specRegExp.getRight(), this.traceId);
SFA rightOFSfa = rightSfaGenerator.buildRegExpOFSfa();
if(this.specRegExp.isUnion()) {
if(leftSfaGenerator.isPredicate && rightSfaGenerator.isPredicate) {
this.isPredicate = true;
return SFAs.unionPredicateOFSfa(leftOFSfa, rightOFSfa);
}
else {
return SFAs.unionOFSfa(leftOFSfa, rightOFSfa);
}
}
if(this.specRegExp.isIntersection()) {
if(leftSfaGenerator.isPredicate && rightSfaGenerator.isPredicate) {
this.isPredicate = true;
return SFAs.productPredicateOFSfa(leftOFSfa, rightOFSfa);
}
else {
return SFAs.productOFSfa(leftOFSfa, rightOFSfa);
}
}
if(this.specRegExp.isConcat()) {
return SFAs.concatOFSfa(leftOFSfa, rightOFSfa);
}
throw new RegExpSFAGeneratorException("Unable to transform the binary regular expression " + this.specRegExp + " into an Epsilon-SFA. This regular expression is not supported", this.traceId);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinput.model;
import java.util.ArrayList;
import java.util.List;
import tau.smlab.syntech.gameinput.spec.Spec;
import tau.smlab.syntech.gameinput.spec.SpecRegExp;
/**
*
* @author <NAME>
*
*/
public class ExistentialConstraint extends Constraint {
/**
*
*/
private static final long serialVersionUID = -336461559302985367L;
private List<Spec> specs;
private boolean isRegExp; //Whether this existential constraint is of the form 'GEF regExp'
private SpecRegExp regExp; //The regular expression of this existential constraint
/**
*
* Returns a new existential constraint of the form 'GE (F(g1 and F (g2 and F (g3 and ..))))'
* where each gi is a {@link tau.smlab.syntech.gameinput.spec.Spec} object (represents an assertion). The returned
* existential constraint has an empty list of assertions gi.
*
* @param name
* @param traceId
*/
public ExistentialConstraint(String name, int traceId) {
super(Kind.EXISTS, null, name, traceId);
this.isRegExp = false;
this.specs = new ArrayList<>();
}
/**
*
* Return a new existential constraint of the form 'GEF {@code regExp}'.
*
* @param name
* @param regExp the regular expression
* @param traceId
*/
public ExistentialConstraint(String name, SpecRegExp regExp, int traceId) {
super(Kind.EXISTS, null, name, traceId);
this.isRegExp = true;
this.regExp = regExp;
}
public boolean isRegExp() {
return this.isRegExp;
}
@Override
public Kind getKind() {
return Kind.EXISTS;
}
public List<Spec> getSpecs() {
return this.specs;
}
public int getSize() {
return isRegExp ? 0 : this.specs.size();
}
public SpecRegExp getRegExp() {
return this.regExp;
}
/**
*
* Adds the specified {@code spec} to the list of existential assertions.
*
* @param spec the existential assertion to add
* @return true if {@code spec} has been successfully added to the list
*/
public boolean addSpec(Spec spec) {
if(!isRegExp) {
return this.specs.add(spec);
}
return false;
}
/**
*
* Returns the spec at the specified position in the list of existential assertions.
* If the specified position is out of bounds, {@code null} is returned.
*
* @param specIdx the position
* @return
*/
public Spec getSpec(int specIdx) {
if(!isRegExp && specIdx >= 0 && specIdx < specs.size()) {
return this.specs.get(specIdx);
}
return null;
}
/**
*
* Replaces the spec at the specified position in the list of existential assertions with the specified spec.
*
* @param specIdx the position
* @param spec the spec
* @return the spec previously at the specified position or {@code null} if the specified position is out of bounds
*/
public Spec replaceSpec(int specIdx, Spec spec) {
if(!isRegExp && specIdx >= 0 && specIdx < specs.size()) {
return this.specs.set(specIdx, spec);
}
return null;
}
/**
*
* Replaces the regular expression of this existential constraint with the specified one.
*
* @param regExp the new regular expression
* @return the previous regular expression
*/
public SpecRegExp replaceRegExp(SpecRegExp regExp) {
if(isRegExp) {
SpecRegExp replacedRegExp = this.regExp;
this.regExp = regExp;
return replacedRegExp;
}
return null;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.bddgenerator.sfa.trigger;
import tau.smlab.syntech.bddgenerator.BDDTranslationException;
import tau.smlab.syntech.gameinput.model.TriggerConstraint;
import tau.smlab.syntech.sfa.SFA;
/**
*
* Use a {@link TriggerSFAGenerator} to translate triggers (instances of {@link TriggerConstraint})
* to equivalent {@link SFA}s.
*
* @author <NAME>
*
*/
public interface TriggerSFAGenerator {
/**
*
* An exception thrown during translations of triggers (instances of {@link TriggerConstraint}) to {@link SFA}s.
*
*/
public static class TriggerSFAGeneratorException extends BDDTranslationException {
/**
*
*/
private static final long serialVersionUID = 1780939868279839674L;
public TriggerSFAGeneratorException() {
super();
}
public TriggerSFAGeneratorException(String string, int traceId) {
super(string, traceId);
}
}
/**
*
* Returns a deterministic and complete {@link SFA} whose language is that of the trigger associated with this generator.
*
* @return
*/
public SFA generateTriggerSfa();
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.ui.jobs;
import java.io.PrintStream;
import org.eclipse.ui.console.IOConsoleOutputStream;
import tau.smlab.syntech.bddgenerator.energy.BDDEnergyReduction;
import tau.smlab.syntech.games.controller.enumerate.ConcreteControllerConstruction;
import tau.smlab.syntech.games.controller.enumerate.printers.MAAMinimizeAutomatonPrinter;
import tau.smlab.syntech.games.controller.enumerate.printers.SimpleTextPrinter;
import tau.smlab.syntech.games.rabin.RabinConcreteControllerConstruction;
import tau.smlab.syntech.games.rabin.RabinGame;
import tau.smlab.syntech.jtlv.BDDPackage;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.ModuleVariableException;
import tau.smlab.syntech.ui.preferences.PreferencePage;
public class CounterStrategyJob extends SyntechJob {
@Override
protected void doWork() {
if (PreferencePage.getBDDPackageSelection().equals(BDDPackage.CUDD_ADD) && model.getWeights() != null) {
BDDEnergyReduction.reduce(model.getSys(), model.getWeights(), gi.getEnergyBound(), PreferencePage.isGroupVarSelection());
}
// play actual game
RabinGame rabin = new RabinGame(model);
if (rabin.checkRealizability()) {
this.isRealizable = false;
if(model.getWeights() != null) {
try {
BDDEnergyReduction.updateSysIniTransWithEngConstraintsForCounterStrategy(model, gi.getEnergyBound());
} catch (ModuleVariableException e) {
e.printStackTrace();
}
}
Env.disableReorder();
ConcreteControllerConstruction cc = new RabinConcreteControllerConstruction(rabin.getMem(), model);
IOConsoleOutputStream cout = console.newOutputStream();
PrintStream out = new PrintStream(cout);
try {
if ("CMP".equals(PreferencePage.getConcreteControllerFormat())) {
MAAMinimizeAutomatonPrinter.REMOVE_DEAD_STATES = false;
new MAAMinimizeAutomatonPrinter(model).printController(out, cc.calculateConcreteController());
} else if ("JTLV".equals(PreferencePage.getConcreteControllerFormat())) {
new SimpleTextPrinter().printController(out, cc.calculateConcreteController());
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
this.isRealizable = true;
printToConsole("The selected specification is realizable.");
}
model.free();
rabin.free();
}
@Override
public boolean needsBound() {
return true;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.checks.ddmin;
import java.util.List;
import tau.smlab.syntech.gamemodel.BehaviorInfo;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.gamemodel.util.GameBuilderUtil;
public abstract class DdminRealizableCore extends AbstractDdmin<BehaviorInfo> {
protected GameModel model;
public DdminRealizableCore(GameModel model) {
this.model = model;
}
/**
* This has to be filled by the caller in order to make realizability checks standard and menu opt. sensitive.
* See CoreMenu class
*
* @param gm
* @return
*/
public abstract boolean realizable(GameModel gm);
@Override
protected boolean check(List<BehaviorInfo> part) {
GameBuilderUtil.buildEnv(model, part);
return realizable(model);
}
}<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.modelchecker;
import java.util.HashMap;
import java.util.Set;
import java.util.Vector;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDException;
import net.sf.javabdd.BDDVarSet;
import tau.smlab.syntech.jtlv.CoreUtil;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.ModuleVariableException;
import tau.smlab.syntech.jtlv.env.module.ModuleBDDField;
import tau.smlab.syntech.gamemodel.ModuleException;
import tau.smlab.syntech.gamemodel.PlayerModule;
import tau.smlab.syntech.gameinput.spec.Spec;
import tau.smlab.syntech.gameinput.spec.SpecBDD;
import tau.smlab.syntech.gameinput.spec.SpecExp;
import tau.smlab.syntech.gameinput.spec.Operator;
/**
* <p>
* A checker which knows how to check LTL properties for the given
* ComposedPlayerModule
* </p>
*
*/
public class LTLModelChecker {
private PlayerModule design;
public LTLModelChecker(PlayerModule design) throws ModelCheckException {
if (design == null)
throw new ModelCheckException("Cannot instatiate an LTL Model " + "Checker with a null module.");
this.design = design;
}
/**
*
* @param property
* @return true if property is verified
*/
public boolean modelCheckWithNoCounterExample(Spec property) {
Spec negp = new SpecExp(Operator.NOT, property);
LTLTesterBuilder builder;
try {
builder = new LTLTesterBuilder(negp, true);
PlayerModule composed = design.compose(builder.getTester());
boolean res = checkVerify(builder.getSpec2BDD(property).not(), composed);
return res;
} catch (ModelCheckException e) {
e.printStackTrace();
} catch (ModuleVariableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
private boolean checkVerify(BDD initial_condition, PlayerModule designWithTester) {
// saving to the previous restriction state
BDD initial = designWithTester.initial().id();
designWithTester.conjunctInitial(initial_condition.id());
FeasibilityChecker fsChecker = new FeasibilityChecker();
BDD feas = fsChecker.check(designWithTester);
// the initial_condition seems redundant
if (!feas.and(designWithTester.initial().id()).and(initial_condition).isZero()) {
// returning to the previous restriction state
designWithTester.resetInitial();
designWithTester.conjunctInitial(initial.id());
return false;
}
// returning to the previous restriction state
designWithTester.resetInitial();
designWithTester.conjunctInitial(initial.id());
return true;
}
/**
* <p>
* Given a specification \phi (as a formula in temporal logic) we want to decide
* whether \phi is valid over finite state program P , i.e. whether all the
* computations of the design satisfy \phi. This variant of implementation,
* prints the results to the standard streams.
* </p>
*
* @param property The property to check.
* @throws ModuleVariableException
*/
public void modelCheckStandardOutput(Spec property) {
System.out.println("model checking property: " + property);
try {
this.modelCheck(property);
} catch (ModelCheckException mce) {
System.err.println(mce.toString());
return;
} catch (ModuleVariableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// else - everything is OK.
System.out.println("*** Property is VALID ***");
}
/**
* <p>
* Given a specification \phi (as a formula in temporal logic) we want to decide
* whether \phi is valid over finite state program P , i.e. whether all the
* computations of the design satisfy \phi.
* </p>
*
* @param property The property to check.
* @throws ModelCheckException When the method is initiated with other then
* LTL property.
* @throws CounterExampleException When the property is not valid, a counter
* example is thrown.
* @throws ModuleVariableException
*/
public void modelCheck(Spec property) throws ModelCheckException, CounterExampleException, ModuleVariableException {
Spec negp = new SpecExp(Operator.NOT, property);
LTLTesterBuilder builder = new LTLTesterBuilder(negp, true);
BDD tester_initials = builder.getSpec2BDD(property).not();
BDDVarSet visibleVars = getRelevantVars(design);
visibleVars.unionWith(getRelevantVars(builder.getTester())); // FIXME
visibleVars.unionWith(tester_initials.support().minus(Env.union(builder.getTester().getAuxFields())));
PlayerModule composed = design.compose(builder.getTester());
try {
verify(tester_initials, composed, visibleVars);
// verify(tester_initials, this.design, null);
} catch (CounterExampleException mce) {
throw mce;
}
}
/**
* <p>
* The main procedure for verifying.
* </p>
*
* @param initial_condition
* @param designWithTester
* @param relevantVars
* @throws ModelCheckException
*/
private static void verify(BDD initial_condition, PlayerModule designWithTester, BDDVarSet relevantVars)
throws CounterExampleException {
// saving to the previous restriction state
BDD initial = designWithTester.initial().id();
designWithTester.conjunctInitial(initial_condition.id());
FeasibilityChecker fsChecker = new FeasibilityChecker();
BDD feas = fsChecker.check(designWithTester);
// the initial_condition seems redundant
if (!feas.and(designWithTester.initial()).and(initial_condition).isZero()) {
BDD[] example = extractWithness(feas, designWithTester, relevantVars, fsChecker);
CounterExampleException cee = new CounterExampleException("\n*** Property is NOT VALID ***", example);
// returning to the previous restriction state
designWithTester.resetInitial();
designWithTester.conjunctInitial(initial.id());
throw cee;
}
// returning to the previous restriction state
designWithTester.resetInitial();
designWithTester.conjunctInitial(initial.id());
}
// private static BDDVarSet getRelevantVars(PlayerModule m) {
// BDDVarSet vars = Env.getEmptySet();
// if (m != null) {
// vars.unionWith(m.initial().support());
// vars.unionWith(m.trans().support());
//
// // fairness variables are important to illustrate feasibility.
// for (int i = 0; i < m.justiceNum(); i++) {
// vars.unionWith(m.justiceAt(i).support());
// }
//
// for (ModuleBDDField f : m.getAuxFields()) {
// BDDVarSet v = vars.minus(f.support());
// vars.free();
// vars = v;
// }
// }
// vars.intersectWith(Env.globalUnprimeVars());
// return vars;
// }
private static BDDVarSet getRelevantVars(PlayerModule m) {
BDDVarSet vars = Env.getEmptySet();
if (m != null) {
vars = Env.getEmptySet();
for (ModuleBDDField f : m.getNonAuxFields()) {
if(!f.isPrime()) {
vars.unionWith(f.support().id());
}
}
}
return vars;
}
/**
* <p>
* This is essentially algorithm "Witness", from the article: <NAME>, <NAME>, <NAME>, <NAME>, "Model checking with strong fairness".<br>
* The line numbers are the line numbers of that algorithm. Read the article for
* further details.
* </p>
*
* @param feasible
* @param designWithTester
* @return
*/
private static BDD[] extractWithness(BDD feasible, PlayerModule designWithTester, BDDVarSet relevantVars,
FeasibilityChecker fsChecker) {
BDD temp, fulfill;
// saving the previous restriction state.
BDD trans = designWithTester.trans().id();
// Lines 1-2 are handled by the caller. ("verify")
// Line 3
designWithTester.conjunctTrans(feasible.and(Env.prime(feasible)));
// Line 4
BDD s = CoreUtil.satOne(feasible, designWithTester.moduleUnprimeVars());
// BDD s = feasible.satOne();
// Lines 5-6
while (true) {
temp = designWithTester.allSucc(s.id()).and(designWithTester.allPred(s.id()).not());
if (!temp.isZero())
s = CoreUtil.satOne(temp, designWithTester.moduleUnprimeVars());
// s = temp.satOne();
else
break;
}
// Lines 5-6 : better version.
// temp = tester.allSucc(s).and(tester.allPred(s).not());
// while (!temp.isZero()){
// s = temp.satOne(tester.moduleUnprimeVars(), false);
// temp = tester.allSucc(s).and(tester.allPred(s).not());
// }
// Line 7: Compute MSCS containing s.
BDD feas = designWithTester.allSucc(s.id());
// Line 9
// Find prefix - shortest path from initial state to subgraph feas.
designWithTester.resetTrans();
designWithTester.conjunctTrans(trans.id());
Vector<BDD> prefix = new Vector<BDD>();
BDD[] path = fsChecker.shortestPath(designWithTester, designWithTester.initial(), feas);
for (int i = 0; i < path.length; i++)
prefix.add(path[i]);
// //// Calculate "_period".
// Line 8: This has to come after line 9, because the way TS.tlv
// implements restriction.
designWithTester.conjunctTrans(feasible.and(Env.prime(feas)));
// Line 10
Vector<BDD> period = new Vector<BDD>();
period.add(prefix.lastElement());
// Since the last item of the prefix is the first item of
// the period we don't need to print the last item of the prefix.
temp = prefix.remove(prefix.size() - 1);
// Lines 11-13
for (int i = 0; i < designWithTester.justiceNum(); i++) {
// Line 12, check if j[i] already satisfied
fulfill = Env.FALSE();
for (int j = 0; j < period.size(); j++) {
fulfill = CoreUtil.satOne(period.elementAt(j).and(designWithTester.justiceAt(i)),
designWithTester.moduleUnprimeVars());
// fulfill =
// period.elementAt(j).and(design.justiceAt(i)).satOne();
if (!fulfill.isZero())
break;
}
// Line 13
if (fulfill.isZero()) {
BDD from = period.lastElement();
BDD to = feas.and(designWithTester.justiceAt(i));
path = fsChecker.shortestPath(designWithTester, from, to);
// eliminate the edge since from is already in period
for (int j = 1; j < path.length; j++)
period.add(path[j]);
}
}
// Lines 14-16 - removed - we don't support compassion
/*
* for (int i = 0; i < designWithTester.compassionNum(); i++) { if
* (!feas.and(designWithTester.pCompassionAt(i)).isZero()) { // check if C
* requirement i is already satisfied fulfill = Env.FALSE(); for (int j = 0; j <
* period.size(); j++) { fulfill = period.elementAt(j).and(
* designWithTester.qCompassionAt(i)).satOne(
* designWithTester.moduleUnprimeVars(), false); // fulfill = //
* period.elementAt(j).and(design.qCompassionAt(i)).satOne(); if
* (!fulfill.isZero()) break; }
*
* if (fulfill.isZero()) { BDD from = period.lastElement(); BDD to =
* feas.and(designWithTester.qCompassionAt(i)); path =
* designWithTester.shortestPath(from, to); // eliminate the edge since from is
* already in period for (int j = 1; j < path.length; j++) period.add(path[j]);
* } } }
*/
//
// Close cycle
//
// A period of length 1 may be fair, but it might be the case that
// period[1] is not a successor of itself. The routine path
// will add nothing. To solve this
// case we add another state to _period, now it will be OK since
// period[1] and period[n] will not be equal.
// Line 17, but modified
if (!period.firstElement().and(period.lastElement()).isZero()) {
// The first and last states are already equal, so we do not
// need to extend them to complete a cycle, unless period is
// a degenerate case of length = 1, which is not a successor of
// self.
if (period.size() == 1) {
// Check if _period[1] is a successor of itself.
if (period.firstElement().and(designWithTester.succ(period.firstElement())).isZero()) {
// period[1] is not a successor of itself: Add state to
// period.
period
.add(CoreUtil.satOne(designWithTester.succ(period.firstElement()), designWithTester.moduleUnprimeVars()));
// period.add(design.succ(period.firstElement()).satOne());
// Close cycle.
BDD from = period.lastElement();
BDD to = period.firstElement();
path = fsChecker.shortestPath(designWithTester, from, to);
// eliminate the edges since from and to are already in
// period
for (int i = 1; i < path.length - 1; i++)
period.add(path[i]);
}
}
} else {
BDD from = period.lastElement();
BDD to = period.firstElement();
path = fsChecker.shortestPath(designWithTester, from, to);
// eliminate the edges since from and to are already in period
for (int i = 1; i < path.length - 1; i++)
period.add(path[i]);
}
// Yaniv - the last one is for closing the cycle. He won't be printed.
period.add(period.firstElement());
// There is no need to have the last state of the period
// in the counterexample since it already appears in _period[1]
// if (period.size() > 1)
// temp = period.remove(period.size() -1);
// Copy prefix and period.
prefix.addAll(period);
BDD[] returned_path = new BDD[prefix.size()];
prefix.toArray(returned_path);
// Strip auxiliary variables introduced by tester.
if (relevantVars != null) {
BDDVarSet extraVars = Env.globalVarsMinus(relevantVars);
// BDDVarSet extraVars = Env.globalVarsMinus(relevantVars);
for (int i = 0; i < returned_path.length; i++) {
returned_path[i] = CoreUtil.satOne(returned_path[i], relevantVars).exist(extraVars);
}
}
// returning to the previous restriction state
designWithTester.resetTrans();
designWithTester.conjunctTrans(trans.id());
return returned_path;
}
private static int tester_id = 0;
private static int field_id = 0;
public static class LTLTesterBuilder {
private Spec root;
private PlayerModule tester;
private HashMap<SpecExp, ModuleBDDField> spec2field = new HashMap<SpecExp, ModuleBDDField>();
public LTLTesterBuilder(Spec root_spec, boolean isWeak) throws ModelCheckException, ModuleVariableException {
this.root = root_spec;
if (root == null)
throw new ModelCheckException("Cannot construct a tester for" + "specification: " + root);
this.tester = new PlayerModule();
this.tester.setName("LTLTester_" + (++tester_id));
createAuxVariable(root);
constructModule(root, isWeak);
}
public PlayerModule getTester() {
return this.tester;
}
public BDD getSpec2BDD(Spec root) throws ModelCheckException {
if (root instanceof SpecBDD)
return ((SpecBDD) root).getVal();
// else it is SpecExp (cannot be a SpecCTLRange)
SpecExp se = (SpecExp) root;
Spec[] child = se.getChildren();
Operator op = se.getOperator();
if (op == Operator.NOT)
return getSpec2BDD(child[0]).not();
if (op == Operator.AND)
return getSpec2BDD(child[0]).and(getSpec2BDD(child[1]));
if (op == Operator.OR)
return getSpec2BDD(child[0]).or(getSpec2BDD(child[1]));
if (op == Operator.XOR)
return getSpec2BDD(child[0]).xor(getSpec2BDD(child[1]));
if (op == Operator.IFF)
return getSpec2BDD(child[0]).biimp(getSpec2BDD(child[1]));
if (op == Operator.IMPLIES)
return getSpec2BDD(child[0]).imp(getSpec2BDD(child[1]));
if (op.isLTLOp()) {
ModuleBDDField f = spec2field.get(root);
if ((f != null) && (f.getDomain().size().intValue() == 2))
return f.getDomain().ithVar(1);
}
// something is wrong
throw new ModelCheckException("Failed to find corresponding bdd" + " to specification: " + root.toString());
}
private void createAuxVariable(Spec s) throws ModelCheckException, ModuleVariableException {
if (!(s instanceof SpecExp))
return;
// else
SpecExp se = (SpecExp) s;
try {
String name = "AUX[" + (++field_id) + "]";
ModuleBDDField f = tester.addVar(name, true);
spec2field.put(se, f);
} catch (ModuleException e) {
throw new ModelCheckException("Failed naming the extra " + "auxiliary fields");
}
Spec[] children = se.getChildren();
for (int i = 0; i < children.length; i++) {
createAuxVariable(children[i]);
}
}
private void constructModule(Spec root, boolean isWeak) throws ModelCheckException {
BDD p_c1, p_c2, p_aux;
Set<SpecExp> specifications = spec2field.keySet();
for (SpecExp spec : specifications) {
// TODO: AVIV (migration)
// 1. DONE - To check the correctness of unrealizability, take the property
// forumla from the paper (including
// "historically", which should be supported in Spectra), and pass it surrounded
// by negation.
// 2. DONE - Instead of re-building the initial and safeties spec, do as Jan did
// in the old env validation -
// pass it into a SpecBDD, which represents an "atomic" element of the spec.
// We do not have SpecBDD in the new env - need to add it (it's in jtlv
// package).
// 3. The below switch case was for supporting LTL. We only need GR1, so no need
// for UNTIL, RELEASES, SINCE
// and TRIGGERED.
// 4. DONE - The FINALLY operator doesn't exist in spectra - need to add it or
// figure out what's its equivalent in spectra
// 5. I will pass a PlayerModule, then create a ComposedPlayerModule which will
// have in it the original
// PlayerModule and the tester PlayerModule.
// 5. implement feasible in a new class - "checker" - and it should get a
// PlayerModule which is composed
// 6. Add to PlayerModule "compose(PlayerModule m2)" which:
// a) create a new PlayerModule which contains:
// - conjuncts all initials of modules
// - conjuncts all trans of modules
// - concatenates the lists of justices - make sure the current module list is
// first
// - TODO - what about vars?
// b) return this new PlayerModule
// 7. in the feasible - perform the "restrictTrans / Ini" by first saving the
// ini/trans, then do
// conjunctIni/Trans and after, reset it with the saved ini/trans.
//
try {
Operator op = spec.getOperator();
Spec[] child = spec.getChildren();
BDD aux = getSpec2BDD(spec);
int noo = op.numOfOperands();
BDD c1 = (noo > 0) ? getSpec2BDD(child[0]) : null;
BDD c2 = (noo > 1) ? getSpec2BDD(child[1]) : null;
switch (op) {
case PRIME:
p_c1 = Env.prime(c1);
tester.conjunctTrans(aux.biimp(p_c1));
break;
case FINALLY:
p_aux = Env.prime(aux);
tester.conjunctTrans(aux.biimp(c1.or(p_aux)));
tester.addJustice(c1.or(aux.not()));
break;
case GLOBALLY:
p_aux = Env.prime(aux);
tester.conjunctTrans(aux.biimp(c1.and(p_aux)));
tester.addJustice(c1.not().or(aux));
break;
case PREV:
p_aux = Env.prime(aux);
tester.conjunctInitial(aux.not());
tester.conjunctTrans(p_aux.biimp(c1));
break;
// no BEFORE
case ONCE:
p_c1 = Env.prime(c1);
p_aux = Env.prime(aux);
tester.conjunctInitial(aux.biimp(c1));
tester.conjunctTrans(p_aux.biimp(aux.or(p_c1)));
break;
case HISTORICALLY:
p_c1 = Env.prime(c1);
p_aux = Env.prime(aux);
tester.conjunctInitial(aux.biimp(c1));
tester.conjunctTrans(p_aux.biimp(aux.and(p_c1)));
break;
case SINCE:
p_c1 = Env.prime(c1);
p_c2 = Env.prime(c2);
p_aux = Env.prime(aux);
tester.conjunctInitial(aux.biimp(c2));
tester.conjunctTrans(p_aux.biimp(p_c2.or(p_c1.and(aux))));
break;
case TRIGGERED:
p_c1 = Env.prime(c1);
p_c2 = Env.prime(c2);
p_aux = Env.prime(aux);
tester.conjunctInitial(aux.biimp(c1.or(c2)));
tester.conjunctTrans(p_aux.biimp(p_c2.or(p_c1.and(aux))));
break;
// NOT_PREV_NOT,
default:
break;
}
} catch (BDDException e) {
throw new ModelCheckException("Failed to prime BDD " + "assertion for specification: " + spec.toString());
}
}
if (!isWeak) {
tester.conjunctInitial(getSpec2BDD(root).not());
}
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.spectragameinput.translator;
public class EntitiesMapper {
private DefineNameToDefineMapping defineNameToDefineMapping;
private VariableNameToVariableMapping variableNameToVariableMapping;
private PredicateNameToPredicateMapping predicateNameToPredicateMapping;
private PatternNameToPatternMapping patternNameToPatternMapping;
private MonitorNameToMonitorMapping monitorNameToMonitorMapping;
private CounterNameToCounterMapping counterNameToCounterMapping;
public EntitiesMapper()
{
defineNameToDefineMapping = new DefineNameToDefineMapping();
variableNameToVariableMapping = new VariableNameToVariableMapping();
predicateNameToPredicateMapping = new PredicateNameToPredicateMapping();
patternNameToPatternMapping = new PatternNameToPatternMapping();
monitorNameToMonitorMapping = new MonitorNameToMonitorMapping();
counterNameToCounterMapping = new CounterNameToCounterMapping();
}
public DefineNameToDefineMapping getDefineNameToDefineMapping() {
return defineNameToDefineMapping;
}
public VariableNameToVariableMapping getVariableNameToVariableMapping() {
return variableNameToVariableMapping;
}
public PredicateNameToPredicateMapping getPredicateNameToPredicateMapping() {
return predicateNameToPredicateMapping;
}
public PatternNameToPatternMapping getPatternNameToPatternMapping() {
return patternNameToPatternMapping;
}
public MonitorNameToMonitorMapping getMonitorNameToMonitorMapping() {
return monitorNameToMonitorMapping;
}
public CounterNameToCounterMapping getCounterNameToCounterMapping() {
return counterNameToCounterMapping;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.gr1;
import java.util.Stack;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDD.BDDIterator;
import net.sf.javabdd.BDDVarSet;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.games.AbstractGamesException;
import tau.smlab.syntech.games.controller.enumerate.ConcreteControllerConstruction;
import tau.smlab.syntech.games.controller.enumerate.EnumStateI;
import tau.smlab.syntech.games.controller.enumerate.EnumStrategyI;
import tau.smlab.syntech.games.controller.enumerate.EnumStrategyImpl;
import tau.smlab.syntech.jtlv.CoreUtil;
import tau.smlab.syntech.jtlv.Env;
public class GR1ConceteControllerConstructionSkip extends ConcreteControllerConstruction {
private GR1Memory mem;
private GR1StrategyType kind;
public GR1ConceteControllerConstructionSkip(GR1Memory mem, GameModel m, GR1StrategyType kind) {
super(mem, m);
this.mem = mem;
this.kind = kind;
}
public GR1ConceteControllerConstructionSkip(GR1Memory mem, GameModel m) {
super(mem, m);
this.mem = mem;
this.kind = GR1StrategyType.ZYX;
}
@Override
public EnumStrategyI calculateConcreteController() throws AbstractGamesException {
return this.calculateConcreteController(false);
}
public EnumStrategyI calculateConcreteController(boolean calcLongestSimplePath) throws AbstractGamesException {
if (!(kind instanceof GR1StrategyType))
return null;
int strategy_kind = ((GR1StrategyType) kind).old_value();
Stack<EnumStateI> st_stack = new Stack<EnumStateI>();
Stack<Integer> j_stack = new Stack<Integer>();
Stack<Integer> cy_stack = new Stack<Integer>();
BDDVarSet envUnprimedVars = env.moduleUnprimeVars();
BDDVarSet sysUnprimedVars = sys.moduleUnprimeVars();
EnumStrategyImpl aut = new EnumStrategyImpl(calcLongestSimplePath);
System.out.println("calculateNewStrategyNewSkip start with node num = " + Env.TRUE().getFactory().getNodeNum());
// for all initial env states find one possible sys state and add these on
// the stack with rank 0
for (BDDIterator it = env.initial().iterator(envUnprimedVars); it.hasNext();) {
// TODO make this faster by keeping envIni symbolic: search "closest" envIni
// states, then iterate (this will save individual searches for "closest")
BDD envIni = it.nextBDD();
BDD iniWin = envIni.andWith(getWinningInitialStates());
int cy = 0;
BDD closest = Env.FALSE();
// get to the closest state to go to next justice
while (closest.isZero()) {
closest.free();
closest = iniWin.and(mem.y_mem[0][cy++]);
}
iniWin.free();
BDD oneIni = CoreUtil.satOne(closest, envUnprimedVars.union(sysUnprimedVars));
closest.free();
st_stack.push(aut.getState(oneIni, new GR1RankInfo(0)));
cy_stack.push(cy);
j_stack.push(new Integer(0));
}
System.out.println("Initial states of environment: " + st_stack.size());
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
EnumStateI new_state = st_stack.pop();
BDD p_st = new_state.getData();
int p_j = j_stack.pop();
int p_cy = cy_stack.pop();
int succ_cy = 0;
assert p_cy >= 0 : "Couldn't find p_cy";
int p_i = -1;
for (int i = 0; i < env.justiceNum(); i++) {
BDD b = p_st.and(mem.x_mem[p_j][i][p_cy]);
if (!b.isZero()) {
p_i = i;
b.free();
break;
}
b.free();
}
assert p_i >= 0 : "Couldn't find p_i";
BDD all_succs = env.succ(p_st);
// For each env successor, find a strategy successor
for (BDDIterator iter_succ = all_succs.iterator(envUnprimedVars); iter_succ.hasNext();) {
BDD primed_cur_succ = Env.prime(iter_succ.nextBDD());
BDD next_s = sys.trans().and(p_st).andWith(primed_cur_succ)
.exist(envUnprimedVars.union(sysUnprimedVars));
BDD next_op = Env.unprime(next_s);
next_s.free();
BDD candidate = Env.FALSE();
int jcand = p_j;
int local_kind = strategy_kind;
while (candidate.isZero() & (local_kind >= 0)) {
// a - first successor option in the strategy.
// just satisfied a justice goal go to next
if ((local_kind == 3) | (local_kind == 7) | (local_kind == 10) | (local_kind == 13)
| (local_kind == 18) | (local_kind == 21)) {
int next_p_j = (p_j + 1) % sys.justiceNum();
BDD justiceAndSt = p_st.and(sys.justiceAt(p_j));
if (!justiceAndSt.isZero()) {
BDD opt = next_op.and(mem.z_mem[next_p_j]);
if (!opt.isZero()) {
// prefer existing states
BDD optEx = opt.and(aut.getStatesOfRank(new GR1RankInfo(next_p_j)));
if (!optEx.isZero()) {
opt.free();
opt = optEx;
}
int steps = 0;
BDD closest = Env.FALSE();
// get to the closest state to go to next justice
while (closest.isZero()) {
closest.free();
closest = opt.and(mem.y_mem[next_p_j][steps++]);
}
candidate = closest;
jcand = next_p_j;
succ_cy = steps;
}
opt.free();
}
justiceAndSt.free();
}
// b - second successor option in the strategy.
// get closest to satisfying current system justice goal
if ((local_kind == 2) | (local_kind == 5) | (local_kind == 11) | (local_kind == 15)
| (local_kind == 17) | (local_kind == 22)) {
if (p_cy > 0) {
int look_r = 0;
// look for the fairest r.
BDD opt = next_op.and(mem.y_mem[p_j][look_r]);
while (opt.isZero() & (look_r < p_cy)) {
look_r++;
opt.free();
opt = next_op.and(mem.y_mem[p_j][look_r]);
}
if ((look_r != p_cy) && (!opt.isZero())) {
candidate = opt.id();
succ_cy = look_r;
}
opt.free();
}
}
// c - third successor option in the strategy.
// preventing env justice goal
if ((local_kind == 1) | (local_kind == 6) | (local_kind == 9) | (local_kind == 14)
| (local_kind == 19) | (local_kind == 23)) {
BDD notJustSt = p_st.id().andWith(env.justiceAt(p_i).not());
if (!notJustSt.isZero()) {
BDD opt = next_op.and(mem.x_mem[p_j][p_i][p_cy]);
if (!opt.isZero()) {
candidate = opt.id();
succ_cy = p_cy;
// does not always succeed to prevent, e.g., when justice
// of env satisfied by successor already
BDD notJustCand = candidate.id().andWith(env.justiceAt(p_i).not());
notJustCand.free();
}
opt.free();
}
notJustSt.free();
}
// no successor was found yet.
assert ((local_kind != 0) & (local_kind != 4) & (local_kind != 8) & (local_kind != 12)
& (local_kind != 16) & (local_kind != 20)) : "No successor was found";
local_kind--;
}
BDD candGoalEx = candidate.and(aut.getStatesOfRank(new GR1RankInfo(jcand)))
.andWith(sys.justiceAt(jcand).id());
BDD candGoalNew = candidate.and(sys.justiceAt(jcand));
BDD candEx = candidate.and(aut.getStatesOfRank(new GR1RankInfo(jcand)));
if (!candGoalEx.isZero()) {
// 1st option take one that reaches goal if possible and exists
candidate.free();
candidate = candGoalEx;
candGoalNew.free();
candEx.free();
} else if (!candGoalNew.isZero()) {
// 2nd option take one that reaches goal if possible (even multiple)
BDD skip = sys.justiceAt(jcand).id();
int skipToJustice = (jcand + 1) % sys.justiceNum();
// TODO check about the BDD z of winning states
BDD skipTo = candGoalNew.and(sys.justiceAt(skipToJustice));
while (jcand != skipToJustice && !skipTo.isZero()) {
skip.andWith(sys.justiceAt(skipToJustice).id());
skipToJustice = (skipToJustice + 1) % sys.justiceNum();
skipTo = candidate.id().andWith(skip.id()).andWith(sys.justiceAt(skipToJustice).id());
}
candidate.andWith(skip);
skipTo.free();
candGoalEx.free();
candGoalNew.free();
candEx.free();
jcand = (skipToJustice + sys.justiceNum() - 1) % sys.justiceNum();
succ_cy = 0;
} else if (!candEx.isZero()) {
// 3rd option take an existing one
candidate.free();
candidate = candEx;
candGoalEx.free();
candGoalNew.free();
}
BDD one_cand = CoreUtil.satOne(candidate, envUnprimedVars.union(sysUnprimedVars));
candidate.free();
BDD tmp = one_cand.and(sys.justiceAt(jcand));
tmp.free();
// add succ
EnumStateI succ = aut.addSuccessorState(new_state, one_cand, new GR1RankInfo(jcand));
if (succ != null) {
// if a new state was created.
st_stack.push(succ);
cy_stack.push(succ_cy);
j_stack.push(jcand);
}
}
all_succs.free();
}
System.out.println("calculateNewStrategyNewSkip end with node num = " + Env.TRUE().getFactory().getNodeNum());
return aut;
}
private BDD getWinningInitialStates() {
return mem.getWin().and(sys.initial());
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.spectragameinput.translator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import tau.smlab.syntech.gameinput.model.Predicate;
import tau.smlab.syntech.spectragameinput.SpectraTranslationException;
public class PredicateNameToPredicateMapping {
private Map<String, Predicate> predicateNameToPredicateObjectMapping;
public PredicateNameToPredicateMapping() {
predicateNameToPredicateObjectMapping = new HashMap<>();
}
public List<Predicate> getAllPredicates() {
return new ArrayList<>(predicateNameToPredicateObjectMapping.values());
}
/**
* Computes GameInput Predicate on demand: If computed before, returns immediately. Otherwise computes the predicate, stores it and returns.
* @param entitiesMapper
* @param tracer
* @param Spectra Predicate
* @return GameInput Predicate
* @throws SpectraTranslationException
*/
public Predicate get(tau.smlab.syntech.spectra.Predicate spectraPredicate, EntitiesMapper entitiesMapper, Tracer tracer) throws SpectraTranslationException
{
String predicateName = spectraPredicate.getName();
if (predicateNameToPredicateObjectMapping.containsKey(predicateName))
{
return predicateNameToPredicateObjectMapping.get(predicateName);
}
else
{
// Compute the predicate
Predicate giPredicate = Spectra2GameInputTranslator.computePredicate(entitiesMapper, tracer, spectraPredicate);
// Store it for future look ups
predicateNameToPredicateObjectMapping.put(predicateName, giPredicate);
return giPredicate;
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinput.spec;
import tau.smlab.syntech.gameinput.model.Variable;
//This class implements a Spec that represents a QuantifierExpr
public class QuantifiedSpec implements Spec {
/**
*
*/
private static final long serialVersionUID = -355517893664017916L;
Operator op; // The operator of the quantifier expression (forall or exists)
private Variable domainVar; // The domain var of the quantifier expression
private Spec tmpExpr; // The inner expression of the quantifier expression
public QuantifiedSpec(Operator op, Variable domainVar, Spec tmpExpr) {
this.op = op;
this.domainVar = domainVar;
this.tmpExpr = tmpExpr;
}
public Operator getOperator() {
return this.op;
}
public void setOperator(Operator op) {
this.op = op;
}
public Operator getExprOperator() {
return (this.getOperator() == Operator.FORALL) ? Operator.AND : Operator.OR;
}
public Variable getDomainVar() {
return this.domainVar;
}
public void setDomainVar(Variable domainVar) {
this.domainVar = domainVar;
}
public Spec getTempExpr() {
return this.tmpExpr;
}
public void setTempExpr(Spec tmpExpr) {
this.tmpExpr = tmpExpr;
}
public String toString() {
return this.op.toString() + " " + this.domainVar.toString() + " expr : " + this.tmpExpr.toString();
}
public boolean isPastLTLSpec() {
return false;
}
@Override
public boolean isPropSpec() {
return false;
}
@Override
public boolean hasTemporalOperators() {
return false;
}
public QuantifiedSpec clone() throws CloneNotSupportedException {
return new QuantifiedSpec(this.op, this.domainVar, this.tmpExpr);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.rabin;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.games.GameSolver;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.lib.FixPoint;
/**
* winning states of game memory are winning for the environment!
*
*/
public class RabinGame extends GameSolver {
public static boolean DETECT_FIX_POINT_EARLY = true;
public static boolean STOP_WHEN_WIN_FROM_SOME_INITIALS = true;
public static boolean USE_FIXPOINT_RECYCLE = true;
/**
* Use CUDD function to conjunct and abstract in parallel
*/
public static boolean SIMULTANEOUS_CONJUNCTION_ABSTRACTION = false;
protected RabinMemory mem;
public RabinGame(GameModel m) {
super(m);
mem = new RabinMemory();
if (sys.justiceNum() == 0) {
sys.addJustice(Env.TRUE());
}
if (env.justiceNum() == 0) {
env.addJustice(Env.TRUE());
}
}
@Override
public boolean checkRealizability() {
this.mem = new RabinMemory();
BDD x, y, z;
FixPoint iterX, iterY, iterZ;
boolean firstFixZ = true;
z = Env.FALSE();
for (iterZ = new FixPoint(false); iterZ.advance(z);) {
for (int j = 0; j < sys.justiceNum(); j++) {
mem.addXLayer(env.justiceNum());
BDD nextZ = env.controlStates(sys, z);
BDD notJj = sys.justiceAt(j).not();
y = Env.TRUE();
for (iterY = new FixPoint(false); iterY.advance(y);) {
mem.clearXLayer();
BDD nextYandNotJj = env.controlStates(sys, y).andWith(notJj.id());
y = Env.TRUE();
for (int i = 0; i < env.justiceNum(); i++) {
BDD pre = nextZ.id().orWith(env.justiceAt(i).and(nextYandNotJj));
if (USE_FIXPOINT_RECYCLE && !firstFixZ) {
x = mem.getXMem().get(mem.getXMem().size() - sys.justiceNum() - 1).get(i).lastElement()
.or(pre);
} else {
x = Env.FALSE();
}
for (iterX = new FixPoint(false); iterX.advance(x);) {
x = pre.id().orWith(notJj.id().andWith(env.controlStates(sys, x)));
mem.addX(i, x);
}
y = y.and(x);
pre.free();
}
nextYandNotJj.free();
} // end y fix
z = z.or(y);
mem.addZ(z);
nextZ.free();
notJj.free();
// breaking as early as possible
if (DETECT_FIX_POINT_EARLY && mem.sizeZ() > sys.justiceNum()) { // at least one full loop
int currZpos = mem.sizeZ() - 1;
if (z.equals(mem.getZ(currZpos - sys.justiceNum()))) {
// System.out.println("Stops early - found early fixed point");
// fixpoint reached because last iteration over all
// system justices
// did not add anything
break; // jump to return below
}
}
// NOTE: check if we win from some initials and stop early
if (STOP_WHEN_WIN_FROM_SOME_INITIALS && envWinAllInitial(z.id())) {
// System.out.println("Stops early - env wins from some initial states");
mem.setWin(z.id());
mem.setComplete(false);
return true;
}
}
firstFixZ = false;
}
mem.setWin(z.id());
mem.setComplete(true);
return envWinAllInitial(z.id());
}
/**
* check existence of an env initial s.t. for all sys initial env wins
*
* @return
*/
public boolean envWinAllInitial() {
BDD envWinIni = envWinIni();
boolean win = !envWinIni.isZero();
envWinIni.free();
return win;
}
private BDD envWinIni() {
BDD sysDeadOrEnvWin = sys.initial().imp(mem.getWin());
BDD envWinIni = env.initial().id().andWith(sysDeadOrEnvWin.forAll(sys.moduleUnprimeVars()));
sysDeadOrEnvWin.free();
return envWinIni;
}
public BDD getInitialStates() {
BDD envWinIni = envWinIni();
BDD ini = envWinIni.andWith(sys.initial().id());
return ini;
}
@Override
public void free() {
mem.free();
}
public RabinMemory getMem() {
return mem;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// BDDFactory.java, created Jan 29, 2003 9:50:57 PM by jwhaley
// Copyright (C) 2003 <NAME>
// Licensed under the terms of the GNU LGPL; see COPYING for details.
package net.sf.javabdd;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigInteger;
import java.security.AccessControlException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.jtlv.ModuleVariableException;
/**
* <p>
* Interface for the creation and manipulation of BDDs.
* </p>
*
* @see net.sf.javabdd.BDD
*
* @author <NAME>
* @version $Id: BDDFactory.java,v 1.2 2009/10/18 19:30:54 uid228351 Exp $
*/
public abstract class BDDFactory {
public static final String getProperty(String key, String def) {
try {
return System.getProperty(key, def);
} catch (AccessControlException e) {
return def;
}
}
/**
* <p>
* Initializes a BDD factory with the given initial node table size and
* operation cache size. Tries to use the "buddy" native library; if it fails,
* it falls back to the "java" library.
* </p>
*
* @param nodenum
* initial node table size
* @param cachesize
* operation cache size
* @return BDD factory object
*/
public static BDDFactory init(int nodenum, int cachesize) {
String bddpackage = getProperty("bdd", "buddy");
return init(bddpackage, null, nodenum, cachesize);
}
/**
* <p>
* Initializes a BDD factory of the given type with the given initial node table
* size and operation cache size. The type is a string that can be "buddy",
* "cudd", "cal", "j", "java", "jdd", "test", "typed", or a name of a class that
* has an init() method that returns a BDDFactory. If it fails, it falls back to
* the "java" factory.
* </p>
*
* @param bddpackage
* BDD package string identifier
* @param nodenum
* initial node table size
* @param cachesize
* operation cache size
* @return BDD factory object
*/
public static BDDFactory init(String bddpackage, int nodenum, int cachesize) {
return init(bddpackage, null, nodenum, cachesize);
}
/**
* <p>
* Initializes a BDD factory of the given type with the given initial node table
* size and operation cache size. The type is a string that can be "buddy",
* "cudd", "cal", "j", "java", "jdd", "test", "typed", or a name of a class that
* has an init() method that returns a BDDFactory. If it fails, it falls back to
* the "java" factory.
* </p>
*
* @param bddpackage
* BDD package string identifier
* @param bddpackageVer
* BDD package version string identifier. If null, the default
* version is used
* @param nodenum
* initial node table size
* @param cachesize
* operation cache size
* @return BDD factory object
*/
public static BDDFactory init(String bddpackage, String bddpackageVer, int nodenum, int cachesize) {
try {
if (bddpackage.equals("net.sf.javabdd.CUDDFactory")) {
if (bddpackageVer != null && bddpackageVer.equals("3.0_PIPE")) {
return CUDDFactoryGeneric.init("3.0_PIPE", nodenum, cachesize);
}
return CUDDFactory.init(nodenum, cachesize);
}
if (bddpackage.equals("net.sf.javabdd.CUDDFactory$CUDDADDFactory")) {
if (bddpackageVer != null && bddpackageVer.equals("3.0_PIPE")) {
return CUDDFactoryGeneric.CUDDADDFactoryGeneric.init("3.0_PIPE", nodenum, cachesize);
}
return CUDDFactory.CUDDADDFactory.init(nodenum, cachesize);
}
} catch (LinkageError e) {
System.out.println("Could not load BDD package " + bddpackage + ": " + e.getLocalizedMessage());
}
try {
Class<?> c = Class.forName((bddpackage.equals("cuddadd")) ? "cudd" : bddpackage);
Method m = (bddpackage.equals("cuddadd"))
? c.getMethod("init", new Class[] { int.class, int.class, boolean.class })
: c.getMethod("init", new Class[] { int.class, int.class });
return (BDDFactory) ((bddpackage.equals("cuddadd"))
? m.invoke(null, new Object[] { new Integer(nodenum), new Integer(cachesize), new Boolean(true) })
: m.invoke(null, new Object[] { new Integer(nodenum), new Integer(cachesize) }));
} catch (Exception e) {
}
// falling back to default java implementation.
return JTLVJavaFactory.init(nodenum, cachesize);
}
/**
* Logical 'and' (BDDs and ADDs; for non 0-1 ADDs this operator is equivalent to
* multiplication).
*/
public static final BDDOp and = new BDDOp(0, "and");
/**
* Logical 'xor' (BDDs and 0-1 ADDs only).
*/
public static final BDDOp xor = new BDDOp(1, "xor");
/**
* Logical 'or' (BDDs and 0-1 ADDs only).
*/
public static final BDDOp or = new BDDOp(2, "or");
/**
* Logical 'nand' (BDDs and 0-1 ADDs only).
*/
public static final BDDOp nand = new BDDOp(3, "nand");
/**
* Logical 'nor' (BDDs and 0-1 ADDs only).
*/
public static final BDDOp nor = new BDDOp(4, "nor");
/**
* Logical 'implication' (BDDs and 0-1 ADDs only).
*/
public static final BDDOp imp = new BDDOp(5, "imp");
/**
* Logical 'bi-implication' (BDDs and 0-1 ADDs only).
*/
public static final BDDOp biimp = new BDDOp(6, "biimp");
/**
* Set difference (BDDs and 0-1 ADDs only).
*/
public static final BDDOp diff = new BDDOp(7, "diff");
/**
* Less than (BDDs and ADDs).
*/
public static final BDDOp less = new BDDOp(8, "less");
/**
* Inverse implication (BDDs and 0-1 ADDs only).
*/
public static final BDDOp invimp = new BDDOp(9, "invimp");
/**
* Arithmetic multiplication (ADDs only).
*/
public static final BDDOp times = new BDDOp(10, "times");
/**
* Arithmetic division (ADDs only).
*/
public static final BDDOp div = new BDDOp(11, "div");
/**
* Arithmetic addition (ADDs only).
*/
public static final BDDOp plus = new BDDOp(12, "plus");
/**
* Arithmetic subtraction (ADDs only).
*/
public static final BDDOp minus = new BDDOp(13, "minus");
/**
* Maximum (ADDs only).
*/
public static final BDDOp max = new BDDOp(14, "max");
/**
* Minimum (ADDs only).
*/
public static final BDDOp min = new BDDOp(15, "min");
/**
* <p>
* Energy (or Mean Payoff) games Arithmetic subtraction (ADDs only). This
* operation is an arithmetic subtraction that is defined differently in the
* following cases:
* </p>
* +INF - y = +INF , for all finite y <br>
* y - (+INF) = 0 , for all finite y <br>
* y - (-INF) = +INF , for all finite, non negative, y <br>
* +INF - (+INF) = 0 <br>
* +INF - (-INF) = +INF <br>
* x - y = max {x-y, 0} , for all finite, non negative x, and for all y
*/
public static final BDDOp engMinus = new BDDOp(16, "engMinus");
/**
* <p>
* Energy (or Mean Payoff) games Arithmetic addition (ADDs only). This operation
* is an arithmetic addition that is defined differently in the following cases:
* </p>
* +INF + y = +INF , for all finite y <br>
* y + (+INF) = +INF , for all finite y <br>
* y + (-INF) = -INF , for all finite y <br>
* (-INF) + y = -INF , for all finite y <br>
* +INF + (+INF) = +INF <br>
* -INF + (-INF) = -INF <br>
* +INF + (-INF) = 0 <br>
* (-INF) + (+INF) = 0 <br>
*/
public static final BDDOp engPlus = new BDDOp(17, "engPlus");
/**
* <p>
* Agreement operator (ADDs only). This operator is similar to xnor, such that
* <br>
* ADD1 op ADD2 = 1 if ADD1==ADD2, and ADD1 op ADD2 = 0 otherwise.
* </p>
*/
public static final BDDOp agree = new BDDOp(18, "agree");
/**
* <p>
* Enumeration class for binary operations on BDDs. Use the static fields in
* BDDFactory to access the different binary operations.
* </p>
*/
public static class BDDOp {
final int id;
final String name;
private BDDOp(int id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return name;
}
}
/**
* <p>
* Construct a new BDDFactory.
* </p>
*/
protected BDDFactory() {
System.out.println(this.getInfo());
}
/**
* <p>
* Get info string of BDD Factory
* </p>
*/
public String getInfo() {
String s = this.getClass().toString();
s = s.substring(s.lastIndexOf('.') + 1);
return "Using BDD Package: " + s + ", Version: " + this.getVersion();
}
/**
* <p>
* Returns true if this is a ZDD factory, false otherwise.
* </p>
*/
public boolean isZDD() {
return false;
}
/**
* <p>
* Returns true if this is an ADD (a.k.a MTBDD) factory, false otherwise.
* </p>
*/
public boolean isADD() {
return false;
}
/**
* <p>
* Get a constant BDD by value: <br>
* If this is a BDD factory, for value of 0 the constant false BDD is returned.
* Otherwise, for any non-zero value the constant true BDD is returned.<br>
* If this is an ADD factory, the constant ADD for the value is returned (not
* implemented by default).
* </p>
* <h4>Implementation notes:</h4> This method is not implemented in the
* {@code abstract BDDFactory class} for ADDs and must be overridden for ADD
* factories.
*
* @param value
* the constant BDD\ADD value
* @return constant BDD\ADD for the value
*/
/*
* default implementation: for an ADD factory this method should be overridden
*/
public BDD constant(double value) {
if (value == 0.0) {
return zero();
}
return one();
}
/**
* <p>
* Get the constant plus infinity ADD.
* </p>
* <h4>Implementation notes:</h4> This method throws by default
* {@code UnsupportedOperationException} and must be overridden for ADD
* factories.
*
* @throws UnsupportedOperationException
* @return constant plus infinity ADD
*/
public ADD plusInfinity() {
throw new UnsupportedOperationException();
}
/**
* <p>
* Get the constant minus infinity ADD.
* </p>
* <h4>Implementation notes:</h4> This method throws by default
* {@code UnsupportedOperationException} and must be overridden for ADD
* factories.
*
* @throws UnsupportedOperationException
* @return constant minus infinity ADD
*/
public ADD minusInfinity() {
throw new UnsupportedOperationException();
}
/**
* <p>
* Get the constant false BDD.
* </p>
*
* <p>
* Compare to bdd_false.
* </p>
*/
public abstract BDD zero();
/**
* <p>
* Get the constant true BDD.
* </p>
*
* <p>
* Compare to bdd_true.
* </p>
*/
public abstract BDD one();
/**
* <p>
* Get the constant universe BDD. (The universe BDD differs from the one BDD in
* ZDD mode.)
* </p>
*
* <p>
* Compare to bdd_true.
* </p>
*/
public BDD universe() {
return one();
}
/**
* <p>
* Get an empty BDDVarSet.
* </p>
*
* <p>
* Compare to bdd_true.
* </p>
*/
public BDDVarSet emptySet() {
return new BDDVarSet.DefaultImpl(one());
}
/**
* <p>
* Build a cube from an array of variables.
* </p>
*
* <p>
* Compare to bdd_buildcube.
* </p>
*/
public BDD buildCube(int value, List<BDD> variables) {
BDD result = universe();
Iterator<BDD> i = variables.iterator();
while (i.hasNext()) {
BDD var = i.next();
if ((value & 0x1) != 0)
var = var.id();
else
var = var.not();
result.andWith(var);
value >>= 1;
}
return result;
}
/**
* <p>
* Build a cube from an array of variables.
* </p>
*
* <p>
* Compare to bdd_ibuildcube./p>
*/
public BDD buildCube(int value, int[] variables) {
BDD result = universe();
for (int z = 0; z < variables.length; z++, value >>= 1) {
BDD v;
if ((value & 0x1) != 0)
v = ithVar(variables[variables.length - z - 1]);
else
v = nithVar(variables[variables.length - z - 1]);
result.andWith(v);
}
return result;
}
/**
* <p>
* Builds a BDD variable set from an integer array. The integer array
* <tt>varset</tt> holds the variable numbers. The BDD variable set is
* represented by a conjunction of all the variables in their positive form.
* </p>
*
* <p>
* Compare to bdd_makeset.
* </p>
*/
public BDDVarSet makeSet(int[] varset) {
BDDVarSet res = emptySet();
int varnum = varset.length;
for (int v = varnum - 1; v >= 0; --v) {
res.unionWith(varset[v]);
}
return res;
}
/**** STARTUP / SHUTDOWN ****/
/**
* <p>
* Compare to bdd_init.
* </p>
*
* @param nodenum
* the initial number of BDD nodes
* @param cachesize
* the size of caches used by the BDD operators
*/
protected abstract void initialize(int nodenum, int cachesize);
/**
* <p>
* Returns true if this BDD factory is initialized, false otherwise.
* </p>
*
* <p>
* Compare to bdd_isrunning.
* </p>
*
* @return true if this BDD factory is initialized
*/
public abstract boolean isInitialized();
/**
* <p>
* Reset the BDD factory to its initial state. Everything is reallocated from
* scratch. This is like calling done() followed by initialize().
* </p>
*/
public void reset() {
int nodes = getNodeTableSize();
int cache = getCacheSize();
domain = null;
fdvarnum = 0;
firstbddvar = 0;
done();
initialize(nodes, cache);
}
/**
* <p>
* This function frees all memory used by the BDD package and resets the package
* to its uninitialized state. The BDD package is no longer usable after this
* call.
* </p>
*
* <p>
* Compare to bdd_done.
* </p>
*/
public abstract void done();
/**
* <p>
* Sets the error condition. This will cause the BDD package to throw an
* exception at the next garbage collection.
* </p>
*
* @param code
* the error code to set
*/
public abstract void setError(int code);
/**
* <p>
* Clears any outstanding error condition.
* </p>
*/
public abstract void clearError();
/**** CACHE/TABLE PARAMETERS ****/
/**
* <p>
* Set the maximum available number of BDD nodes.
* </p>
*
* <p>
* Compare to bdd_setmaxnodenum.
* </p>
*
* @param size
* maximum number of nodes
* @return old value
*/
public abstract int setMaxNodeNum(int size);
/**
* <p>
* Set minimum percentage of nodes to be reclaimed after a garbage collection.
* If this percentage is not reclaimed, the node table will be grown. The range
* of x is 0..1. The default is .20.
* </p>
*
* <p>
* Compare to bdd_setminfreenodes.
* </p>
*
* @param x
* number from 0 to 1
* @return old value
*/
public abstract double setMinFreeNodes(double x);
/**
* <p>
* Set maximum number of nodes by which to increase node table after a garbage
* collection.
* </p>
*
* <p>
* Compare to bdd_setmaxincrease.
* </p>
*
* @param x
* maximum number of nodes by which to increase node table
* @return old value
*/
public abstract int setMaxIncrease(int x);
/**
* <p>
* Set factor by which to increase node table after a garbage collection. The
* amount of growth is still limited by <tt>setMaxIncrease()</tt>.
* </p>
*
* @param x
* factor by which to increase node table after GC
* @return old value
*/
public abstract double setIncreaseFactor(double x);
/**
* <p>
* Sets the cache ratio for the operator caches. When the node table grows,
* operator caches will also grow to maintain the ratio.
* </p>
*
* <p>
* Compare to bdd_setcacheratio.
* </p>
*
* @param x
* cache ratio
*/
public abstract double setCacheRatio(double x);
/**
* <p>
* Sets the node table size.
* </p>
*
* @param n
* new size of table
* @return old size of table
*/
public abstract int setNodeTableSize(int n);
/**
* <p>
* Sets cache size.
* </p>
*
* @return old cache size
*/
public abstract int setCacheSize(int n);
/**** VARIABLE NUMBERS ****/
/**
* <p>
* Returns the number of defined variables.
* </p>
*
* <p>
* Compare to bdd_varnum.
* </p>
*/
public abstract int varNum();
/**
* <p>
* Set the number of used BDD variables. It can be called more than one time,
* but only to increase the number of variables.
* </p>
*
* <p>
* Compare to bdd_setvarnum.
* </p>
*
* @param num
* new number of BDD variables
* @return old number of BDD variables
*/
public abstract int setVarNum(int num);
/**
* <p>
* Add extra BDD variables. Extends the current number of allocated BDD
* variables with num extra variables.
* </p>
*
* <p>
* Compare to bdd_extvarnum.
* </p>
*
* @param num
* number of BDD variables to add
* @return old number of BDD variables
*/
public int extVarNum(int num) {
int start = varNum();
if (num < 0 || num > 0x3FFFFFFF)
throw new BDDException();
setVarNum(start + num);
return start;
}
/**
* <p>
* Returns a BDD representing the I'th variable. (One node with the children
* true and false.) The requested variable must be in the (zero-indexed) range
* defined by <tt>setVarNum</tt>.
* </p>
*
* <p>
* Compare to bdd_ithvar.
* </p>
*
* @param var
* the variable number
* @return the I'th variable on success, otherwise the constant false BDD
*/
public abstract BDD ithVar(int var);
/**
* <p>
* Returns a BDD representing the negation of the I'th variable. (One node with
* the children false and true.) The requested variable must be in the
* (zero-indexed) range defined by <tt>setVarNum</tt>.<br>
* If it is a MTBDD \ ADD, the negation is the complement ADD, i.e. every zero
* terminal becomes one, and every non-zero terminal becomes zero.
* </p>
* <p>
* Compare to bdd_nithvar.
* </p>
*
* @param var
* the variable number
* @return the negated I'th variable on success, otherwise the constant false
* BDD
*/
public abstract BDD nithVar(int var);
/**** INPUT / OUTPUT ****/
/**
* <p>
* Prints all used entries in the node table.
* </p>
*
* <p>
* Compare to bdd_printall.
* </p>
*/
public abstract void printAll();
/**
* <p>
* Prints the node table entries used by a BDD.
* </p>
*
* <p>
* Compare to bdd_printtable.
* </p>
*/
public abstract void printTable(BDD b);
/**
* <p>
* Loads a BDD from a file.
* </p>
*
* <p>
* Compare to bdd_load.
* </p>
*/
public BDD load(String filename) throws IOException {
BufferedReader r = null;
try {
r = new BufferedReader(new FileReader(filename));
BDD result = load(r);
return result;
} finally {
if (r != null)
try {
r.close();
} catch (IOException e) {
}
}
}
// TODO: error code from bdd_load (?)
/**
* <p>
* Loads a BDD from the given input, translating BDD variables according to the
* given map.
* </p>
*
* <p>
* Compare to bdd_load.
* </p>
*
* @param ifile
* reader
* @param translate
* variable translation map
* @return BDD
*/
public BDD load(BufferedReader ifile) throws IOException {
Map<Long, BDD> map = new HashMap<>();
map.put(0l, zero());
map.put(1l, universe());
tokenizer = null;
long vnum = Long.parseLong(readNext(ifile));
// Check for constant true / false
if (vnum == 0) {
long r = Long.parseLong(readNext(ifile));
return r == 0 ? zero() : universe();
}
if (vnum > varNum()) {
System.err.println(
"Warning! Missing some variables. Have " + varNum() + " need " + vnum + ". Filling with dummys.");
while (vnum > varNum()) {
try {
Env.newVar("dummy" + Math.random());
} catch (ModuleVariableException e) {
throw new RuntimeException(e);
}
}
} else if (vnum < varNum()) {
System.err.println("Warning! Env has more vars than expected by BDD.");
}
disableReorder(); // FIXME remember whether to enable later
int[] order = new int[(int) vnum];
for (int i = 0; i < vnum; i++) {
order[i] = Integer.parseInt(readNext(ifile));
}
setVarOrder(order);
BDD root = null;
while (!doneReading(ifile)) {
long key = Long.parseLong(readNext(ifile));
int var = Integer.parseInt(readNext(ifile));
long lowi = Long.parseLong(readNext(ifile));
long highi = Long.parseLong(readNext(ifile));
BDD low, high;
low = map.get(lowi);
high = map.get(highi);
if (low == null || high == null || var < 0)
throw new BDDException("Incorrect file format");
BDD b = ithVar(var);
root = b.ite(high, low);
b.free();
map.put(key, root);
}
BDD tmproot = root.id();
Env.free(map);
// FIXME do not always turn it on (only on demand or if it was already enabled)
enableReorder();
return tmproot;
}
/**
* not done reading if the tokenizer still has tokens or if the file has more
* content to be read
*
* @param ifile
* @return true if more tokens or characters; false otherwise
*/
private boolean doneReading(BufferedReader ifile) {
if (tokenizer != null && tokenizer.hasMoreTokens()) {
return false;
}
try {
if (ifile.ready()) {
return false;
}
} catch (IOException e) {
}
return true;
}
/**
* Used for tokenization during loading.
*/
protected StringTokenizer tokenizer;
/**
* Read the next token from the file.
*
* @param ifile
* reader
* @return next string token
*/
protected String readNext(BufferedReader ifile) throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String s = ifile.readLine();
if (s == null)
throw new BDDException("Incorrect file format");
tokenizer = new StringTokenizer(s);
}
return tokenizer.nextToken();
}
/**
* <p>
* Saves a BDD to a file.
* </p>
*
* <p>
* Compare to bdd_save.
* </p>
*/
public void save(String filename, BDD var) throws IOException {
BufferedWriter is = null;
try {
is = new BufferedWriter(new FileWriter(filename));
save(is, var);
} finally {
if (is != null)
try {
is.close();
} catch (IOException e) {
}
}
}
// TODO: error code from bdd_save (?)
/**
* <p>
* Saves a BDD to an output writer.
* </p>
*
* <p>
* Compare to bdd_save.
* </p>
*/
public void save(BufferedWriter out, BDD r) throws IOException {
// special encoding of TRUE and FALSE use 0 variables and then 1 (TRUE) or 0
// (FALSE)
if (r.isOne() || r.isZero()) {
out.write("0 " + (r.isOne() ? 1 : 0) + "\n");
return;
}
out.write(varNum() + "\n");
for (int i : getVarOrder()) {
out.write(i + " ");
}
out.write("\n");
Set<Long> visited = new HashSet<>();
save_rec(out, visited, r.id());
}
/**
* Helper function for save().
*/
protected long save_rec(BufferedWriter out, Set<Long> visited, BDD root) throws IOException {
if (root.isZero()) {
root.free();
return 0;
}
if (root.isOne()) {
root.free();
return 1;
}
long i = root.rootId();
if (visited.contains(i)) {
root.free();
return i;
}
long v = i;
visited.add(i);
BDD h = root.high();
BDD l = root.low();
int rootvar = root.var();
root.free();
long lo = save_rec(out, visited, l);
long hi = save_rec(out, visited, h);
out.write(i + " ");
out.write(rootvar + " ");
out.write(lo + " ");
out.write(hi + "\n");
return v;
}
// TODO: bdd_blockfile_hook
// TODO: bdd_versionnum, bdd_versionstr
/**** REORDERING ****/
/**
* <p>
* Convert from a BDD level to a BDD variable.
* </p>
*
* <p>
* Compare to bdd_level2var.
* </p>
*/
public abstract int level2Var(int level);
/**
* <p>
* Convert from a BDD variable to a BDD level.
* </p>
*
* <p>
* Compare to bdd_var2level.
* </p>
*/
public abstract int var2Level(int var);
/**
* No reordering.
*/
public static final ReorderMethod REORDER_NONE = new ReorderMethod(0, "NONE");
/**
* Reordering using a sliding window of 2.
*/
public static final ReorderMethod REORDER_WIN2 = new ReorderMethod(1, "WIN2");
/**
* Reordering using a sliding window of 2, iterating until no further progress.
*/
public static final ReorderMethod REORDER_WIN2ITE = new ReorderMethod(2, "WIN2ITE");
/**
* Reordering using a sliding window of 3.
*/
public static final ReorderMethod REORDER_WIN3 = new ReorderMethod(5, "WIN3");
/**
* Reordering using a sliding window of 3, iterating until no further progress.
*/
public static final ReorderMethod REORDER_WIN3ITE = new ReorderMethod(6, "WIN3ITE");
/**
* Reordering where each block is moved through all possible positions. The best
* of these is then used as the new position. Potentially a very slow but good
* method.
*/
public static final ReorderMethod REORDER_SIFT = new ReorderMethod(3, "SIFT");
/**
* Same as REORDER_SIFT, but the process is repeated until no further progress
* is done. Can be extremely slow.
*/
public static final ReorderMethod REORDER_SIFTITE = new ReorderMethod(4, "SIFTITE");
/**
* Selects a random position for each variable. Mostly used for debugging
* purposes.
*/
public static final ReorderMethod REORDER_RANDOM = new ReorderMethod(7, "RANDOM");
/**
* Enumeration class for method reordering techniques. Use the static fields in
* BDDFactory to access the different reordering techniques.
*/
public static class ReorderMethod {
final int id;
final String name;
private ReorderMethod(int id, String name) {
this.id = id;
this.name = name;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
return name;
}
}
/**
* <p>
* Reorder the BDD with the given method.
* </p>
*
* <p>
* Compare to bdd_reorder.
* </p>
*/
public abstract void reorder(ReorderMethod m);
/**
* <p>
* Enables automatic reordering. If method is REORDER_NONE then automatic
* reordering is disabled.
* </p>
*
* <p>
* Compare to bdd_autoreorder.
* </p>
*/
public abstract void autoReorder(ReorderMethod method);
/**
* <p>
* Enables automatic reordering with the given (maximum) number of reorderings.
* If method is REORDER_NONE then automatic reordering is disabled.
* </p>
*
* <p>
* Compare to bdd_autoreorder_times.
* </p>
*/
public abstract void autoReorder(ReorderMethod method, int max);
/**
* <p>
* Returns the current reorder method as defined by autoReorder.
* </p>
*
* <p>
* Compare to bdd_getreorder_method.
* </p>
*
* @return ReorderMethod
*/
public abstract ReorderMethod getReorderMethod();
/**
* <p>
* Returns the number of allowed reorderings left. This value can be defined by
* autoReorder.
* </p>
*
* <p>
* Compare to bdd_getreorder_times.
* </p>
*/
public abstract int getReorderTimes();
/**
* <p>
* Disable automatic reordering until enableReorder is called. Reordering is
* enabled by default as soon as any variable blocks have been defined.
* </p>
*
* <p>
* Compare to bdd_disable_reorder.
* </p>
*/
public abstract void disableReorder();
/**
* <p>
* Enable automatic reordering after a call to disableReorder.<br>
* The reordering method is left unchanged.
* </p>
*
*
* <p>
* Compare to bdd_enable_reorder.
* </p>
*/
public abstract void enableReorder();
/**
* Returns true if automatic reordering is enabled.
*
* @return Whether automatic reordering is enabled
*/
public abstract boolean reorderEnabled();
/**
* <p>
* Enables verbose information about reordering. A value of zero means no
* information, one means some information and greater than one means lots of
* information.
* </p>
*
* @param v
* the new verbose level
* @return the old verbose level
*/
public abstract int reorderVerbose(int v);
/**
* <p>
* This function sets the current variable order to be the one defined by
* neworder. The variable parameter neworder is interpreted as a sequence of
* variable indices and the new variable order is exactly this sequence. The
* array must contain all the variables defined so far. If, for instance the
* current number of variables is 3 and neworder contains [1; 0; 2] then the new
* variable order is v1<v0<v2.
* </p>
*
* <p>
* Note that this operation must walk through the node table many times, and
* therefore it is much more efficient to call this when the node table is
* small.
* </p>
*
* @param neworder
* new variable order
*/
public abstract void setVarOrder(int[] neworder);
/**
* <p>
* Gets the current variable order.
* </p>
*
* @return variable order
*/
public int[] getVarOrder() {
int n = varNum();
int[] result = new int[n];
for (int i = 0; i < n; ++i) {
result[i] = level2Var(i);
}
return result;
}
/**
* <p>
* Make a new BDDPairing object.
* </p>
*
* <p>
* Compare to bdd_newpair.
* </p>
*/
public abstract BDDPairing makePair();
/**
* Make a new pairing that maps from one variable to another.
*
* @param oldvar
* old variable
* @param newvar
* new variable
* @return BDD pairing
*/
public BDDPairing makePair(int oldvar, int newvar) {
BDDPairing p = makePair();
p.set(oldvar, newvar);
return p;
}
/**
* Make a new pairing that maps from one variable to another BDD.
*
* @param oldvar
* old variable
* @param newvar
* new BDD
* @return BDD pairing
*/
public BDDPairing makePair(int oldvar, BDD newvar) {
BDDPairing p = makePair();
p.set(oldvar, newvar);
return p;
}
/**
* Make a new pairing that maps from one BDD domain to another.
*
* @param oldvar
* old BDD domain
* @param newvar
* new BDD domain
* @return BDD pairing
*/
public BDDPairing makePair(BDDDomain oldvar, BDDDomain newvar) {
BDDPairing p = makePair();
p.set(oldvar, newvar);
return p;
}
/**
* <p>
* Swap two variables.
* </p>
*
* <p>
* Compare to bdd_swapvar.
* </p>
*/
public abstract void swapVar(int v1, int v2);
/**** VARIABLE BLOCKS ****/
/**
* <p>
* Adds a new variable block for reordering.
* </p>
*
* <p>
* Creates a new variable block with the variables in the variable set var. The
* variables in var must be contiguous.
* </p>
*
* <p>
* The fixed parameter sets the block to be fixed (no reordering of its child
* blocks is allowed) or free.
* </p>
*
* <p>
* Compare to bdd_addvarblock.
* </p>
*/
public void addVarBlock(BDDVarSet var, boolean fixed) {
int[] v = var.toArray();
int first, last;
if (v.length < 1)
throw new BDDException("Invalid parameter for addVarBlock");
first = last = v[0];
for (int n = 1; n < v.length; n++) {
if (v[n] < first)
first = v[n];
if (v[n] > last)
last = v[n];
}
addVarBlock(first, last, fixed);
}
// TODO: handle error code for addVarBlock.
/**
* <p>
* Adds a new variable block for reordering.
* </p>
*
* <p>
* Creates a new variable block with the variables numbered first through last,
* inclusive.
* </p>
*
* <p>
* The fixed parameter sets the block to be fixed (no reordering of its child
* blocks is allowed) or free.
* </p>
*
* <p>
* Compare to bdd_intaddvarblock.
* </p>
*/
public abstract void addVarBlock(int first, int last, boolean fixed);
// TODO: handle error code for addVarBlock.
// TODO: fdd_intaddvarblock (?)
/**
* <p>
* Add a variable block for all variables.
* </p>
*
* <p>
* Adds a variable block for all BDD variables declared so far. Each block
* contains one variable only. More variable blocks can be added later with the
* use of addVarBlock -- in this case the tree of variable blocks will have the
* blocks of single variables as the leafs.
* </p>
*
* <p>
* Compare to bdd_varblockall.
* </p>
*/
public abstract void varBlockAll();
/**
* <p>
* Clears all the variable blocks that have been defined by calls to
* addVarBlock.
* </p>
*
* <p>
* Compare to bdd_clrvarblocks.
* </p>
*/
public abstract void clearVarBlocks();
/**
* <p>
* Prints an indented list of the variable blocks.
* </p>
*
* <p>
* Compare to bdd_printorder.
* </p>
*/
public abstract void printOrder();
/**** BDD STATS ****/
/**
* Get the BDD library version.
*
* @return version string
*/
public abstract String getVersion();
/**
* <p>
* Counts the number of shared nodes in a collection of BDDs. Counts all
* distinct nodes that are used in the BDDs -- if a node is used in more than
* one BDD then it only counts once.
* </p>
*
* <p>
* Compare to bdd_anodecount.
* </p>
*/
public abstract int nodeCount(Collection<BDD> r);
/**
* <p>
* Get the number of allocated nodes. This includes both dead and active nodes.
* </p>
*
* <p>
* Compare to bdd_getallocnum.
* </p>
*/
public abstract int getNodeTableSize();
/**
* <p>
* Get the number of active nodes in use. Note that dead nodes that have not
* been reclaimed yet by a garbage collection are counted as active.
* </p>
*
* <p>
* Compare to bdd_getnodenum.
* </p>
*/
public abstract int getNodeNum();
/**
* <p>
* Get the current size of the cache, in entries.
* </p>
*
* @return size of cache
*/
public abstract int getCacheSize();
/**
* <p>
* Calculate the gain in size after a reordering. The value returned is
* (100*(A-B))/A, where A is previous number of used nodes and B is current
* number of used nodes.
* </p>
*
* <p>
* Compare to bdd_reorder_gain.
* </p>
*/
public abstract int reorderGain();
/**
* <p>
* Print cache statistics.
* </p>
*
* <p>
* Compare to bdd_printstat.
* </p>
*/
public abstract void printStat();
/*
* public boolean thereIsNegativeCycle(ADD sourceStates, ADD arena, BDDVarSet
* primedVariables, BDDPairing primedUnprimedPairs) { return false; }
*/
/**
* Stores statistics about garbage collections.
*
* @author jwhaley
* @version $Id: BDDFactory.java,v 1.2 2009/10/18 19:30:54 uid228351 Exp $
*/
public static class GCStats {
public int nodes;
public int freenodes;
public long time;
public long sumtime;
public int num;
protected GCStats() {
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Garbage collection #");
sb.append(num);
sb.append(": ");
sb.append(nodes);
sb.append(" nodes / ");
sb.append(freenodes);
sb.append(" free");
sb.append(" / ");
sb.append((float) time / (float) 1000);
sb.append("s / ");
sb.append((float) sumtime / (float) 1000);
sb.append("s total");
return sb.toString();
}
}
/**
* Singleton object for GC statistics.
*/
protected GCStats gcstats = new GCStats();
/**
* <p>
* Return the current GC statistics for this BDD factory.
* </p>
*
* @return GC statistics
*/
public GCStats getGCStats() {
return gcstats;
}
/**
* Stores statistics about reordering.
*
* @author jwhaley
* @version $Id: BDDFactory.java,v 1.2 2009/10/18 19:30:54 uid228351 Exp $
*/
public static class ReorderStats {
public long time;
public int usednum_before, usednum_after;
protected ReorderStats() {
}
public int gain() {
if (usednum_before == 0)
return 0;
return (100 * (usednum_before - usednum_after)) / usednum_before;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Went from ");
sb.append(usednum_before);
sb.append(" to ");
sb.append(usednum_after);
sb.append(" nodes, gain = ");
sb.append(gain());
sb.append("% (");
sb.append((float) time / 1000f);
sb.append(" sec)");
return sb.toString();
}
}
/**
* Singleton object for reorder statistics.
*/
protected ReorderStats reorderstats = new ReorderStats();
/**
* <p>
* Return the current reordering statistics for this BDD factory.
* </p>
*
* @return reorder statistics
*/
public ReorderStats getReorderStats() {
return reorderstats;
}
/**
* Stores statistics about the operator cache.
*
* @author jwhaley
* @version $Id: BDDFactory.java,v 1.2 2009/10/18 19:30:54 uid228351 Exp $
*/
public static class CacheStats {
public int uniqueAccess;
public int uniqueChain;
public int uniqueHit;
public int uniqueMiss;
public int opHit;
public int opMiss;
public int swapCount;
protected CacheStats() {
}
void copyFrom(CacheStats that) {
this.uniqueAccess = that.uniqueAccess;
this.uniqueChain = that.uniqueChain;
this.uniqueHit = that.uniqueHit;
this.uniqueMiss = that.uniqueMiss;
this.opHit = that.opHit;
this.opMiss = that.opMiss;
this.swapCount = that.swapCount;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer sb = new StringBuffer();
String newLine = getProperty("line.separator", "\n");
sb.append(newLine);
sb.append("Cache statistics");
sb.append(newLine);
sb.append("----------------");
sb.append(newLine);
sb.append("Unique Access: ");
sb.append(uniqueAccess);
sb.append(newLine);
sb.append("Unique Chain: ");
sb.append(uniqueChain);
sb.append(newLine);
sb.append("=> Ave. chain = ");
if (uniqueAccess > 0)
sb.append(((float) uniqueChain) / ((float) uniqueAccess));
else
sb.append((float) 0);
sb.append(newLine);
sb.append("Unique Hit: ");
sb.append(uniqueHit);
sb.append(newLine);
sb.append("Unique Miss: ");
sb.append(uniqueMiss);
sb.append(newLine);
sb.append("=> Hit rate = ");
if (uniqueHit + uniqueMiss > 0)
sb.append(((float) uniqueHit) / ((float) uniqueHit + uniqueMiss));
else
sb.append((float) 0);
sb.append(newLine);
sb.append("Operator Hits: ");
sb.append(opHit);
sb.append(newLine);
sb.append("Operator Miss: ");
sb.append(opMiss);
sb.append(newLine);
sb.append("=> Hit rate = ");
if (opHit + opMiss > 0)
sb.append(((float) opHit) / ((float) opHit + opMiss));
else
sb.append((float) 0);
sb.append(newLine);
sb.append("Swap count = ");
sb.append(swapCount);
sb.append(newLine);
return sb.toString();
}
}
/**
* Singleton object for cache statistics.
*/
protected CacheStats cachestats = new CacheStats();
/**
* <p>
* Return the current cache statistics for this BDD factory.
* </p>
*
* @return cache statistics
*/
public CacheStats getCacheStats() {
return cachestats;
}
// TODO: bdd_sizeprobe_hook
// TODO: bdd_reorder_probe
/**** FINITE DOMAINS ****/
protected BDDDomain[] domain;
protected int fdvarnum;
protected int firstbddvar;
/**
* <p>
* Implementors must implement this factory method to create BDDDomain objects
* of the correct type.
* </p>
*/
protected BDDDomain createDomain(int a, BigInteger b) {
return new BDDDomain(a, b) {
public BDDFactory getFactory() {
return BDDFactory.this;
}
};
}
/**
* <p>
* Creates a new finite domain block of the given size. Allocates log 2
* (|domainSize|) BDD variables for the domain.
* </p>
*/
public BDDDomain extDomain(long domainSize) {
return extDomain(BigInteger.valueOf(domainSize));
}
public BDDDomain extDomain(BigInteger domainSize) {
return extDomain(new BigInteger[] { domainSize })[0];
}
/**
* <p>
* Extends the set of finite domain blocks with domains of the given sizes. Each
* entry in domainSizes is the size of a new finite domain which later on can be
* used for finite state machine traversal and other operations on finite
* domains. Each domain allocates log 2 (|domainSizes[i]|) BDD variables to be
* used later. The ordering is interleaved for the domains defined in each call
* to extDomain. This means that assuming domain D0 needs 2 BDD variables x1 and
* x2 , and another domain D1 needs 4 BDD variables y1, y2, y3 and y4, then the
* order then will be x1, y1, x2, y2, y3, y4. The new domains are returned in
* order. The BDD variables needed to encode the domain are created for the
* purpose and do not interfere with the BDD variables already in use.
* </p>
*
* <p>
* Compare to fdd_extdomain.
* </p>
*/
public BDDDomain[] extDomain(int[] dom) {
BigInteger[] a = new BigInteger[dom.length];
for (int i = 0; i < a.length; ++i) {
a[i] = BigInteger.valueOf(dom[i]);
}
return extDomain(a);
}
public BDDDomain[] extDomain(long[] dom) {
BigInteger[] a = new BigInteger[dom.length];
for (int i = 0; i < a.length; ++i) {
a[i] = BigInteger.valueOf(dom[i]);
}
return extDomain(a);
}
public BDDDomain[] extDomain(BigInteger[] domainSizes) {
int offset = fdvarnum;
int binoffset;
int extravars = 0;
int n, bn;
boolean more;
int num = domainSizes.length;
/* Build domain table */
if (domain == null) /* First time */ {
domain = new BDDDomain[num];
} else /* Allocated before */ {
if (fdvarnum + num > domain.length) {
int fdvaralloc = domain.length + Math.max(num, domain.length);
BDDDomain[] d2 = new BDDDomain[fdvaralloc];
System.arraycopy(domain, 0, d2, 0, domain.length);
domain = d2;
}
}
/* Create bdd variable tables */
for (n = 0; n < num; n++) {
domain[n + fdvarnum] = createDomain(n + fdvarnum, domainSizes[n]);
extravars += domain[n + fdvarnum].varNum();
}
binoffset = firstbddvar;
int bddvarnum = varNum();
if (firstbddvar + extravars > bddvarnum) {
setVarNum(firstbddvar + extravars);
}
/* Set correct variable sequence (interleaved) */
for (bn = 0, more = true; more; bn++) {
more = false;
for (n = 0; n < num; n++) {
if (bn < domain[n + fdvarnum].varNum()) {
more = true;
domain[n + fdvarnum].ivar[bn] = binoffset++;
}
}
}
if (isZDD()) {
// Need to rebuild varsets for existing domains.
for (n = 0; n < fdvarnum; n++) {
domain[n].var.free();
domain[n].var = makeSet(domain[n].ivar);
}
}
for (n = 0; n < num; n++) {
domain[n + fdvarnum].var = makeSet(domain[n + fdvarnum].ivar);
}
fdvarnum += num;
firstbddvar += extravars;
BDDDomain[] r = new BDDDomain[num];
System.arraycopy(domain, offset, r, 0, num);
return r;
}
/**
* <p>
* This function takes two finite domain blocks and merges them into a new one,
* such that the new one is encoded using both sets of BDD variables.
* </p>
*
* <p>
* Compare to fdd_overlapdomain.
* </p>
*/
public BDDDomain overlapDomain(BDDDomain d1, BDDDomain d2) {
BDDDomain d;
int n;
int fdvaralloc = domain.length;
if (fdvarnum + 1 > fdvaralloc) {
fdvaralloc += fdvaralloc;
BDDDomain[] domain2 = new BDDDomain[fdvaralloc];
System.arraycopy(domain, 0, domain2, 0, domain.length);
domain = domain2;
}
d = domain[fdvarnum];
d.realsize = d1.realsize.multiply(d2.realsize);
d.ivar = new int[d1.varNum() + d2.varNum()];
for (n = 0; n < d1.varNum(); n++)
d.ivar[n] = d1.ivar[n];
for (n = 0; n < d2.varNum(); n++)
d.ivar[d1.varNum() + n] = d2.ivar[n];
d.var = makeSet(d.ivar);
// bdd_addref(d.var);
fdvarnum++;
return d;
}
/**
* <p>
* Returns a BDD defining all the variable sets used to define the variable
* blocks in the given array.
* </p>
*
* <p>
* Compare to fdd_makeset.
* </p>
*/
public BDDVarSet makeSet(BDDDomain[] v) {
BDDVarSet res = emptySet();
int n;
for (n = 0; n < v.length; n++) {
res.unionWith(v[n].set());
}
return res;
}
/**
* <p>
* Clear all allocated finite domain blocks that were defined by extDomain() or
* overlapDomain().
* </p>
*
* <p>
* Compare to fdd_clearall.
* </p>
*/
public void clearAllDomains() {
domain = null;
fdvarnum = 0;
firstbddvar = 0;
}
/**
* <p>
* Returns the number of finite domain blocks defined by calls to extDomain().
* </p>
*
* <p>
* Compare to fdd_domainnum.
* </p>
*/
public int numberOfDomains() {
return fdvarnum;
}
/**
* <p>
* Returns the ith finite domain block, as defined by calls to extDomain().
* </p>
*/
public BDDDomain getDomain(int i) {
if (i < 0 || i >= fdvarnum)
throw new IndexOutOfBoundsException();
return domain[i];
}
// TODO: fdd_file_hook, fdd_strm_hook
/**
* <p>
* Creates a variable ordering from a string. The resulting order can be passed
* into <tt>setVarOrder()</tt>. Example: in the order "A_BxC_DxExF", the bits
* for A are first, followed by the bits for B and C interleaved, followed by
* the bits for D, E, and F interleaved.
* </p>
*
* <p>
* Obviously, domain names cannot contain the 'x' or '_' characters.
* </p>
*
* @param reverseLocal
* whether to reverse the bits of each domain
* @param ordering
* string representation of ordering
* @return int[] of ordering
* @see net.sf.javabdd.BDDFactory#setVarOrder(int[])
*/
public int[] makeVarOrdering(boolean reverseLocal, String ordering) {
int varnum = varNum();
int nDomains = numberOfDomains();
int[][] localOrders = new int[nDomains][];
for (int i = 0; i < localOrders.length; ++i) {
localOrders[i] = new int[getDomain(i).varNum()];
}
for (int i = 0; i < nDomains; ++i) {
BDDDomain d = getDomain(i);
int nVars = d.varNum();
for (int j = 0; j < nVars; ++j) {
if (reverseLocal) {
localOrders[i][j] = nVars - j - 1;
} else {
localOrders[i][j] = j;
}
}
}
BDDDomain[] doms = new BDDDomain[nDomains];
int[] varorder = new int[varnum];
// System.out.println("Ordering: "+ordering);
StringTokenizer st = new StringTokenizer(ordering, "x_", true);
int numberOfDomains = 0, bitIndex = 0;
boolean[] done = new boolean[nDomains];
for (int i = 0;; ++i) {
String s = st.nextToken();
BDDDomain d;
for (int j = 0;; ++j) {
if (j == numberOfDomains())
throw new BDDException("bad domain: " + s);
d = getDomain(j);
if (s.equals(d.getName()))
break;
}
if (done[d.getIndex()])
throw new BDDException("duplicate domain: " + s);
done[d.getIndex()] = true;
doms[i] = d;
if (st.hasMoreTokens()) {
s = st.nextToken();
if (s.equals("x")) {
++numberOfDomains;
continue;
}
}
bitIndex = fillInVarIndices(doms, i - numberOfDomains, numberOfDomains + 1, localOrders, bitIndex,
varorder);
if (!st.hasMoreTokens()) {
break;
}
if (s.equals("_"))
numberOfDomains = 0;
else
throw new BDDException("bad token: " + s);
}
for (int i = 0; i < doms.length; ++i) {
if (!done[i]) {
throw new BDDException("missing domain #" + i + ": " + getDomain(i));
}
}
while (bitIndex < varorder.length) {
varorder[bitIndex] = bitIndex;
++bitIndex;
}
int[] test = new int[varorder.length];
System.arraycopy(varorder, 0, test, 0, varorder.length);
Arrays.sort(test);
for (int i = 0; i < test.length; ++i) {
if (test[i] != i)
throw new BDDException(test[i] + " != " + i);
}
return varorder;
}
/**
* Helper function for makeVarOrder().
*/
static int fillInVarIndices(BDDDomain[] doms, int domainIndex, int numDomains, int[][] localOrders, int bitIndex,
int[] varorder) {
// calculate size of largest domain to interleave
int maxBits = 0;
for (int i = 0; i < numDomains; ++i) {
BDDDomain d = doms[domainIndex + i];
maxBits = Math.max(maxBits, d.varNum());
}
// interleave the domains
for (int bitNumber = 0; bitNumber < maxBits; ++bitNumber) {
for (int i = 0; i < numDomains; ++i) {
BDDDomain d = doms[domainIndex + i];
if (bitNumber < d.varNum()) {
int di = d.getIndex();
int local = localOrders[di][bitNumber];
if (local >= d.vars().length) {
System.out.println("bug!");
}
if (bitIndex >= varorder.length) {
System.out.println("bug2!");
}
varorder[bitIndex++] = d.vars()[local];
}
}
}
return bitIndex;
}
/**** BIT VECTORS ****/
/**
* <p>
* Implementors must implement this factory method to create BDDBitVector
* objects of the correct type.
* </p>
*/
protected BDDBitVector createBitVector(int a) {
return new BDDBitVector(a) {
public BDDFactory getFactory() {
return BDDFactory.this;
}
};
}
/**
* <p>
* Implementors must implement this factory method to create BDDBitVector
* objects of the correct type.
* </p>
*/
protected BDDBitVector createBitVector(BigInteger i) {
return new BDDBitVector(i) {
public BDDFactory getFactory() {
return BDDFactory.this;
}
};
}
/**
* <p>
* Build a bit vector that is constant true or constant false.
* </p>
*
* <p>
* Compare to bvec_true, bvec_false.
* </p>
*/
public BDDBitVector buildVector(int bitnum, boolean b) {
BDDBitVector v = createBitVector(bitnum);
v.initialize(b);
return v;
}
/**
* <p>
* Build a bit vector that corresponds to a constant value.
* </p>
*
* <p>
* Compare to bvec_con.
* </p>
*/
public BDDBitVector constantVector(int bitnum, long val) {
BDDBitVector v = createBitVector(bitnum);
v.initialize(val);
return v;
}
/**
* Build a bit vector that corresponds to a constant value. The size of the
* vector is determined such that it suffices for holding the value.
*
* @param val
* @return
*/
public BDDBitVector constantVector(BigInteger val) {
BDDBitVector v = createBitVector(val);
return v;
}
public BDDBitVector constantVector(int bitnum, BigInteger val) {
BDDBitVector v = createBitVector(bitnum);
v.initialize(val);
return v;
}
/**
* <p>
* Build a bit vector using variables offset, offset+step, offset+2*step, ... ,
* offset+(bitnum-1)*step.
* </p>
*
* <p>
* Compare to bvec_var.
* </p>
*/
public BDDBitVector buildVector(int bitnum, int offset, int step) {
BDDBitVector v = createBitVector(bitnum);
v.initialize(offset, step);
return v;
}
/**
* <p>
* Build a bit vector using variables from the given BDD domain.
* </p>
*
* <p>
* Compare to bvec_varfdd.
* </p>
*/
public BDDBitVector buildVector(BDDDomain d) {
BDDBitVector v = createBitVector(d.varNum());
v.initialize(d);
return v;
}
/**
* <p>
* Build a bit vector using the given variables.
* </p>
*
* <p>
* compare to bvec_varvec.
* </p>
*/
public BDDBitVector buildVector(int[] var) {
BDDBitVector v = createBitVector(var.length);
v.initialize(var);
return v;
}
/**** CALLBACKS ****/
protected List<Object[]> gc_callbacks, reorder_callbacks, resize_callbacks;
/**
* <p>
* Register a callback that is called when garbage collection is about to occur.
* </p>
*
* @param o
* base object
* @param m
* method
*/
public void registerGCCallback(Object o, Method m) {
if (gc_callbacks == null)
gc_callbacks = new LinkedList<Object[]>();
registerCallback(gc_callbacks, o, m);
}
/**
* <p>
* Unregister a garbage collection callback that was previously registered.
* </p>
*
* @param o
* base object
* @param m
* method
*/
public void unregisterGCCallback(Object o, Method m) {
if (gc_callbacks == null)
throw new BDDException();
if (!unregisterCallback(gc_callbacks, o, m))
throw new BDDException();
}
/**
* <p>
* Register a callback that is called when reordering is about to occur.
* </p>
*
* @param o
* base object
* @param m
* method
*/
public void registerReorderCallback(Object o, Method m) {
if (reorder_callbacks == null)
reorder_callbacks = new LinkedList<Object[]>();
registerCallback(reorder_callbacks, o, m);
}
/**
* <p>
* Unregister a reorder callback that was previously registered.
* </p>
*
* @param o
* base object
* @param m
* method
*/
public void unregisterReorderCallback(Object o, Method m) {
if (reorder_callbacks == null)
throw new BDDException();
if (!unregisterCallback(reorder_callbacks, o, m))
throw new BDDException();
}
/**
* <p>
* Register a callback that is called when node table resizing is about to
* occur.
* </p>
*
* @param o
* base object
* @param m
* method
*/
public void registerResizeCallback(Object o, Method m) {
if (resize_callbacks == null)
resize_callbacks = new LinkedList<Object[]>();
registerCallback(resize_callbacks, o, m);
}
/**
* <p>
* Unregister a reorder callback that was previously registered.
* </p>
*
* @param o
* base object
* @param m
* method
*/
public void unregisterResizeCallback(Object o, Method m) {
if (resize_callbacks == null)
throw new BDDException();
if (!unregisterCallback(resize_callbacks, o, m))
throw new BDDException();
}
protected void gbc_handler(boolean pre, GCStats s) {
if (gc_callbacks == null) {
bdd_default_gbchandler(pre, s);
} else {
doCallbacks(gc_callbacks, new Integer(pre ? 1 : 0), s);
}
}
protected static void bdd_default_gbchandler(boolean pre, GCStats s) {
if (pre) {
if (s.freenodes != 0)
System.err.println(
"Starting GC cycle #" + (s.num + 1) + ": " + s.nodes + " nodes / " + s.freenodes + " free");
} else {
System.err.println(s.toString());
}
}
void reorder_handler(boolean b, ReorderStats s) {
if (b) {
s.usednum_before = getNodeNum();
s.time = System.currentTimeMillis();
} else {
s.time = System.currentTimeMillis() - s.time;
s.usednum_after = getNodeNum();
}
if (reorder_callbacks == null) {
bdd_default_reohandler(b, s);
} else {
doCallbacks(reorder_callbacks, new Boolean(b), s);
}
}
protected void bdd_default_reohandler(boolean prestate, ReorderStats s) {
int verbose = 1;
if (verbose > 0) {
if (prestate) {
System.out.println("Start reordering");
} else {
System.out.println("End reordering. " + s);
}
}
}
protected void resize_handler(int oldsize, int newsize) {
if (resize_callbacks == null) {
bdd_default_reshandler(oldsize, newsize);
} else {
doCallbacks(resize_callbacks, new Integer(oldsize), new Integer(newsize));
}
}
protected static void bdd_default_reshandler(int oldsize, int newsize) {
int verbose = 1;
if (verbose > 0) {
System.out.println("Resizing node table from " + oldsize + " to " + newsize);
}
}
protected void registerCallback(List<Object[]> callbacks, Object o, Method m) {
if (!Modifier.isPublic(m.getModifiers()) && !m.isAccessible()) {
throw new BDDException("Callback method not accessible");
}
if (!Modifier.isStatic(m.getModifiers())) {
if (o == null) {
throw new BDDException("Base object for callback method is null");
}
if (!m.getDeclaringClass().isAssignableFrom(o.getClass())) {
throw new BDDException("Base object for callback method is the wrong type");
}
}
callbacks.add(new Object[] { o, m });
}
protected boolean unregisterCallback(List<Object[]> callbacks, Object o, Method m) {
if (callbacks != null) {
for (Iterator<Object[]> i = callbacks.iterator(); i.hasNext();) {
Object[] cb = i.next();
if (o == cb[0] && m.equals(cb[1])) {
i.remove();
return true;
}
}
}
return false;
}
protected void doCallbacks(List<Object[]> callbacks, Object arg1, Object arg2) {
if (callbacks != null) {
for (Iterator<Object[]> i = callbacks.iterator(); i.hasNext();) {
Object[] cb = i.next();
Object o = cb[0];
Method m = (Method) cb[1];
try {
switch (m.getParameterTypes().length) {
case 0:
m.invoke(o, new Object[] {});
break;
case 1:
m.invoke(o, new Object[] { arg1 });
break;
case 2:
m.invoke(o, new Object[] { arg1, arg2 });
break;
default:
throw new BDDException("Wrong number of arguments for " + m);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException)
throw (RuntimeException) e.getTargetException();
if (e.getTargetException() instanceof Error)
throw (Error) e.getTargetException();
e.printStackTrace();
}
}
}
}
public int[] getAttrSizes() {
System.out.println("getAttrSizes() not implemented");
return null;
}
public BDD[] getXMem() {
System.out.println("getXMem() not implemented");
return null;
}
public BDD[] getYMem() {
System.out.println("getYMem() not implemented");
return null;
}
public BDD[] getZMem() {
System.out.println("getZMem() not implemented");
return null;
}
public BDD[] getZMemFirstItr() {
System.out.println("getZMemFirstItr() not implemented");
return null;
}
public BDD getFulfillBDD(int[] exjindices, int[] findices) {
System.out.println("getFulfillBDD not implemented");
return null;
}
public BDD getTowardsBDD(int[] exjindices, int[] tindices) {
System.out.println("getTowardsBDD not implemented");
return null;
}
public BDD getEnvViolationBDD(int[] iindices, int[] kindices) {
System.out.println("getEnvViolationBDD not implemented");
return null;
}
public BDD getGr1StarWinningStates() {
System.out.println("getGr1StarWinningStates() not implemented");
return null;
}
public boolean gr1StarGame(BDD[] sysJ, BDD[] envJ,
BDD[] sfaIni, BDD[] sfaTrans, BDD[] sfaTransToAcc, BDDVarSet[] sfaUnprimeStateVars, BDDVarSet[] sfaPrimeStateVars,
BDD sysIni, BDD envIni, BDD sysTrans,
BDD envTrans, BDDVarSet sysUnprimeVars, BDDVarSet envUnprimeVars, BDDVarSet sysPrimeVars,
BDDVarSet envPrimeVars, BDDPairing pairs, BDD[] sysTransList, BDD[] envTransList,
BDDVarSet[] sysQuantSets, BDDVarSet[] envQuantSets, boolean efp,
boolean eun, boolean fpr, boolean sca, boolean mem) {
System.out.println("gr1 star game not implemented");
return false;
}
public boolean gr1Game(BDD[] sysJ, BDD[] envJ, BDD sysIni, BDD envIni, BDD sysTrans, BDD envTrans,
BDDVarSet sysUnprimeVars, BDDVarSet envUnprimeVars, BDDVarSet sysPrimeVars, BDDVarSet envPrimeVars,
BDDPairing pairs, BDD[] sysTransList, BDD[] envTransList, BDDVarSet[] sysQuantSets,
BDDVarSet[] envQuantSets, boolean efp, boolean eun, boolean fpr, boolean sca) {
System.out.println("gr1 game not implemented");
return false;
}
public boolean gr1SeparatedGame(BDD[] sysJ, BDD[] envJ, BDD sysIni, BDD envIni, BDD sysTrans, BDD envTrans,
BDDVarSet sysUnprimeVars, BDDVarSet envUnprimeVars, BDDVarSet sysPrimeVars, BDDVarSet envPrimeVars,
BDDPairing pairs, BDD[] sysTransList, BDD[] envTransList, BDDVarSet[] sysQuantSets,
BDDVarSet[] envQuantSets, boolean efp, boolean eun, boolean fpr, boolean sca) {
System.out.println("gr1 game not implemented");
return false;
}
public boolean vacuityC(BDD[] justices, BDD ini, BDD trans, BDDVarSet primeVars, BDDPairing pairs, BDD targetJustice) {
System.out.println("vacuity in c not implemented");
return false;
}
public boolean gr1GameWithIncData(BDD[] sysJ, BDD[] envJ, BDD sysIni, BDD envIni, BDD sysTrans, BDD envTrans,
BDDVarSet sysUnprimeVars, BDDVarSet envUnprimeVars, BDDVarSet sysPrimeVars, BDDVarSet envPrimeVars,
BDDPairing pairs, boolean efp, boolean eun, boolean fpr, boolean sca, int incBitmap, BDD incStartZ,
BDD[] incZMem, BDD[] incZMemFirstItr, BDD[] incXMem, int jIdx, int incSizeD1, int incSizeD2,
int[] incSizeD3) {
System.out.println("gr1GameWithIncData not implemented");
return false;
}
public int getRabinZSize() {
System.out.println("getRabinZSize() not implemented");
return 0;
}
public int[] getRabinXSizes() {
System.out.println("getRabinXSizes() not implemented");
return null;
}
public BDD[] getRabinXMem() {
System.out.println("getRabinXMem() not implemented");
return null;
}
public BDD[] getRabinZMem() {
System.out.println("getRabinZMem() not implemented");
return null;
}
public boolean rabinGame(BDD[] sysJ, BDD[] envJ, BDD sysIni, BDD envIni, BDD sysTrans, BDD envTrans,
BDDVarSet sysUnprimeVars, BDDVarSet envUnprimeVars, BDDVarSet sysPrimeVars, BDDVarSet envPrimeVars,
BDDPairing pairs, BDD[] sysTransList, BDD[] envTransList, BDDVarSet[] sysQuantSets,
BDDVarSet[] envQuantSets, boolean efp, boolean eun, boolean fpr, boolean sca) {
System.out.println("rabin game not implemented");
return false;
}
public boolean rabinGameWithIncData(BDD[] sysJ, BDD[] envJ, BDD sysIni, BDD envIni, BDD sysTrans, BDD envTrans,
BDDVarSet sysUnprimeVars, BDDVarSet envUnprimeVars, BDDVarSet sysPrimeVars, BDDVarSet envPrimeVars,
BDDPairing pairs, boolean efp, boolean eun, boolean fpr, boolean sca, int incBitmap, BDD incStartZ,
BDD[] incZMem, BDD[] incXMem, int jIdx, int incSizeD1, int incSizeD2, int[] incSizeD3) {
System.out.println("rabinGameWithIncData not implemented");
return false;
}
public BDD getJusticesBDD(BDD[] sysJ, BDD[] envJ, int[] jindices, int[] iindices, int utilindex) {
System.out.println("getJusticesBDD not implemented");
return null;
}
public BDD getTransBDD(BDD sysIni, BDD envIni, BDD sysTrans, BDD envTrans, int[] jindices, int[] iindices, int utilindex) {
System.out.println("getTransBDD not implemented");
return null;
}
public BDD getFixpointsBDD(int[] jindices, int[] iindices, int[] kindices) {
System.out.println("getFixpointsBDD not implemented");
return null;
}
public BDD getFixpointsStarBDD(int[] jindices, int[] iindices, int[] kindices) {
System.out.println("getFixpointsStarBDD not implemented");
return null;
}
public BDD getJusticesStarBDD(BDD[] sysJ, BDD[] envJ, int[] jindices, int[] iindices, int utilindex) {
System.out.println("getJusticesStarBDD not implemented");
return null;
}
// GR(1) controller execution funcions
public void loadFixpointsJits(BDD fixpoints, int[] jindices, int[] iindices, int[] kindices, int[] ranks, BDDPairing pairs, BDDVarSet primeVars) {
System.out.println("loadFixpointsJits not implemented");
}
public void loadTransJits(BDD trans, int[] jindices, int[] iindices, int utilindex) {
System.out.println("loadTransJits not implemented");
}
public void loadJusticesJits(BDD justices, int[] jindices, int[] iindices, int utilindex, int n, int m) {
System.out.println("loadJusticesJits not implemented");
}
public BDD nextStatesJits(BDD current, BDD inputs, BDDPairing pairs, BDDVarSet unprimeVars) {
System.out.println("nextStatesJits not implemented");
return null;
}
public int initControllerJits(BDD inputs, BDDPairing pairs) {
System.out.println("initControllerJits not implemented");
return 0;
}
public void freeControllerJits() {
System.out.println("freeControllerJits not implemented");
}
public BDD getTransitionsJits() {
System.out.println("getTransitionsJits not implemented");
return null;
}
public BDD getInitialJits() {
System.out.println("getInitialJits not implemented");
return null;
}
public BDD[] getGr1StarXMem() {
System.out.println("getGr1StarXMem() game not implemented");
return null;
}
public BDD[] getGr1StarYMem() {
System.out.println("getGr1StarYMem() game not implemented");
return null;
}
public int[] getGr1StarTowardsExistIterNum() {
System.out.println("getGr1StarTowardsExistIterNum() game not implemented");
return null;
}
public int[] getGr1StarFulfillExistIterNum() {
System.out.println("getGr1StarFulfillExistIterNum() game not implemented");
return null;
}
public int getGr1StarEnvJViolationIterNum() {
System.out.println("getGr1StarEnvJViolationIterNum() game not implemented");
return 0;
}
public BDD[] getGr1StarFulfillExistMem() {
System.out.println("getGr1StarFulfillExistMem() game not implemented");
return null;
}
public BDD[] getGr1StarTowardsExistMem() {
System.out.println("getGr1StarTowardsExistMem() game not implemented");
return null;
}
public BDD[] getGR1StarEnvJViolationMem() {
System.out.println("getGR1StarEnvJViolationMem() game not implemented");
return null;
}
public int[] getGr1StarJusticeIterNum() {
System.out.println("getGr1StarJusticeIterNum() game not implemented");
return null;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.checks;
import java.util.ArrayList;
import java.util.List;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDDomain;
import tau.smlab.syntech.gamemodel.BehaviorInfo;
import tau.smlab.syntech.jtlv.Env;
/**
* Compute and keep popular BDDs for reuse
*
* @author shalom
*
*/
public class BDDBuilder {
private static BDD keptWinRegion = null;
private static BDD keptTrans = null;
private static BDD keptIni = null;
private static List<BehaviorInfo> justBehaviors = null;
private static List<BehaviorInfo> transBehaviors = null;
private static List<BehaviorInfo> iniBehaviors = null;
private static boolean keepBDDs = false;
private enum bType {INI, TRANS, JUST};
/**
* Set behaviors and activate the keepBDDs option
* @param behaviors
*/
public static void setBehaviors(List<BehaviorInfo> behaviors) {
justBehaviors = new ArrayList<BehaviorInfo>();
transBehaviors = new ArrayList<BehaviorInfo>();
iniBehaviors = new ArrayList<BehaviorInfo>();
iniBehaviors = allOfType(behaviors, bType.INI);
transBehaviors = allOfType(behaviors, bType.TRANS);
justBehaviors = allOfType(behaviors, bType.JUST);
keptWinRegion = null;
keptTrans = null;
keptIni = null;
keepBDDs = true;
}
/**
* get a copy of the win region when possible
*
* @param behaviors
* @return
*/
public static BDD getWinRegion(List<BehaviorInfo> behaviors) {
if (keepBDDs &&
eq(allOfType(behaviors, bType.TRANS), transBehaviors) &&
eq(allOfType(behaviors, bType.JUST), justBehaviors)) {
if (keptWinRegion==null) {
keptWinRegion = GR1Implication.computeWinRegion(behaviors);
}
return keptWinRegion.id();
} else {
return GR1Implication.computeWinRegion(behaviors);
}
}
/**
* get a copy of the transition relation when possible
* @param behaviors
* @return
*/
public static BDD getTrans(List<BehaviorInfo> behaviors) {
if (keepBDDs && eq(allOfType(behaviors, bType.TRANS), transBehaviors)) {
if (keptTrans==null) {
keptTrans = computeTrans(behaviors);
}
return keptTrans.id();
} else {
return computeTrans(behaviors);
}
}
/**
* get a copy of the initial states when possible
* @param behaviors
* @return
*/
public static BDD getIni(List<BehaviorInfo> behaviors) {
if (keepBDDs && eq(allOfType(behaviors, bType.INI), iniBehaviors)) {
if (keptIni==null) {
keptIni = computeIni(behaviors);
}
return keptIni.id();
} else {
return computeIni(behaviors);
}
}
/**
* Remove all behaviors and BDDs and lower the keepBDDs flag
*/
public static void release() {
if (keptWinRegion!=null) {
keptWinRegion.free();
}
if (keptTrans!=null) {
keptTrans.free();
}
if (keptIni!=null) {
keptIni.free();
}
keptWinRegion = null;
keptTrans = null;
keptIni = null;
justBehaviors = null;
transBehaviors = null;
iniBehaviors = null;
keepBDDs = false;
}
private static boolean eq(List<BehaviorInfo> a, List<BehaviorInfo> b) {
return a.containsAll(b) && b.containsAll(a);
}
/**
* get the initial states of the prefix
* @param pref
* @return init states
*/
private static BDD computeIni(List<BehaviorInfo> pref) {
BDD result = Env.TRUE();
for (BehaviorInfo b : pref) {
if (b.isInitial()) {
result.andWith(b.initial.id());
}
}
return clear(result);
}
/**
* compute transitions of the prefix
* @param pref
* @return Transition function
*/
private static BDD computeTrans(List<BehaviorInfo> pref) {
BDD result = Env.TRUE();
for (BehaviorInfo b : pref) {
if (b.isSafety()) {
result.andWith(b.safety.id());
}
}
return clear(result);
}
private static List<BehaviorInfo> allOfType(List<BehaviorInfo> pref, bType t) {
List<BehaviorInfo> all = new ArrayList<BehaviorInfo>();
for (BehaviorInfo b : pref) {
if (b.isJustice() && t==bType.JUST) {
all.add(b);
}
if (b.isSafety() && t==bType.TRANS) {
all.add(b);
}
if (b.isInitial() && t==bType.INI) {
all.add(b);
}
}
return all;
}
/**
* clear BDD from irrelevant domain values caused by domains which are not a power of 2
*
* @param b
* @return
*/
private static BDD clear(BDD b) {
for (BDDDomain d : b.support().getDomains()) {
b.andWith(d.domain());
}
return b;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.enumerate.printers;
import java.io.PrintStream;
import java.util.Vector;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.games.controller.enumerate.EnumStateI;
import tau.smlab.syntech.games.controller.enumerate.EnumStrategyI;
import tau.smlab.syntech.jtlv.Env;
public class SimpleTextPrinter implements EnumStrategyPrinter {
@Override
public void printController(PrintStream out, EnumStrategyI c) {
for (int i = 0; i < c.numOfStates(); i++) {
EnumStateI s = c.getState(i);
if (s.isInitial())
out.print("Initial ");
BDD prn = s.getData();
out.print("State " + i + " "
+ prn.toStringWithDomains(Env.stringer) + "\n");
Vector<EnumStateI> succ = s.getSuccessors();
if (succ.isEmpty()) {
out.print("\tWith no successors.");
} else {
EnumStateI[] all_succ = new EnumStateI[succ.size()];
succ.toArray(all_succ);
out.print("\tWith successors : " + all_succ[0].getStateId());
for (int j = 1; j < all_succ.length; j++)
out.print(", " + all_succ[j].getStateId());
}
if (c.isCalcStats()) {
out.print("\tDist From Ini: " + s.getDistFromIni());
}
out.println();
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gamemodel.util;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import tau.smlab.syntech.gamemodel.BehaviorInfo;
import tau.smlab.syntech.gamemodel.GameModel;
import tau.smlab.syntech.spectragameinput.translator.Tracer;
/**
* This class allows identification of model elements according to traces
*
* Their respective module (parts of monitors and counters are built into the system but their module label is AUX)
* Their type (pattrens and triggers are considered justices according to their non-aux behaviors)
* Their kind (pattrens and triggers are considered COMPLEX because they are env or sys with supporting aux,
* parts of monitors and counters are AUX, because they are listed as only aux behaviors)
*
* @author shalom
*
*/
public class TraceIdentifier {
GameModel gm = null;
protected List<BehaviorInfo> env = null;
protected List<BehaviorInfo> sys = null;
protected List<BehaviorInfo> aux = null;
public enum Module {SYS, ENV, AUX};
public enum Type { INI, SAFE, JUST;
public String toString() {
switch (this) {
case INI:
return "<Initial>";
case SAFE:
return "<Safety>";
case JUST:
return "<Justice>";
default:
return "*error*";
}
}
}
public enum Kind { COMPLEX, SIMPLE;
public String toString() {
switch (this) {
case COMPLEX:
return "<Complex>";
case SIMPLE:
return "<Simple GR(1)>";
default:
return "error";
}
}
}
public TraceIdentifier(GameModel gm) {
this.gm = gm;
env = new ArrayList<BehaviorInfo>(gm.getEnvBehaviorInfo());
sys = new ArrayList<BehaviorInfo>(gm.getSysBehaviorInfo());
aux = new ArrayList<BehaviorInfo>(gm.getAuxBehaviorInfo());
}
/**
* get all traces that build the system, including auxiliary behaviors
*
* @return list of traces
*/
public List<Integer> getSysTraces() {
List<Integer> envTraces = new ArrayList<Integer>();
List<Integer> traceList = new ArrayList<Integer>();
for (BehaviorInfo bi : env) {
singularAdd(envTraces, bi.traceId);
}
for (BehaviorInfo bi : sys) {
if (!envTraces.contains(bi.traceId)) {
singularAdd(traceList, bi.traceId);
}
}
for (BehaviorInfo bi : aux) {
if (!envTraces.contains(bi.traceId)) {
singularAdd(traceList, bi.traceId);
}
}
return traceList;
}
/**
* get all traces that build the environment
* @return list of traces
*/
public List<Integer> getEnvTraces() {
List<Integer> traceList = new ArrayList<Integer>();
for (BehaviorInfo bi : env) {
singularAdd(traceList, bi.traceId);
}
return traceList;
}
/**
* A trace is identified as ENV or SYS if at least one of its behaviors has it.
*
* @param t
* @return
*/
public Module getModule(Integer t) {
return in(env, t) ? Module.ENV : (in(sys, t) ? Module.SYS : Module.AUX);
}
/**
* This is the type in the sys or env module.
* Note !! Ones in aux pick the first one they see (for example there could be a ONCE in a monitor safety)
*
* @param t
* @return
*/
public Type getType(Integer t) {
List<BehaviorInfo> lookin = null;
Type ret = null;
switch (getModule(t)) {
case SYS:
lookin = sys;
break;
case ENV:
lookin = env;
break;
case AUX:
lookin = aux;
break;
}
for (BehaviorInfo bi : lookin) {
if (bi.traceId == t) {
ret = bi.isInitial() ? Type.INI : (bi.isSafety() ? Type.SAFE : Type.JUST);
break;
}
}
return ret;
}
/**
* Traces both in sys or env but not in aux are simple GR(1) elements
* Traces both in sys or env yet also in aux are complex (patterns, triggers, containing ONCE)
* Traces only in aux are auxiliary behaviors (monitors, counters), and are simple if they have just one behavior
*
* @param t
* @return
*/
public Kind getKind(Integer t) {
boolean inSys = in(sys, t);
boolean inEnv = in(env, t);
int countAux = countin(aux, t);
int countSys = countin(sys, t);
int countEnv = countin(env, t);
return ((inSys | inEnv) && (countAux>0 || countSys>1 || countEnv>1)) || countAux>1 ? Kind.COMPLEX : Kind.SIMPLE;
}
/**
* How many of specified type ate in the list
*
* @param lst
* @param t
* @return
*/
public int countType(List<Integer> lst, Type t) {
int ret = 0;
for (Integer trace : lst) {
if (getType(trace)==t) {
ret++;
}
}
return ret;
}
/** get a list of lines according to traces
*
* @param list
* @return
*/
public static String formatLines(List<Integer> list) {
String formatted = "< ";
for (Integer p : list) {
EObject obj=Tracer.getTarget(p);
formatted+= obj==null ? "untraced" : NodeModelUtils.getNode(Tracer.getTarget(p)).getStartLine() + " ";
}
return formatted + ">";
}
/**
* get a message about the line number
*
* @param b
* @return
*/
public static String getLine(Integer b) {
EObject obj=Tracer.getTarget(b);
return obj==null ? "<line cannot be traced>" : "At line " + NodeModelUtils.getNode(Tracer.getTarget(b)).getStartLine();
}
/**
* Format a message about a marked element
*
* @param b
* @return
*/
public String formatMarked(Integer b) {
return TraceIdentifier.getLine(b) + (getModule(b)==TraceIdentifier.Module.AUX ? " is an auxiliary" : " is a")
+ " behavior of kind " + getKind(b) +
(getKind(b)==TraceIdentifier.Kind.SIMPLE ? " and type " + getType(b) : "");
}
/**
* get the correct traces according to start line numbers
*
* @param traces
* @param lines
* @return
*/
public List<Integer> locateSysTraces(List<Integer> lines) {
List<Integer> traces = getSysTraces();
List<Integer> subTraces = new ArrayList<Integer>();
for (Integer l : lines) {
for (Integer t : traces) {
if (Tracer.getTarget(t)!=null & l==NodeModelUtils.getNode(Tracer.getTarget(t)).getStartLine()) {
singularAdd(subTraces, t);
continue;
}
}
}
return subTraces;
}
/**
* add making sure the is the only instance in list
*
* @param lst the list
* @param x the item
*/
private void singularAdd(List<Integer> lst, Integer x) {
if (!lst.contains(x)) {
lst.add(x);
}
}
/**
* Is the trace in one of the behaviors?
*
* @param lst
* @param who
* @return
*/
private boolean in(List<BehaviorInfo> lst, Integer who) {
return countin(lst, who) > 0;
}
/**
* How many of the trace is in one of the behaviors?
*
* @param lst
* @param who
* @return
*/
private int countin(List<BehaviorInfo> lst, Integer who) {
int num = 0;
for (BehaviorInfo bi : lst) {
if (bi.traceId == who) {
num++;
}
}
return num;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.ui.logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.time.Instant;
import java.util.HashMap;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
import tau.smlab.syntech.ui.preferences.PreferencePage;
public class SpectraLogger {
public static void logOperationStart(IFile specFile, String actionID) {
if (PreferencePage.isLoggerActive()) {
long timeStamp = Instant.now().getEpochSecond();
SpectraLogger.log(specFile, "TimeStamp-" + timeStamp + "-Start-" + actionID, timeStamp);
}
}
public static void logOperationDone(IFile specFile, String actionID, long time, boolean status) {
if (PreferencePage.isLoggerActive()) {
long timeStamp = Instant.now().getEpochSecond();
SpectraLogger.log(specFile,
"TimeStamp-" + timeStamp + "-Done-" + actionID + "-Took-" + time + "ms-Status-" + status,
timeStamp);
}
}
public static void logBuffer(IFile specFile, String actionID, String buffer) {
if (PreferencePage.isLoggerActive()) {
long timeStamp = Instant.now().getEpochSecond();
SpectraLogger.log(specFile, "TimeStamp-" + timeStamp + "-Operation-" + actionID + "-Buffer-" + buffer,
timeStamp);
}
}
public static void log(IFile specFile, String str, long timeStamp) {
IPath log_dir_path = specFile.getLocation().removeLastSegments(1).append("/spectra-logs");
File log_dir = log_dir_path.toFile();
if (!log_dir.exists()) {
log_dir.mkdir();
}
IPath spec_log_dir_path = log_dir_path.append("/" + specFile.getFullPath().removeFileExtension().lastSegment());
File dir = spec_log_dir_path.toFile();
if (!dir.exists()) {
dir.mkdir();
}
FileHandler handler = null;
try {
handler = new FileHandler(dir.getAbsolutePath().concat("/" + timeStamp + ".spectraXML"), true);
handler.setFormatter(new SpectraLoggerFormatter());
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Logger logger = Logger.getLogger(specFile.getLocation().toString());
logger.addHandler(handler);
saveNewSpecificationCopy(specFile, timeStamp, spec_log_dir_path);
logger.info(str);
handler.close();
}
private static void saveNewSpecificationCopy(IFile specFile, long timeStamp, IPath spec_log_dir_path) {
FileInputStream in = null;
FileOutputStream out = null;
try {
File myObj = spec_log_dir_path.append(timeStamp + ".spectraArxived").toFile();
myObj.createNewFile();
FileWriter myWriter = null;
in = new FileInputStream(specFile.getLocation().toFile());
out = new FileOutputStream(myObj);
int n;
while ((n = in.read()) != -1) {
out.write(n);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.games.controller.symbolic;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDVarSet;
import tau.smlab.syntech.gamemodel.PlayerModule;
import tau.smlab.syntech.jtlv.Env;
public class SymbolicControllerDeterminizer {
/**
* Creates a deterministic version of the specified symbolic controller {@code ctrl}, such that
* for any (initial) state there is at most one assignment to the (non primed) variables controlled by
* {@code detPlayer} module.
*
* @param ctrl non-deterministic symbolic controller
* @param detPlayer the player module by which the controller would become deterministic
* @param responderModule whether {@code detPlayer} is the system (responder) player or the environment player
* @return A deterministic version of the specified symbolic controller relative to the given player module.
*/
public static SymbolicController determinize(SymbolicController ctrl, PlayerModule detPlayer, boolean responderModule) {
if(responderModule) {
return determinize(ctrl, Env.union(detPlayer.getAllFields()), Env.unionPrime(detPlayer.getAllFields()));
}
//remove variables of the responder module from the controller
BDD transEx = ctrl.trans().exist(Env.globalPrimeVars().minus(Env.unionPrime(detPlayer.getAllFields())));
BDD iniEx = ctrl.initial().exist(Env.globalUnprimeVars().minus(Env.union(detPlayer.getAllFields())));
SymbolicController ctrlEx = new SymbolicController(iniEx, transEx);
//create a deterministic version of the controller with the removed variables of the responder module
SymbolicController detCtrl = determinize(ctrlEx, Env.union(detPlayer.getAllFields()), Env.unionPrime(detPlayer.getAllFields()));
ctrlEx.free();
SymbolicController resCtrl = new SymbolicController();
//add valid choices of the responder module to the new deterministic controller
resCtrl.setInit(ctrl.initial().and(detCtrl.initial()));
resCtrl.setTrans(ctrl.trans().and(detCtrl.trans()));
detCtrl.free();
return resCtrl;
}
/**
* Creates a deterministic version of the specified symbolic controller {@code ctrl}, such that
* for any (initial) state there is at most one assignment to the variables (iniDetVars) transDetVars that
* evaluates to true.
*
* @param ctrl non-deterministic symbolic controller
* @param transDetVars the variables set according to which the transition relation would be deterministic
* @param iniDetVars the variables set according to which the initial states would be deterministic
* @return A deterministic version of the specified symbolic controller relative to the two given variables sets.
*/
public static SymbolicController determinize(SymbolicController ctrl, BDDVarSet transDetVars, BDDVarSet iniDetVars) {
BDD detTrans, trans = ctrl.trans();
BDD detIni, ini = ctrl.initial();
detTrans = trans.determinizeController(transDetVars);
detIni = ini.determinizeController(iniDetVars);
return new SymbolicController(detIni, detTrans);
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.ui.preferences;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.RadioGroupFieldEditor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import tau.smlab.syntech.gamemodel.PlayerModule.TransFuncType;
import tau.smlab.syntech.games.gr1.GR1GameExperiments;
import tau.smlab.syntech.games.rabin.RabinGame;
import tau.smlab.syntech.jtlv.BDDPackage;
import tau.smlab.syntech.jtlv.BDDPackage.BBDPackageVersion;
import tau.smlab.syntech.ui.Activator;
/**
* This class represents a preference page that is contributed to the
* Preferences dialog. By subclassing <samp>FieldEditorPreferencePage</samp>, we
* can use the field support built into JFace that allows us to create a page
* that is small and knows how to save, restore and apply itself.
* <p>
* This page is used to modify preferences only. They are stored in the
* preference store that belongs to the main plug-in class. That way,
* preferences can be accessed directly via the preference store.
*/
public class PreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
public PreferencePage() {
super(GRID);
setPreferenceStore(Activator.getDefault().getPreferenceStore());
setDescription("General SYNTECH preferences:");
}
/**
* Creates the field editors. Field editors are abstractions of the common GUI
* blocks needed to manipulate various types of preferences. Each field editor
* knows how to save and restore itself.
*/
private RadioGroupFieldEditor engine;
private RadioGroupFieldEditor concCont;
private RadioGroupFieldEditor opts;
private RadioGroupFieldEditor reorder;
private RadioGroupFieldEditor synthesisMethod;
private BooleanFieldEditor determinize;
private BooleanFieldEditor reorderBeforeSave;
private BooleanFieldEditor isLoggerActive;
public void createFieldEditors() {
engine = new RadioGroupFieldEditor(PreferenceConstants.BDD_ENGINE_CHOICE, "BDD engine", 1,
new String[][] { { "&JTLV package -- pure Java implementation", "JTLV" },
{ "&CUDD package -- JNI access to C implementation", "CUDD" },
{ "CUDD package using &ADDs -- JNI access to C implementation", "CUDD_ADD" } },
getFieldEditorParent(), true);
opts = new RadioGroupFieldEditor(PreferenceConstants.OPT_CHOICE, "Optimization options", 1,
new String[][] { { "Disable optimizations", "none" }, { "All optimizations", "all" },
{ "Algorithms optimizations", "fp_opts" }, { "Symmetry detection", "sym" },
{ "Controlled predecessors optimizations", "cp_opts" } },
getFieldEditorParent(), true);
reorder = new RadioGroupFieldEditor(PreferenceConstants.REORDER_CHOICE, "Reorder strategy", 1,
new String[][] { { "Disable reorder (not recommended)", "none" }, { "Enable reorder", "reorder" },
{ "Enable reorder with grouping (variables and their next state copies)", "group" },
// { "Special reorder strategy", "special"}
}, getFieldEditorParent(), true);
synthesisMethod = new RadioGroupFieldEditor(PreferenceConstants.SYNTHESIS_METHOD, "Realizability checking method", 1,
new String[][] {{"Original GR(1) (3-fixed-points)", PreferenceConstants.SYNTHESIS_METHOD_GR1},
{"Do not force justice assumption violations (4 fixed-points)", PreferenceConstants.SYNTHESIS_METHOD_PITERMAN},
{"Kind realizability: do not force any assumption violations (reduction plus 4 fixed-points)", PreferenceConstants.SYNTHESIS_METHOD_PITERMAN_REDUCTION}
},
getFieldEditorParent(), true);
determinize = new BooleanFieldEditor(PreferenceConstants.DETERMINIZE,
"Determinize static symbolic controllers (can be slow)", getFieldEditorParent());
reorderBeforeSave = new BooleanFieldEditor(PreferenceConstants.REORDER_BEFORE_SAVE,
"Reorder BDD before save to reduce size", getFieldEditorParent());
isLoggerActive = new BooleanFieldEditor(PreferenceConstants.IS_LOGGER_ACTIVE,
"Use Spectra Logger", getFieldEditorParent());
concCont = new RadioGroupFieldEditor(PreferenceConstants.CONC_CONT_FORMAT, "Concrete Controller Format", 1,
new String[][] { { "CMP automaton (Mealy)", "CMP" }, { "JTLV text format", "JTLV" } },
getFieldEditorParent(), true);
addField(engine);
addField(opts);
addField(reorder);
addField(determinize);
addField(reorderBeforeSave);
addField(concCont);
addField(isLoggerActive);
addField(synthesisMethod);
// String engineChoice =
// this.getPreferenceStore().getString(PreferenceConstants.BDD_ENGINE_CHOICE);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
}
public static boolean isReorderEnabled() {
String val = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.REORDER_CHOICE);
return val.equals("reorder");
}
// public static boolean isSpecialReorderStrategy() {
// String val = Activator.getDefault().getPreferenceStore()
// .getString(PreferenceConstants.REORDER_CHOICE);
// return val.equals("special");
// }
public static boolean isGroupVarSelection() {
String val = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.REORDER_CHOICE);
return val.equals("group");
}
public static boolean isDeterminize() {
return Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.DETERMINIZE);
}
public static boolean isReorderBeforeSave() {
return Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.REORDER_BEFORE_SAVE);
}
public static boolean isLoggerActive() {
return Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.IS_LOGGER_ACTIVE);
}
public static BDDPackage getBDDPackageSelection() {
String val = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.BDD_ENGINE_CHOICE);
if (val.equals("JTLV")) {
return BDDPackage.JTLV;
} else if (val.equals("CUDD")) {
return BDDPackage.CUDD;
} else if (val.equals("CUDD_ADD")) {
return BDDPackage.CUDD_ADD;
}
System.out.println("No preference for BDD engine choice was found. Using as default the CUDD library");
return BDDPackage.CUDD;
}
public static BBDPackageVersion getBDDPackageVersionSelection() {
BDDPackage engineSelection = getBDDPackageSelection();
if (engineSelection.equals(BDDPackage.JTLV)) {
return BBDPackageVersion.DEFAULT;
}
// CUDD BDD package has been selected
return BBDPackageVersion.CUDD_3_0;
}
public static boolean hasSymmetryDetection() {
String val = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.OPT_CHOICE);
return val.equals("sym");
}
public static boolean hasOptSelection() {
String val = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.OPT_CHOICE);
return !val.equals("none");
}
public static void setOptSelection() {
String val = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.OPT_CHOICE);
boolean fp_opts = val.equals("all") || val.equals("fp_opts");
boolean cp_opts = val.equals("all") || val.equals("cp_opts");
GR1GameExperiments.DETECT_FIX_POINT_EARLY = fp_opts;
GR1GameExperiments.USE_FIXPOINT_RECYCLE = fp_opts;
GR1GameExperiments.STOP_WHEN_INITIALS_LOST = fp_opts;
GR1GameExperiments.SIMULTANEOUS_CONJUNCTION_ABSTRACTION = cp_opts;
RabinGame.DETECT_FIX_POINT_EARLY = fp_opts;
RabinGame.USE_FIXPOINT_RECYCLE = fp_opts;
RabinGame.STOP_WHEN_WIN_FROM_SOME_INITIALS = fp_opts;
RabinGame.SIMULTANEOUS_CONJUNCTION_ABSTRACTION = cp_opts;
// TMP - NOTE: the function relprod needed for this optimization is not
// implemented for ADDs
if (PreferencePage.getBDDPackageSelection().equals(BDDPackage.CUDD_ADD)) {
GR1GameExperiments.SIMULTANEOUS_CONJUNCTION_ABSTRACTION = false;
RabinGame.SIMULTANEOUS_CONJUNCTION_ABSTRACTION = false;
}
}
public static TransFuncType getTransFuncSelection(boolean isDDMin) {
String val = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.OPT_CHOICE);
if (val.equals("all") || val.equals("cp_opts")) {
return isDDMin ? TransFuncType.PARTIAL_DECOMPOSED_FUNC : TransFuncType.DECOMPOSED_FUNC;
}
return TransFuncType.SINGLE_FUNC;
}
// public static boolean getWellSepIncludeSys() {
// return
// "SYS".equals(Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.WELL_SEP_SYS));
// }
public static String getConcreteControllerFormat() {
return Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.CONC_CONT_FORMAT);
}
public static String getSynthesisMethod() {
return Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.SYNTHESIS_METHOD);
}
}<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.logs;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;
/**
* iterator over BDDs of a log
*
*/
public class BDDLogReader implements Iterable<BDD> {
private String fileName;
public BDDLogReader(String fileName) {
this.fileName = fileName;
}
/**
* translate a log entry to a BDD
*
* @param text
* @return
*/
private BDD toBDD(String text) {
if ("FALSE".equals(text)) {
return Env.FALSE();
}
if ("TRUE".equals(text)) {
return Env.TRUE();
}
String[] stateVals = text.replace("<", "").replace(">", "").replace(" ", "").split(",");
BDD res = Env.TRUE();
// iterate over all assignments
for (String asgmt : stateVals) {
String[] asgm = asgmt.split(":");
// check if variable exists
if (Env.getVar(asgm[0]) != null) {
BDD val = Env.getBDDValue(asgm[0], asgm[1]);
// check if value exists
if (val == null) {
throw new RuntimeException("Value " + asgm[1] + " undefined for variable " + asgm[0]);
} else {
res.andWith(val.id());
}
} else {
System.err.println("Warning: Variable " + asgm[0] + " from log does not exist and is ignored!");
}
}
return res;
}
@Override
public Iterator<BDD> iterator() {
try {
return new Iterator<BDD>() {
String line = null;
boolean isNext = false;
BufferedReader br = new BufferedReader(new FileReader(fileName));
/**
* check if we can read another line from the file
*/
@Override
public boolean hasNext() {
if (!isNext) {
try {
line = br.readLine();
} catch (IOException e) {
}
isNext = true;
}
return line != null;
}
/**
* convert next line to BDD
*/
@Override
public BDD next() {
if (!hasNext()) {
return null;
}
isNext = false;
return toBDD(line);
}
@Override
public void remove() {
}
};
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gameinput.model;
import java.io.Serializable;
import tau.smlab.syntech.gameinput.spec.SpecTraceable;
public class Counter implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2420031291078508480L;
public enum OverFlowMethod {
FALSE, KEEP, MODULO
};
// FALSE = Assumption to not exceed bounds.
// KEEP = Keep Min/ Max value when trying to exceed bounds.
// MODULO = Modulo(Max value)
private int traceId;
private String name;
private SpecTraceable iniPred;
private SpecTraceable incPred;
private SpecTraceable decPred;
private SpecTraceable resetPred;
private OverFlowMethod overFlowMethod;
private OverFlowMethod underFlowMethod;
private int lower;
private int upper;
/**
* @param traceId
* @param name
* @param incPred
* @param decPred
* @param resetPred
* @param overFlowMethod
* @param range
* @param iniPred
*/
public Counter(int traceId, String name, SpecTraceable incPred, SpecTraceable decPred,
SpecTraceable resetPred, OverFlowMethod overFlowMethod, OverFlowMethod underFlowMethod,
int lower, int upper, SpecTraceable iniPred) {
super();
this.traceId = traceId;
this.name = name;
this.iniPred = iniPred;
this.incPred = incPred;
this.decPred = decPred;
this.resetPred = resetPred;
this.overFlowMethod = overFlowMethod;
this.underFlowMethod = underFlowMethod;
this.lower = lower;
this.upper = upper;
}
public Counter(int traceId, String name) {
this.name = name;
this.traceId = traceId;
}
public void setTraceId(int traceId) {
this.traceId = traceId;
}
public void setName(String name) {
this.name = name;
}
public void setIncPred(SpecTraceable incPredicate) {
this.incPred = incPredicate;
}
public void setDecPred(SpecTraceable decPredicate) {
this.decPred = decPredicate;
}
public void setResetPred(SpecTraceable resetPredicate) {
this.resetPred = resetPredicate;
}
public void setOverFlowMethod(OverFlowMethod overFlowMethod) {
this.overFlowMethod = overFlowMethod;
}
public void setUnderFlowMethod(OverFlowMethod underFlowMethod) {
this.underFlowMethod = underFlowMethod;
}
public void setLower(int lower) {
this.lower = lower;
}
public void setUpper(int upper) {
this.upper = upper;
}
public void setIniPred(SpecTraceable initialConstraint) {
this.iniPred = initialConstraint;
}
public int getTraceId() {
return traceId;
}
public String getName() {
return name;
}
public SpecTraceable getIncPred() {
return incPred;
}
public SpecTraceable getResetPred() {
return resetPred;
}
public SpecTraceable getDecPred() {
return decPred;
}
public int getLower() {
return lower;
}
public int getUpper() {
return upper;
}
public OverFlowMethod getOverFlowMethod() {
return overFlowMethod;
}
public OverFlowMethod getUnderFlowMethod() {
return underFlowMethod;
}
public SpecTraceable getIniPred() {
return iniPred;
}
}
<file_sep>/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.gamemodel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;
public class GameModel {
private PlayerModule sys;
private PlayerModule env;
private Map<Integer, BDD> weights;
private List<BehaviorInfo> auxBehaviorInfo = new ArrayList<BehaviorInfo>();
private List<BehaviorInfo> sysBehaviorInfo = new ArrayList<BehaviorInfo>();
private List<BehaviorInfo> envBehaviorInfo = new ArrayList<BehaviorInfo>();
public PlayerModule getSys() {
return sys;
}
public void setSys(PlayerModule sys) {
this.sys = sys;
}
public PlayerModule getEnv() {
return env;
}
public void setEnv(PlayerModule env) {
this.env = env;
}
public Map<Integer, BDD> getWeights() {
return weights;
}
public void setWeights(Map<Integer, BDD> weights) {
this.weights = weights;
}
public List<BehaviorInfo> getEnvBehaviorInfo() {
return envBehaviorInfo;
}
public void addEnvBehaviorInfo(BehaviorInfo envBehaviorInfo) {
this.envBehaviorInfo.add(envBehaviorInfo);
}
public List<BehaviorInfo> getSysBehaviorInfo() {
return sysBehaviorInfo;
}
public void addSysBehaviorInfo(BehaviorInfo sysBehaviorInfo) {
this.sysBehaviorInfo.add(sysBehaviorInfo);
}
public List<BehaviorInfo> getAuxBehaviorInfo() {
return auxBehaviorInfo;
}
public void addAuxBehaviorInfo(BehaviorInfo auxBehaviorInfo) {
this.auxBehaviorInfo.add(auxBehaviorInfo);
}
public void updateSingleTransFunc() {
sys.createTransFromPartTrans();
env.createTransFromPartTrans();
}
public void resetSingleTransFunc() {
sys.resetSingleTrans();
env.resetSingleTrans();
}
public void free() {
Env.free(auxBehaviorInfo);
Env.free(sysBehaviorInfo);
Env.free(envBehaviorInfo);
if(this.weights != null) {
Env.free(this.weights);
}
sys.free();
env.free();
}
}
| a2d61f4b4e4e31c83f0c7a3ccd40cd39397aea14 | [
"Markdown",
"Java",
"INI"
] | 85 | Java | SpectraSynthesizer/spectra-synt | ff4b4d5fa284bb0b0d7e77129f9b36606a4e37dd | e04fe7adda9ac515f303f7a780fd52ab2640eaa1 | |
refs/heads/master | <repo_name>andreadelprete/gepetto-viewer-corba<file_sep>/pyplugins/gepetto/gui/__init__.py
from pythonwidget import Plugin
<file_sep>/include/gepetto/gui/meta.hh
// Copyright (c) 2015-2018, LAAS-CNRS
// Authors: <NAME> (<EMAIL>)
//
// This file is part of gepetto-viewer-corba.
// gepetto-viewer-corba 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
// 3 of the License, or (at your option) any later version.
//
// gepetto-viewer-corba is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// gepetto-viewer-corba. If not, see <http://www.gnu.org/licenses/>.
#ifndef GEPETTO_GUI_META_HH
#define GEPETTO_GUI_META_HH
#include <QString>
namespace gepetto {
namespace gui {
template <typename T> struct convertTo {
static inline T& from ( T& t) { return t; }
static inline const T& from (const T& t) { return t; }
};
template <> struct convertTo<std::string> {
static inline std::string from (const QString& in) { return in.toStdString(); };
};
template <typename T> struct Traits;
template <> struct Traits <CORBA::String_var> {
typedef CORBA::String_var type;
static inline type from (const QString& s) { return (const char*)s.toLocal8Bit().data(); }
static inline type from (const std::string& s) { return s.c_str(); }
};
template <> struct Traits <QString> {
typedef CORBA::String_var CORBA_t;
static inline CORBA_t to_corba (const QString& s) { return (const char*)s.toLocal8Bit().data(); }
};
template <typename In, typename Out, std::size_t Size>
inline void convertSequence (const In* in, Out (&out)[Size]) {
for (size_t i = 0; i < Size; ++i) out[i] = (Out)in[i];
}
template <typename In, typename Out>
inline void convertSequence (const In* in, Out* out, const std::size_t& s) {
for (size_t i = 0; i < s; ++i) out[i] = (Out)in[i];
}
}
}
#endif // GEPETTO_GUI_META_HH
<file_sep>/doc/main.hh
/// \mainpage Gepetto Viewer user interfaces
///
/// This package provides two compatible interfaces to vizualise robots:
/// \li a \ref gepetto_viewer_corba_introduction "command line interface in Python"
/// \li a \ref gepetto_gui_introduction "graphical user interface" which is fully compatible with the Python interface.
///
/// \defgroup pluginlist List of available plugins
///
/// \defgroup plugin Plugin interfaces
/// Interface of C++ and Python plugins.
///
/// \ingroup plugin
/// \{
/// \defgroup plugin_cpp C++ Plugin API
/// Descriptions of the available interfaces.
///
/// \defgroup plugin_python Python plugin API
/// These slots are available for Python scripting in plugins.
/// \}
<file_sep>/src/test-client-cpp.cc
//
// test-client-cpp.cc
// Test SceneViewer with C++ CORBA client interface.
//
// Created by <NAME> in December 2014.
// Copyright (c) 2014 LAAS-CNRS. All rights reserved.
//
#include <gepetto/viewer/corba/client.hh>
void se3ToCorba(CORBA::Float* corbaPosition, const se3::SE3& se3position)
{
Eigen::Quaternion<float> q(se3position.rotation());
corbaPosition[0] = se3position.translation()(0);
corbaPosition[1] = se3position.translation()(1);
corbaPosition[2] = se3position.translation()(2);
corbaPosition[3] = q.w();
corbaPosition[4] = q.x();
corbaPosition[5] = q.y();
corbaPosition[6] = q.z();
}
int main(int, const char **)
{
using namespace graphics;
using namespace corbaServer;
using namespace std;
Client client (0, NULL);
client.connect ();
se3::SE3 position1 = se3::SE3::Random();
se3::SE3 position2 = se3::SE3::Random();
se3::SE3 position3 = se3::SE3::Random();
se3::SE3 position4 = se3::SE3::Random();
se3::SE3 position5 = se3::SE3::Random();
CORBA::Float pos[7];
Client::WindowID windowId = client.gui()->createWindow("window1");
client.gui()->createScene("scene1");
client.gui()->addSceneToWindow("scene1",windowId);
client.gui()->addURDF("scene1/hrp2", "/local/mgeisert/devel/src/hrp2/hrp2_14_description/urdf/hrp2_14_capsule.urdf", "/local/mgeisert/devel/src/hrp2/");
sleep(5);
//vector<float> tri01 (3);
float pos1[3]= {1.,0.,0.};
float pos2[3] = {0.,1.,0.};
float pos3[3]= {0.,1.,1.};
float color[4] = {1.,1.,1.,1.};
client.gui()->addTriangleFace("scene1/triangle", pos1, pos2, pos3, color);
sleep(15);
se3ToCorba (pos, position1);
client.gui()->applyConfiguration("scene1/hrp2/RLEG_LINK0", pos);
se3ToCorba (pos, position2);
client.gui()->applyConfiguration("scene1/hrp2/RLEG_LINK1", pos);
se3ToCorba (pos, position3);
client.gui()->applyConfiguration("scene1/hrp2/LLEG_LINK1", pos);
se3ToCorba (pos, position4);
client.gui()->applyConfiguration("scene1/hrp2/LLEG_LINK2", pos);
se3ToCorba (pos, position5);
client.gui()->applyConfiguration("scene1/hrp2/BODY", pos);
client.gui()->refresh();
return 0;
}
<file_sep>/src/gui/CMakeLists.txt
#
# Copyright (c) 2015-2016 CNRS
# Authors: <NAME>
#
#
# This file is part of gepetto-gui
# gepetto-gui 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
# 3 of the License, or (at your option) any later version.
#
# gepetto-gui is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Lesser Public License for more details. You should have
# received a copy of the GNU Lesser General Public License along with
# gepetto-gui If not, see
# <http://www.gnu.org/licenses/>.
# Configure the project
INCLUDE_DIRECTORIES(${CMAKE_BINARY_DIR}/src)
SET (${PROJECT_NAME}_SOURCES
${CMAKE_BINARY_DIR}/src/gui/main.cc
settings.cc
windows-manager.cc
safeapplication.cc
mainwindow.cc
osgwidget.cc
pick-handler.cc
tree-item.cc
omniorbthread.cc
bodytreewidget.cc
ledindicator.cc
dialog/dialogloadrobot.cc
dialog/dialogloadenvironment.cc
dialog/pluginmanagerdialog.cc
shortcut-factory.cc
selection-handler.cc
selection-event.cc
action-search-bar.cc
node-action.cc
)
IF(GEPETTO_GUI_HAS_PYTHONQT)
INCLUDE_DIRECTORIES("${PYTHON_INCLUDE_DIR}" "${PYTHONQT_INCLUDE_DIR}")
SET (${PROJECT_NAME}_SOURCES
${${PROJECT_NAME}_SOURCES}
pythonwidget.cc)
SET (${PROJECT_NAME}_MOC
${${PROJECT_NAME}_HEADERS_MOC}
python-decorator.hh
)
ELSE (GEPETTO_GUI_HAS_PYTHONQT)
MESSAGE(STATUS "Skipping PythonQt settings")
SET (${PROJECT_NAME}_MOC
${${PROJECT_NAME}_HEADERS_MOC}
)
ENDIF(GEPETTO_GUI_HAS_PYTHONQT)
SET (${PROJECT_NAME}_HEADERS
${${PROJECT_NAME}_HEADERS_MOC}
${${PROJECT_NAME}_HEADERS_NO_MOC}
)
# Compile meta-objects and executable
IF(USE_QT4)
QT4_WRAP_CPP(${PROJECT_NAME}_HEADERS_MOCED ${${PROJECT_NAME}_MOC})
QT4_WRAP_UI(${PROJECT_NAME}_FORMS_HEADERS ${${PROJECT_NAME}_FORMS})
QT4_ADD_RESOURCES(${PROJECT_NAME}_RESOURCES_RCC ${${PROJECT_NAME}_RESOURCES})
INCLUDE(${QT_USE_FILE})
ELSE(USE_QT4)
QT5_WRAP_CPP(${PROJECT_NAME}_HEADERS_MOCED ${${PROJECT_NAME}_MOC})
QT5_WRAP_UI(${PROJECT_NAME}_FORMS_HEADERS ${${PROJECT_NAME}_FORMS})
QT5_ADD_RESOURCES(${PROJECT_NAME}_RESOURCES_RCC ${${PROJECT_NAME}_RESOURCES})
ENDIF(USE_QT4)
ADD_DEFINITIONS(${QT_DEFINITIONS})
ADD_EXECUTABLE(gepetto-gui ${${PROJECT_NAME}_SOURCES}
${${PROJECT_NAME}_HEADERS_MOCED}
${${PROJECT_NAME}_HEADERS_NO_MOC}
${${PROJECT_NAME}_FORMS_HEADERS}
${${PROJECT_NAME}_RESOURCES_RCC}
)
TARGET_LINK_LIBRARIES(gepetto-gui ${PROJECT_NAME} ${QT_LIBRARIES})
PKG_CONFIG_USE_DEPENDENCY(gepetto-gui gepetto-viewer)
PKG_CONFIG_USE_DEPENDENCY(gepetto-gui openscenegraph)
PKG_CONFIG_USE_DEPENDENCY(gepetto-gui openthreads)
PKG_CONFIG_USE_DEPENDENCY(gepetto-gui openscenegraph-osgQt)
PKG_CONFIG_USE_DEPENDENCY(gepetto-gui omniORB4)
IF (GEPETTO_GUI_HAS_PYTHONQT)
TARGET_LINK_LIBRARIES(gepetto-gui ${PYTHONQT_LIBRARIES})
ENDIF (GEPETTO_GUI_HAS_PYTHONQT)
TARGET_LINK_LIBRARIES(gepetto-gui ${Boost_LIBRARIES})
INSTALL(TARGETS gepetto-gui DESTINATION bin)
<file_sep>/examples/display-urdf.cc
//
// display-urdf.cc
// Test SceneViewer with C++ CORBA client interface.
//
// Created by <NAME> in June 2015.
// Copyright (c) 2014 LAAS-CNRS. All rights reserved.
//
#include <gepetto/viewer/corba/client.hh>
int main(int argc, const char ** argv)
{
using namespace graphics;
using namespace corbaServer;
if (argc != 3) {
std::cout << "Usage " << argv[0] << " <urdf-filename> <path-to-meshes>"
<< std::endl;
return 1;
}
Client client (0, NULL);
client.connect ();
Client::WindowID windowId = client.gui()->createWindow("urdf-display");
client.gui()->createScene("scene-urdf");
client.gui()->addSceneToWindow("scene-urdf",windowId);
client.gui()->addURDF("scene-urdf/urdf", argv[1], argv[2]);
client.gui()->refresh();
return 0;
}
<file_sep>/src/gui/osgwidget.cc
// Copyright (c) 2015-2018, LAAS-CNRS
// Authors: <NAME> (<EMAIL>)
//
// This file is part of gepetto-viewer-corba.
// gepetto-viewer-corba 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
// 3 of the License, or (at your option) any later version.
//
// gepetto-viewer-corba is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// gepetto-viewer-corba. If not, see <http://www.gnu.org/licenses/>.
#include "gepetto/gui/osgwidget.hh"
#include "gepetto/gui/mainwindow.hh"
#include <gepetto/gui/pick-handler.hh>
#include <boost/regex.hpp>
#include <QFileDialog>
#include <QProcess>
#include <QTextBrowser>
#include <osg/Camera>
#include <osg/DisplaySettings>
#include <osg/Geode>
#include <osg/Material>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osg/StateSet>
#include <osgGA/EventQueue>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/TrackballManipulator>
#include <osgUtil/IntersectionVisitor>
#include <osgUtil/PolytopeIntersector>
#include <osgViewer/View>
#include <osgViewer/ViewerEventHandlers>
#include <cassert>
#include <stdexcept>
#include <vector>
#include <QDebug>
#include <QKeyEvent>
#include <QWheelEvent>
#include <QVBoxLayout>
#include <gepetto/viewer/urdf-parser.h>
#include <gepetto/viewer/OSGManipulator/keyboard-manipulator.h>
#include <gepetto/gui/windows-manager.hh>
#include <gepetto/gui/selection-event.hh>
namespace gepetto {
namespace gui {
namespace
{
QRect makeRectangle( const QPoint& first, const QPoint& second )
{
// Relative to the first point, the second point may be in either one of the
// four quadrants of an Euclidean coordinate system.
//
// We enumerate them in counter-clockwise order, starting from the lower-right
// quadrant that corresponds to the default case:
//
// |
// (3) | (4)
// |
// -------|-------
// |
// (2) | (1)
// |
if( second.x() >= first.x() && second.y() >= first.y() )
return QRect( first, second );
else if( second.x() < first.x() && second.y() >= first.y() )
return QRect( QPoint( second.x(), first.y() ), QPoint( first.x(), second.y() ) );
else if( second.x() < first.x() && second.y() < first.y() )
return QRect( second, first );
else if( second.x() >= first.x() && second.y() < first.y() )
return QRect( QPoint( first.x(), second.y() ), QPoint( second.x(), first.y() ) );
// Should never reach that point...
return QRect();
}
}
OSGWidget::OSGWidget(WindowsManagerPtr_t wm,
const std::string & name,
MainWindow *parent, Qt::WindowFlags f ,
osgViewer::ViewerBase::ThreadingModel threadingModel)
: QWidget( parent, f )
, graphicsWindow_()
, wsm_ (wm)
, pickHandler_ (new PickHandler (this, wsm_))
, wid_ (-1)
, wm_ ()
, viewer_ (new osgViewer::Viewer)
, screenCapture_ ()
, process_ (new QProcess (this))
, showPOutput_ (new QDialog (this, Qt::Dialog | Qt::WindowCloseButtonHint | Qt::WindowMinMaxButtonsHint))
, pOutput_ (new QTextBrowser())
{
osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
osg::ref_ptr <osg::GraphicsContext::Traits> traits_ptr (new osg::GraphicsContext::Traits(ds));
traits_ptr->windowName = "Gepetto Viewer";
traits_ptr->x = this->x();
traits_ptr->y = this->y();
traits_ptr->width = this->width();
traits_ptr->height = this->height();
traits_ptr->windowDecoration = false;
traits_ptr->doubleBuffer = true;
traits_ptr->vsync = true;
// traits_ptr->sharedContext = 0;
graphicsWindow_ = new osgQt::GraphicsWindowQt ( traits_ptr );
osg::Camera* camera = viewer_->getCamera();
camera->setGraphicsContext( graphicsWindow_ );
camera->setClearColor( osg::Vec4(0.2f, 0.2f, 0.6f, 1.0f) );
camera->setViewport( new osg::Viewport(0, 0, traits_ptr->width, traits_ptr->height) );
camera->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(traits_ptr->width)/static_cast<double>(traits_ptr->height), 1.0f, 10000.0f );
viewer_->setKeyEventSetsDone(0);
osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
keyswitchManipulator->addMatrixManipulator( '2', "First person", new ::osgGA::KeyboardManipulator(graphicsWindow_));
keyswitchManipulator->selectMatrixManipulator (0);
viewer_->setCameraManipulator( keyswitchManipulator.get() );
screenCapture_ = new osgViewer::ScreenCaptureHandler (
new osgViewer::ScreenCaptureHandler::WriteToFile (
parent->settings_->captureDirectory + "/" + parent->settings_->captureFilename,
parent->settings_->captureExtension),
1);
viewer_->addEventHandler(screenCapture_);
viewer_->addEventHandler(new osgViewer::HelpHandler);
viewer_->addEventHandler(pickHandler_);
wid_ = wm->createWindow (name, viewer_, graphicsWindow_.get());
wm_ = wsm_->getWindowManager (wid_);
viewer_->setThreadingModel(threadingModel);
osgQt::GLWidget* glWidget = graphicsWindow_->getGLWidget();
//glWidget->setForwardKeyEvents(true);
QVBoxLayout* hblayout = new QVBoxLayout (this);
hblayout->setContentsMargins(1,1,1,1);
setLayout (hblayout);
hblayout->addWidget(glWidget);
setMinimumSize(10,10);
connect( &timer_, SIGNAL(timeout()), this, SLOT(update()) );
timer_.start(parent->settings_->refreshRate);
// Setup widgets to record movies.
process_->setProcessChannelMode(QProcess::MergedChannels);
connect (process_, SIGNAL (readyReadStandardOutput ()), SLOT (readyReadProcessOutput()));
showPOutput_->setModal(false);
showPOutput_->setLayout(new QHBoxLayout ());
showPOutput_->layout()->addWidget(pOutput_);
}
OSGWidget::~OSGWidget()
{
viewer_->setDone(true);
viewer_->removeEventHandler(pickHandler_);
pickHandler_ = NULL;
wm_.reset();
wsm_.reset();
}
void OSGWidget::paintEvent(QPaintEvent*)
{
wsm_->osgFrameMutex().lock();
viewer_->frame();
wsm_->osgFrameMutex().unlock();
}
graphics::WindowsManager::WindowID OSGWidget::windowID() const
{
return wid_;
}
graphics::WindowManagerPtr_t OSGWidget::window() const
{
return wm_;
}
WindowsManagerPtr_t OSGWidget::osg() const
{
return wsm_;
}
void OSGWidget::onHome()
{
viewer_->home ();
}
void OSGWidget::addFloor()
{
wsm_->addFloor("hpp-gui/floor");
}
void OSGWidget::toggleCapture (bool active)
{
MainWindow* main = MainWindow::instance();
if (active) {
QDir tmp ("/tmp");
tmp.mkpath ("gepetto-gui/record"); tmp.cd("gepetto-gui/record");
foreach (QString f, tmp.entryList(QStringList() << "img_0_*.jpeg", QDir::Files))
tmp.remove(f);
QString path = tmp.absoluteFilePath("img");
const char* ext = "jpeg";
osg ()->startCapture(windowID(), path.toLocal8Bit().data(), ext);
main->log("Saving images to " + path + "_*." + ext);
} else {
osg()->stopCapture(windowID());
QString outputFile = QFileDialog::getSaveFileName(this, tr("Save video to"), "untitled.mp4");
if (!outputFile.isNull()) {
if (QFile::exists(outputFile))
QFile::remove(outputFile);
QString avconv = "avconv";
QStringList args;
QString input = "/tmp/gepetto-gui/record/img_0_%d.jpeg";
args << "-r" << "50"
<< "-i" << input
<< "-vf" << "scale=trunc(iw/2)*2:trunc(ih/2)*2"
<< "-r" << "25"
<< "-vcodec" << "libx264"
<< outputFile;
qDebug () << args;
showPOutput_->setWindowTitle(avconv + " " + args.join(" "));
pOutput_->clear();
showPOutput_->resize(main->size() / 2);
showPOutput_->show();
process_->start(avconv, args);
}
}
}
void OSGWidget::readyReadProcessOutput()
{
pOutput_->append(process_->readAll());
}
} // namespace gui
} // namespace gepetto
<file_sep>/plugins/pyqcustomplot/decorator.hh
#include <qcustomplot.h>
#include <QObject>
void registerQCustomPlot ();
class QCustomPlotDecorator : public QObject
{
Q_OBJECT
public Q_SLOTS:
/// \name QCustomPlot
/// \{
QCustomPlot* new_QCustomPlot(QWidget* parent = 0)
{
return new QCustomPlot(parent);
}
void delete_QCustomPlot(QCustomPlot* o) //delete QCustomPlot object
{
delete o;
}
void clearGraphs(QCustomPlot* o)
{
o->clearGraphs();
}
QCPGraph* addGraph(QCustomPlot* o)
{
return o->addGraph();
}
void addPlottable(QCustomPlot* o, QCPAbstractPlottable* ap)
{
o->addPlottable(ap);
}
QCPGraph* graph(QCustomPlot* o, int graphnum)
{
return o->graph(graphnum);
}
void replot (QCustomPlot* o) //replot object to visualise new data
{
o->replot();
}
void show (QCustomPlot* o) //open new window with graph
{
o->show();
}
void setWindowTitle(QCustomPlot* o,QString title) //set title of window of graph
{
o->setWindowTitle(title);
}
void rescaleAxes(QCustomPlot* o, bool v = true) //rescale axis automatically if data does not fit
{
o->rescaleAxes(v);
}
QCPLayoutGrid* plotLayout (QCustomPlot* o) { return o->plotLayout (); }
void setAutoAddPlottableToLegend (QCustomPlot* o, bool v)
{
o->setAutoAddPlottableToLegend (v);
}
/// \param interaction See QCP::Interaction
void setInteraction(QCustomPlot* o, int interaction, bool enabled = true)
{
o->setInteraction((QCP::Interaction)interaction, enabled);
}
QCPAxis* xAxis (QCustomPlot* o) { return o->xAxis ; }
QCPAxis* xAxis2 (QCustomPlot* o) { return o->xAxis2; }
QCPAxis* yAxis (QCustomPlot* o) { return o->yAxis ; }
QCPAxis* yAxis2 (QCustomPlot* o) { return o->yAxis2; }
QCPLegend* legend (QCustomPlot* o) { return o->legend; }
QCPAxisRect* axisRect (QCustomPlot* o, int index=0) { return o->axisRect(index); }
/// \}
/// \name QCPAxis
/// \{
int selectedParts(const QCPAxis* a)
{
return a->selectedParts();
}
void setLabel(QCPAxis* a, const QString text)
{
a->setLabel(text);
}
void setRange(QCPAxis* a, double position, double size)
{
a->setRange(position, size);
}
void setAutoTicks(QCPAxis* a, bool on)
{
a->setAutoSubTicks(on);
}
void setAutoTickLabels(QCPAxis* a, bool on)
{
a->setAutoTickLabels(on);
}
void setTickVector(QCPAxis* a, const QVector<double> &ticks)
{
a->setTickVector(ticks);
}
void setTickVectorLabels(QCPAxis* a, const QVector<QString> &labels)
{
a->setTickVectorLabels(labels);
}
void setTickLength(QCPAxis* a, int inside, int outside)
{
a->setTickLength(inside,outside);
}
void setSubTickLength(QCPAxis* a, int inside, int outside)
{
a->setSubTickLength(inside, outside);
}
double pixelToCoord(QCPAxis* a, double pixel)
{
return a->pixelToCoord(pixel);
}
/// \}
/// \name QCPGraph
/// \{
QCPGraph* new_QCPGraph (QCPAxis* key, QCPAxis* value) { return new QCPGraph (key, value); }
void delete_QCPGraph (QCPGraph* g) { delete g; }
void setData (QCPGraph* g, const QVector<double> &keys, const QVector<double> &values)
{
g->setData(keys,values);
}
void addData (QCPGraph* g, const QVector<double> &keys, const QVector<double> &values)
{
g->addData(keys,values);
}
void addData (QCPGraph* g, const double &key, const double &value)
{
g->addData(key,value);
}
void clearData (QCPGraph* o) { o->clearData (); }
/// \}
/// \name QCPCurve
/// \{
QCPCurve* new_QCPCurve (QCPAxis* key, QCPAxis* value) { return new QCPCurve (key, value); }
void delete_QCPCurve (QCPCurve* g) { delete g; }
void setData (QCPCurve* c, const QVector<double> &keys, const QVector<double> &values)
{
c->setData(keys,values);
}
void addData (QCPCurve* c, const QVector<double> &ts, const QVector<double> &keys, const QVector<double> &values)
{
c->addData(ts, keys,values);
}
void clearData (QCPCurve* o) { o->clearData (); }
/// \}
/// \name QCPBars
/// \{
QCPBars* new_QCPBars (QCPAxis* key, QCPAxis* value) { return new QCPBars (key, value); }
void delete_QCPBars (QCPBars* g) { delete g; }
void setData (QCPBars* c, const QVector<double> &keys, const QVector<double> &values)
{
c->setData(keys,values);
}
void addData (QCPBars* c, const QVector<double> &keys, const QVector<double> &values)
{
c->addData(keys,values);
}
void clearData (QCPBars* o) { o->clearData (); }
/// \}
/// \name QCPAbstractPlottable
/// \{
void rescaleAxes(QCPAbstractPlottable* ap, bool v = true)
{
ap->rescaleAxes(v);
}
void setName (QCPAbstractPlottable* ap, const QString &n)
{
ap->setName(n);
}
void setPen (QCPAbstractPlottable* ap, const QPen &pen)
{
ap->setPen(pen);
}
/// \}
/// \name QCPLayerable
/// \{
void setVisible (QCPLayerable* l, const bool &v)
{
l->setVisible(v);
}
/// \}
/// \name QCPLayoutGrid
/// \{
void insertRow (QCPLayoutGrid* lg, int row) //insert row above graph
{
lg->insertRow(row);
}
void insertColumn (QCPLayoutGrid* lg, int column) //insert column above graph
{
lg->insertColumn(column);
}
void addElement (QCPLayoutGrid* lg, int row, int column, QCPLayoutElement *element) //add text to graph at row,column
{
lg->addElement(row,column,element);
}
/// \}
/// \name QCPAxisRect
/// \{
void setRangeZoomAxes (QCPAxisRect* ar, QCPAxis* horizontal, QCPAxis* vertical)
{
ar->setRangeZoomAxes (horizontal, vertical);
}
/// \}
};
| f4b0ff3bf0b88d08292308076404c799542d13f6 | [
"Python",
"CMake",
"C++"
] | 8 | Python | andreadelprete/gepetto-viewer-corba | 7116c02e8c8b33d55e952a326bc8e15d5fd770d2 | 8ed907f48dfc399e96b97dd1021575d0fa17d652 | |
refs/heads/master | <repo_name>SP2224/macdown-site-django<file_sep>/base/context_processors.py
from sparkle.models import Channel, Version
from .models import macdown
def latest_version(request):
try:
latest_version = macdown.active_versions().latest()
except Version.DoesNotExist:
latest_version = None
return {'latest_version': latest_version}
def channels(request):
return {'channels': Channel.objects.all()}
<file_sep>/downloads/views.py
from django.http import Http404
from django.views.generic import RedirectView
from sparkle.models import Version
from base.models import macdown
class VersionView(RedirectView):
permanent = False
def get_version(self, **kwargs):
try:
return macdown.versions.get(**kwargs)
except Version.DoesNotExist:
raise Http404
def get_redirect_url(self, *args, **kwargs):
return self.get_version(**kwargs).update_url
class LatestVersionView(VersionView):
def get_version(self, **kwargs):
return macdown.active_versions().latest()
version = VersionView.as_view()
latest = LatestVersionView.as_view()
<file_sep>/downloads/urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^latest/$', views.latest, name='latest'),
url(r'^v(?P<short_version>\d+(?:\.\w+)+)/$', views.version,
name='short_version'),
url(r'^(?P<version>[\.\d]+)/$', views.version, name='version'),
)
<file_sep>/history/urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.all_, name='all'),
url(r'^(?P<slug>[\w-]+)/$', views.channel, name='channel'),
)
<file_sep>/downloads/tests.py
from django.test import TestCase, Client
from nose.tools import assert_equal, assert_not_equal
from sparkle.models import Version
class DownloadTests(TestCase):
"""Tests for download link generation.
"""
fixtures = ('macdown', 'macdown_data')
def test_version_absolute_url(self):
# Version with readable tag.
version = Version.objects.get(short_version='0.1.2')
assert_equal(version.get_absolute_url(), '/download/v0.1.2/')
# Version without readable tag.
version = Version.objects.get(version='217')
assert_equal(version.get_absolute_url(), '/download/217/')
def test_version(self):
client = Client()
# Resolve short version string.
response = client.get('/download/v0.1.2/')
assert_equal(response.status_code, 302)
assert_equal(
response['Location'],
'https://github.com/MacDownApp/macdown/releases/download/v0.1.2/'
'MacDown.app.zip',
)
# Resolve version number.
response = client.get('/download/217/')
assert_equal(response.status_code, 302)
assert_equal(response['Location'], 'http://d.pr/f/3qn7+')
def test_latest_version(self):
client = Client()
# Should point to the real lastest active version.
response = client.get('/download/latest/')
location = response['Location']
assert_equal(response.status_code, 302)
# Should not point to a newer, but non-active version.
response = client.get('/download/v0.1.2/')
assert_equal(location, response['Location'])
response = client.get('/download/217/')
assert_not_equal(location, response['Location'])
<file_sep>/sparkle/migrations/0002_auto_20140701_1935.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('sparkle', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Channel',
fields=[
('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),
('name', models.CharField(verbose_name='name', max_length=50)),
('slug', models.SlugField(verbose_name='slug', unique=True)),
],
options={
'verbose_name': 'channel',
'verbose_name_plural': 'channels',
},
bases=(models.Model,),
),
migrations.AlterModelOptions(
name='version',
options={'ordering': ('-publish_at',), 'verbose_name': 'version', 'verbose_name_plural': 'versions', 'get_latest_by': 'version'},
),
migrations.AddField(
model_name='application',
name='default_channel',
field=models.ForeignKey(null=True, verbose_name='default channel', to='sparkle.Channel'),
preserve_default=True,
),
migrations.AddField(
model_name='version',
name='channels',
field=models.ManyToManyField(verbose_name='channels', to='sparkle.Channel'),
preserve_default=True,
),
]
<file_sep>/history/models.py
from django.core.urlresolvers import reverse
from sparkle.models import Channel
def channel_get_absolute_url(obj):
return reverse('history:channel', kwargs={'slug': obj.slug})
Channel.get_absolute_url = channel_get_absolute_url
<file_sep>/sparkle/forms/__init__.py
from django import forms
from .widgets import PopupGhostdownInput
class VersionAdminForm(forms.ModelForm):
class Meta:
fields = (
'application', 'channels', 'title', 'version', 'short_version',
'dsa_signature', 'length', 'release_notes',
'minimum_system_version', 'update_url', 'publish_at',
)
<file_sep>/base/tests.py
from django.test import TestCase
from nose.tools import assert_equal
from sparkle.models import Application
from .models import macdown
class BaseTests(TestCase):
"""Tests for base module.
"""
fixtures = ('macdown', 'macdown_data')
def test_macdown(self):
assert_equal(macdown, Application.objects.get(slug='macdown'))
<file_sep>/sparkle/views.py
from django.utils.translation import ugettext as _
from django.http import Http404
from django.views.generic.detail import DetailView
from .models import (
Application, Channel, SystemProfileReport, SystemProfileReportRecord,
)
class ChannelView(DetailView):
model = Channel
context_object_name = 'channel'
slug_url_kwarg = 'channel_slug'
content_type = 'application/xml'
template_name = 'sparkle/appcast.xml'
def get_object(self, queryset=None):
try:
self.application = Application.objects.get(
slug=self.kwargs['app_slug'],
)
except Application.DoesNotExist:
raise Http404(
_("No {verbose_name} found matching the query").format(
verbose_name=Application._meta.verbose_name,
)
)
if self.slug_url_kwarg not in self.kwargs:
obj = self.application.default_channel
else:
obj = super(ChannelView, self).get_object(queryset)
return obj
def get_context_data(self, **kwargs):
data = super(ChannelView, self).get_context_data(**kwargs)
data.update({
'application': self.application,
'active_versions': self.application.active_versions(self.object)
})
return data
def render_to_response(self, context, **response_kwargs):
"""Record system profile reports before we send out the response.
"""
if self.request.GET:
# Create a report and records of the keys/values
report = SystemProfileReport.objects.create(
ip_address=self.request.META.get('REMOTE_ADDR'),
)
for key in self.request.GET:
SystemProfileReportRecord.objects.create(
report=report, key=key, value=self.request.GET[key],
)
return super(ChannelView, self).render_to_response(
context, **response_kwargs
)
channel = ChannelView.as_view()
<file_sep>/blog/posts.py
import os
import re
import yaml
from django.utils.functional import cached_property
from django.conf import settings
from django.core.urlresolvers import reverse
from django.apps import apps
from django.template import TemplateDoesNotExist
from base.markdown import render
FRONT_MATTER_PATTERN = re.compile(r'^---\n(.*?\n)---', re.DOTALL)
class PostDoesNotExist(TemplateDoesNotExist):
pass
class Post:
FILENAME_PATTERN = re.compile(r'^(\d+)-([\w-]+)$')
def __init__(self, filename, dirpath=None):
filename, ext = os.path.splitext(filename)
match = self.FILENAME_PATTERN.match(filename)
if match is None:
raise PostDoesNotExist(
os.path.join(dirpath, ''.join([filename, ext]))
)
self.id = int(match.group(1))
self.slug = match.group(2)
self.renderer = None
if dirpath is None:
dirpath = default_post_dir
self.dirpath = dirpath
self.filename = ''.join([filename, ext])
def __getattr__(self, key):
try:
value = self.meta[key]
except KeyError:
raise AttributeError(key)
return value
@property
def abspath(self):
return os.path.join(self.dirpath, self.filename)
@cached_property
def file_content(self):
"""Returns a 2-tuple (meta, content).
"""
full_content = self.read()
front_matter, offset = get_front_matter(full_content)
return (front_matter, full_content[offset:])
@cached_property
def meta(self):
return self.file_content[0]
@cached_property
def rendered_content(self):
self.renderer, rendered = render(self.file_content[1])
return rendered
def get_absolute_url(self):
return reverse('blog:post', kwargs={'id': self.id, 'slug': self.slug})
def read(self):
return load_post_source(self.filename, self.dirpath)
def calculate_post_dir():
app_config = apps.get_app_config('blog')
return os.path.join(app_config.path, 'posts')
default_post_dir = calculate_post_dir()
def get_post_filelist(post_dir=None):
if post_dir is None:
post_dir = default_post_dir
filelist = os.listdir(post_dir)
filelist.sort()
return filelist
# id => post instance
_post_cache = {}
def get_post_list(post_dir=None):
posts = []
for filename in reversed(get_post_filelist(post_dir)):
try:
base, _ = os.path.splitext(filename)
post_id = int(Post.FILENAME_PATTERN.match(base).group(1))
post = _post_cache[post_id]
except (AttributeError, KeyError):
try:
post = Post(filename)
except PostDoesNotExist:
continue
_post_cache[post.id] = post
if post.title:
posts.append(post)
return posts
def get_post(post_id, post_dir=None):
try:
post = _post_cache[post_id]
except KeyError:
post = Post(get_post_filename(id=post_id, post_dir=post_dir))
_post_cache[post_id] = post
return post
def get_post_filename(id, post_dir=None):
prefix_pattern = re.compile(r'^0*{id}-'.format(id=id))
for filename in get_post_filelist(post_dir):
if prefix_pattern.match(filename):
return filename
if post_dir is None:
post_dir = default_post_dir
raise PostDoesNotExist(
'ID {id} in directory {dir}'.format(id=id, dir=post_dir)
)
def get_post_abspath(filename, post_dir=None):
if post_dir is None:
post_dir = default_post_dir
return os.path.join(post_dir, filename)
def load_post_source(filename, post_dir=None):
filepath = get_post_abspath(filename, post_dir)
try:
with open(filepath, 'rb') as f:
return f.read().decode(settings.FILE_CHARSET)
except IOError:
pass
raise PostDoesNotExist(filepath)
def get_front_matter(markdown):
"""Returns a 2-tuple (front_matter, content_offset)
"""
front_matter = None
offset = 0
match = FRONT_MATTER_PATTERN.search(markdown)
if match:
try:
front_matter = yaml.load(match.group(1))
except yaml.YAMLError:
pass
else:
offset = match.end(0) + 1 # Eat newline after closing "---"
return (front_matter, offset)
<file_sep>/blog/views.py
from django.http import Http404, HttpResponsePermanentRedirect
from django.views.generic import TemplateView
from .posts import PostDoesNotExist, get_post_list, get_post
from .utils import resolve_prism_languages
class PostListView(TemplateView):
template_name = 'blog/post_list.html'
def get_context_data(self, **kwargs):
posts = get_post_list()
data = super().get_context_data()
data.update({'posts': posts})
return data
class PostDetailView(TemplateView):
template_name = 'blog/post_detail.html'
def get(self, request, *args, **kwargs):
post_id = int(kwargs['id'])
post_slug = kwargs.get('slug')
try:
post = get_post(post_id)
except PostDoesNotExist:
raise Http404
if post.slug != post_slug or kwargs['id'] != str(post_id):
canonical_url = post.get_absolute_url()
return HttpResponsePermanentRedirect(redirect_to=canonical_url)
self.post = post
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
try:
page_meta = self.post.meta
content = self.post.rendered_content
renderer = self.post.renderer
assert page_meta is not None
assert renderer is not None
except (AssertionError, PostDoesNotExist):
raise Http404
data = super().get_context_data()
data.update({
'post': self.post,
'page': page_meta,
'content': content,
'languages': resolve_prism_languages(renderer.languages),
})
return data
post_list = PostListView.as_view()
post_detail = PostDetailView.as_view()
<file_sep>/__/wsgi.py
"""
WSGI config for macdown project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
# This needs to be set BEFORE Cling is imported.
# https://github.com/kennethreitz/dj-static/issues/28
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '__.settings.deploy')
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
<file_sep>/__/settings/local_uranusjr.py
from .base import * # noqa
SECRET_KEY = '!)<KEY>'
DEBUG = True
TEMPLATE_DEBUG = True
DATABASES['default'] = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
<file_sep>/base/templatetags/base_tags.py
from __future__ import division
from django.utils.translation import ugettext as _
from django.template import Library
from django.template.defaultfilters import stringfilter
register = Library()
@register.simple_tag(takes_context=True)
def absolute_uri(context, path):
return context['request'].build_absolute_uri(path)
@register.filter
@stringfilter
def volumize(value):
try:
value = float(value)
except ValueError:
value = 0
if value == 0:
return _('0 bytes')
elif value == 1:
return _('1 byte')
for unit in (_('bytes'), _('KB'), _('MB'), _('GB'),):
if -1024 < value < 1024:
return _('{value:3.1f} {unit}').format(value=value, unit=unit)
value /= 1024
return '{value:3.1f} {unit}'.format(value=value, unit=_('TB'))
<file_sep>/sparkle/migrations/0003_auto_20150411_1654.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('sparkle', '0002_auto_20140701_1935'),
]
operations = [
migrations.AlterField(
model_name='systemprofilereport',
name='ip_address',
field=models.GenericIPAddressField(verbose_name='IP address'),
preserve_default=True,
),
migrations.AlterField(
model_name='version',
name='application',
field=models.ForeignKey(related_name='versions', to='sparkle.Application', verbose_name='application'),
preserve_default=True,
),
migrations.AlterField(
model_name='version',
name='channels',
field=models.ManyToManyField(related_name='versions', verbose_name='channels', to='sparkle.Channel'),
preserve_default=True,
),
]
<file_sep>/blog/feeds.py
from django.core.urlresolvers import reverse
from django.utils import feedgenerator
from django.utils.translation import ugettext_lazy as _
from django.contrib.syndication.views import Feed
from .posts import get_post_list
MACDOWN_DESCRIPTION = _(
'<p>MacDown is an open source Markdown editor for OS X, released under '
'the MIT License. It is heavily influenced by '
'<a href="https://twitter.com/chenluois"><NAME></a>’s '
'<a href="http://mouapp.com">Mou</a>.</p>'
)
class PostsFeed(Feed):
"""Common parent class for RSS and Atom feeds
"""
title = _('The MacDown Blog')
description = MACDOWN_DESCRIPTION
def link(self):
return reverse('blog:list')
def items(self):
return get_post_list()
def item_title(self, item):
return item.title
def item_description(self, item):
return item.rendered_content
def item_link(self, item):
return item.get_absolute_url()
class PostsRss201rev2Reed(PostsFeed):
feed_type = feedgenerator.Rss201rev2Feed
class PostsAtom1Feed(PostsFeed):
feed_type = feedgenerator.Atom1Feed
rss201rev2 = PostsRss201rev2Reed()
atom1 = PostsAtom1Feed()
<file_sep>/pages/urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.home, name='home'),
url(r'^features/$', views.features, name='features'),
url(r'^(?P<name>[\w-]+)/$', views.page, name='page'),
)
<file_sep>/history/views.py
from django.http import Http404
from django.core.urlresolvers import reverse_lazy
from django.views.generic import ListView
from sparkle.models import Channel
from base.models import macdown
class AllHistoryView(ListView):
def get_queryset(self):
return macdown.active_versions()
class ChannelHistoryView(ListView):
def get_queryset(self):
try:
self.channel = Channel.objects.get(slug=self.kwargs.get('slug'))
except Channel.DoesNotExist:
raise Http404
return macdown.active_versions(channel=self.channel)
def get_context_data(self):
data = super().get_context_data()
data.update({'channel': self.channel})
return data
all_ = AllHistoryView.as_view()
channel = ChannelHistoryView.as_view()
<file_sep>/sparkle/urls.py
from django.conf.urls import patterns, url
from .views import channel
urlpatterns = patterns(
'',
url(r'^(?P<app_slug>[\w-]+)/appcast\.xml$', channel,
name='sparkle_application_default_channel'),
url(r'^(?P<app_slug>[\w-]+)/(?P<channel_slug>[\w-]+)/appcast\.xml$',
channel, name='sparkle_application_channel')
)
<file_sep>/blog/tests.py
import os
import tempfile
from django.test import TestCase
from nose.tools import assert_equal, assert_raises
from . import posts
EXAMPLE_POST_CONTENT = (
"""---
title: Test Post
author: <NAME>
---
Lorem ipsum.
""")
class PostDirTests(TestCase):
"""Tests for Post lookup-related things.
"""
def setUp(self):
self.post_dir = os.path.join(os.path.dirname(__file__), 'posts')
def test_post_dir(self):
assert_equal(posts.default_post_dir, self.post_dir)
def test_get_post_abspath(self):
post_path = os.path.join(self.post_dir, 'foo')
assert_equal(posts.get_post_abspath('foo'), post_path)
def test_does_not_exist(self):
with assert_raises(posts.PostDoesNotExist):
posts.Post('loremipsum', self.post_dir)
def test_default_dir(self):
post = posts.Post('01-the-macdown-blog.md')
assert_equal(post.dirpath, self.post_dir)
class PostTests(TestCase):
"""Tests for Post model.
"""
def setUp(self):
fd, path = tempfile.mkstemp(prefix='1-', suffix='.md')
f = os.fdopen(fd, 'w')
f.write(EXAMPLE_POST_CONTENT)
f.close()
dirpath, filename = os.path.split(path)
self.post = posts.Post(filename, dirpath)
self.filename = filename
def tearDown(self):
os.remove(self.post.abspath)
def test_load(self):
pass # If this fails, Post initialization failed.
def test_filename(self):
assert_equal(self.post.filename, self.filename)
def test_file_content(self):
fm, content = self.post.file_content
assert_equal(fm, {'title': 'Test Post', 'author': '<NAME>'})
assert_equal(content.strip(), 'Lorem ipsum.')
def test_meta(self):
assert_equal(self.post.meta, {
'title': 'Test Post', 'author': '<NAME>',
})
assert_equal(self.post.title, 'Test Post')
assert_equal(self.post.author, '<NAME>')
with assert_raises(AttributeError):
self.post.foobar
def test_rendered_content(self):
assert_equal(self.post.rendered_content, '<p>Lorem ipsum.</p>\n')
def test_get_absolute_url(self):
# Strip "1-" and ".md" from filename to get the slug.
expected = '/blog/post/1/{slug}/'.format(slug=self.filename[2:-3])
assert_equal(self.post.get_absolute_url(), expected)
<file_sep>/pages/views.py
from django.http import Http404
from django.template.base import TemplateDoesNotExist
from django.template.loader import get_template
from django.views.generic import TemplateView
from .utils import get_language_infos
class HomeView(TemplateView):
template_name = 'pages/home.html'
class PageView(TemplateView):
def get(self, request, *args, **kwargs):
self.name = kwargs['name']
return super().get(request, *args, **kwargs)
def get_template_names(self):
template_name = 'pages/{name}.html'.format(name=self.name)
try:
get_template(template_name)
except TemplateDoesNotExist:
raise Http404
return [template_name]
class FeaturesView(TemplateView):
template_name = 'pages/features.html'
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
data['language_infos'] = get_language_infos()
return data
home = HomeView.as_view()
page = PageView.as_view()
features = FeaturesView.as_view()
<file_sep>/blog/utils.py
from base.markdown import PRISM_LANGAUGE_DEPENDENCIES
def resolve_prism_languages(language_set):
"""Resolve language aliases, add required dependencies, and order them.
Returns a list of languages used. The more dependant langauge will be
listed LAST.
"""
languages = []
def put_lang(lang):
try:
languages.remove(lang)
except ValueError: # Not found.
pass
languages.append(lang)
for lang in language_set:
put_lang(lang)
while lang in PRISM_LANGAUGE_DEPENDENCIES:
lang = PRISM_LANGAUGE_DEPENDENCIES[lang]
put_lang(lang)
return languages
<file_sep>/pages/utils.py
import base64
import json
import os
import re
from django.apps import apps
from django.utils.six.moves import urllib
GITHUB_API_BASE_URL = 'https://api.github.com/'
STABLE_TAG_PATTERN = re.compile(r'^v[\d\.]+$')
def get_endpoint(path, params=None):
url = urllib.parse.urljoin(GITHUB_API_BASE_URL, path)
if params is not None:
url = url + '?' + '&'.join('{k}={v}'.format(
k=key, v=params[key],
) for key in params)
response = urllib.request.urlopen(url)
return json.loads(response.read().decode('utf8'))
def get_latest_tag():
tag_data_list = get_endpoint('/repos/MacDownApp/macdown/tags')
tag = None
for tag_data in tag_data_list:
tag_name = tag_data['name']
if STABLE_TAG_PATTERN.match(tag_name):
tag = tag_name
break
assert tag is not None
return tag
def download_endpoint(endpoint, ref, encoding='utf-8'):
data = get_endpoint(endpoint, params={'ref': ref})
content_str = base64.b64decode(data['content']).decode(encoding)
return content_str
def get_prism_languages():
"""Use the GitHub API to get a list of currently contained Prism languages.
"""
# Get Git URL of Prism submodule at the tag.
data = get_endpoint(
'/repos/MacDownApp/macdown/contents/Dependency/prism',
params={'ref': get_latest_tag()},
)
components_str = download_endpoint(
endpoint='/repos/PrismJS/prism/contents/components.js',
ref=data['sha'],
)
# Make this string JSON-compatible.
components_str = components_str[
components_str.find('{'):components_str.rfind('}') + 1
]
components_str_lines = [
line for line in components_str.splitlines(True)
if not line.strip().startswith('//')
]
components = json.loads(''.join(components_str_lines))
languages = components['languages']
return languages
def get_language_aliases():
"""Get a list of MacDown-maintained language aliases.
"""
info_str = download_endpoint(
endpoint=(
'/repos/MacDownApp/macdown/contents/MacDown/Resources/'
'syntax_highlighting.json'
),
ref=get_latest_tag(),
)
info = json.loads(info_str)
return info['aliases']
def get_language_notes():
"""Get custom notes for languages.
The values are raw HTML content. A key can be either a Prism language ID, or
a MacDown language alias.
"""
app_config = apps.get_app_config('pages')
path = os.path.join(
app_config.path, 'static', 'pages', 'data', 'language_notes.json',
)
with open(path) as f:
return json.load(f)
LANGUAGE_INFO_CACHE = None
def get_language_infos():
if LANGUAGE_INFO_CACHE is None:
languages = get_prism_languages()
del languages['meta']
infos = {lang: '' for lang in languages if not lang.endswith('-extras')}
aliases = get_language_aliases()
infos.update({
k: 'Alias to <code>{lang}</code>.'.format(lang=aliases[k])
for k in aliases
})
notes = get_language_notes()
for lang in notes:
infos[lang] = notes[lang]
infos = [(key, infos[key]) for key in sorted(infos.keys())]
global LANGUAGE_INFO_CACHE
LANGUAGE_INFO_CACHE = infos
return LANGUAGE_INFO_CACHE
<file_sep>/sparkle/models/compat.py
try:
from django.db.models import GenericIPAddressField
except ImportError:
# Django 1.6 or earlier. Remove this when dropping support to Django 1.7.
from django.db.models import IPAddressField as GenericIPAddressField # noqa
<file_sep>/base/middleware.py
import re
from django.http import HttpResponsePermanentRedirect
from django.conf import settings
class SecureRequiredMiddleware(object):
"""Forces HTTPS access for paths specified.
"""
def __init__(self):
try:
pattern = settings.SECURE_REQUIRED_PATH_PATTERN
except AttributeError:
self.path_regex = None
else:
self.path_regex = re.compile(pattern)
def process_request(self, request):
if self.path_regex is None:
return
full_path = request.get_full_path()
if not request.is_secure() and self.path_regex.match(full_path):
request_url = request.build_absolute_uri()
secure_url = request_url.replace('http://', 'https://')
return HttpResponsePermanentRedirect(secure_url)
return None
<file_sep>/pages/tests.py
import lxml.html
from lxml.cssselect import CSSSelector
from nose.tools import assert_equal, assert_not_equal
from django.test import TestCase
from sparkle.models import Version
from base.models import macdown
class PageTests(TestCase):
"""Tests for page loading.
"""
fixtures = ('macdown', 'macdown_data')
def _check_download_buttons(self, tree):
"""Check that download links in the tree are correct.
There should be at least one download link, and all links should point
to the version specified.
"""
matches = CSSSelector('.download.button')(tree)
assert_not_equal(len(matches), 0)
for match in matches:
assert_equal(match.get('href'), '/download/latest/')
def test_home(self):
# Should load.
response = self.client.get('/')
assert_equal(response.status_code, 200)
tree = lxml.html.fromstring(response.content)
# Should contain download link in top navbar.
for match in CSSSelector('.top-bar a')(tree):
if match.get('href') == '/download/latest/':
break
else: # This happens if no matches are found
self.fail('Download link not found in top navbar.')
def test_features(self):
response = self.client.get('/features/')
assert_equal(response.status_code, 200)
tree = lxml.html.fromstring(response.content)
self._check_download_buttons(tree)
def test_faq(self):
response = self.client.get('/faq/')
assert_equal(response.status_code, 200)
tree = lxml.html.fromstring(response.content)
self._check_download_buttons(tree)
class NoDownloadLinkTests(TestCase):
"""Test the download link if versions does not exist.
"""
fixtures = ('macdown', 'macdown_data')
def _test_home(self):
# Should load.
response = self.client.get('/')
assert_equal(response.status_code, 200)
tree = lxml.html.fromstring(response.content)
# Should not contain download link in navbar.
assert_equal(len(CSSSelector('.top-bar li.active a')(tree)), 0)
# Should not contain download link.
assert_equal(len(CSSSelector('.download.button')(tree)), 0)
def test_no_default(self):
# Remove versions from default channel.
macdown.active_versions().delete()
self._test_home()
def test_nothing_at_all(self):
# Remove all versions.
Version.objects.all().delete()
self._test_home()
<file_sep>/sparkle/forms/widgets.py
#!/usr/bin/env python
# -*- coding: utf-8
from __future__ import unicode_literals
from django.template.loader import get_template
from ghostdown.forms.widgets import GhostdownInput
class PopupGhostdownInput(GhostdownInput):
def get_template(self):
return get_template('sparkle/includes/ghostdown_editor.html')
<file_sep>/README.rst
#LOG = This is an amazing project
===================
macdown-site
===================
This is the source code of the official site for MacDown_. Please click here_
if you’re looking for the real MacDown repository.
.. _Macdown: http://macdown.uranusjr.com
.. _here: https://github.com/MacDownApp/macdown
<file_sep>/base/utils.py
from sparkle.models import Version
class MacDown(object):
objects = Version.objects.filter(application__slug='macdown')
<file_sep>/sparkle/models/query.py
from django.utils.timezone import now
from django.db.models.query import QuerySet
class VersionQuerySet(QuerySet):
def active(self, channel=None):
qs = self.filter(publish_at__lte=now())
if channel is None:
return qs
return qs.filter(channels__in=[channel])
<file_sep>/sparkle/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import ghostdown.models.fields
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Application',
fields=[
('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),
('name', models.CharField(verbose_name='name', max_length=50)),
('slug', models.SlugField(verbose_name='slug', unique=True)),
],
options={
'verbose_name_plural': 'applications',
'verbose_name': 'application',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='SystemProfileReport',
fields=[
('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),
('ip_address', models.IPAddressField(verbose_name='IP address')),
('created_at', models.DateTimeField(verbose_name='created at', auto_now_add=True)),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='SystemProfileReportRecord',
fields=[
('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),
('key', models.CharField(verbose_name='key', max_length=100)),
('value', models.CharField(verbose_name='value', max_length=80)),
('report', models.ForeignKey(to='sparkle.SystemProfileReport', verbose_name='report')),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Version',
fields=[
('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),
('title', models.CharField(verbose_name='title', max_length=100)),
('version', models.CharField(verbose_name='version', help_text='If you use short_version, this can be the internal version number or build number that will not be shown. In any case, this string is compared to CFBundleVersion of your bundle.', max_length=10)),
('short_version', models.CharField(verbose_name='short version', max_length=50, help_text='A user-displayable version string.', blank=True)),
('dsa_signature', models.CharField(verbose_name='DSA signature', max_length=80)),
('length', models.CharField(verbose_name='length', max_length=20)),
('release_notes', ghostdown.models.fields.GhostdownField(verbose_name='release notes', blank=True)),
('minimum_system_version', models.CharField(verbose_name='minimum system version', max_length=10)),
('update_url', models.URLField(verbose_name='update URL')),
('created_at', models.DateTimeField(verbose_name='created at', auto_now_add=True)),
('publish_at', models.DateTimeField(default=django.utils.timezone.now, verbose_name='published at', help_text='When this upate will be (automatically) published.')),
('application', models.ForeignKey(to='sparkle.Application', verbose_name='application')),
],
options={
'verbose_name_plural': 'versions',
'verbose_name': 'version',
'get_latest_by': 'publish_at',
'ordering': ('-publish_at',),
},
bases=(models.Model,),
),
]
<file_sep>/sparkle/conf.py
from django.conf import settings
SYSTEM_PROFILES_VISIBLE = getattr(
settings, 'SPARKLE_SYSTEM_PROFILES_VISIBLE', False
)
<file_sep>/requirements.txt
cython
django>=1.7,<1.8
dj-database-url
dj-static>=0.0.6
django-absolute
django-appconf
django-ghostdown
django-grappelli
mistune
psycopg2
pystache
PyYAML
six
waitress
<file_sep>/blog/urls.py
from django.conf.urls import patterns, url
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
from . import feeds, views
urlpatterns = patterns(
'',
url(r'^$', views.post_list, name='list'),
url(r'^post/(?P<id>\d+)/$', views.post_detail),
url(r'^post/(?P<id>\d+)/(?P<slug>.+?)/$', views.post_detail, name='post'),
url(r'^feed/atom\.xml$', feeds.atom1, name='atom1'),
# Deprecated.
url(r'^feed/rss201rev2/$', feeds.rss201rev2, name='rss201rev2'),
url(r'^feed/atom1/$', RedirectView.as_view(
url=reverse_lazy('blog:atom1'), permanent=True,
)),
)
<file_sep>/__/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^sparkle/', include('sparkle.urls')),
url(r'^download/', include('downloads.urls', namespace='downloads')),
url(r'^blog/', include('blog.urls', namespace='blog')),
url(r'^history/', include('history.urls', namespace='history')),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('pages.urls', namespace='pages')),
)
<file_sep>/downloads/models.py
from django.core.urlresolvers import reverse
from sparkle.models import Version
def version_get_absolute_url(obj):
if obj.short_version:
return reverse('downloads:short_version', kwargs={
'short_version': obj.short_version
})
else:
return reverse('downloads:version', kwargs={'version': obj.version})
Version.get_absolute_url = version_get_absolute_url
<file_sep>/base/models.py
from django.utils.functional import SimpleLazyObject
from sparkle.models import Application
def get_macdown():
return Application.objects.get_or_create(slug='macdown')[0]
macdown = SimpleLazyObject(get_macdown)
<file_sep>/sparkle/models/managers.py
from django.db import models
from .query import VersionQuerySet
class VersionManager(models.Manager):
use_for_related_fields = True
def get_queryset(self):
return VersionQuerySet(self.model, using=self._db)
def active(self, channel=None):
return self.get_queryset().active(channel=channel)
<file_sep>/base/markdown.py
import mistune
PRISM_LANGUAGE_ALIASES = {
'c++': 'cpp',
'coffee': 'coffeescript',
'coffee-script': 'coffeescript',
'cs': 'csharp',
'html': 'markup',
'js': 'javascript',
'json': 'javascript',
'objective-c': 'objectivec',
'obj-c': 'objectivec',
'objc': 'objectivec',
'py': 'python',
'rb': 'ruby',
'sh': 'bash',
'xml': 'markup',
}
PRISM_LANGAUGE_DEPENDENCIES = {
'aspnet': 'markup',
'bash': 'clike',
'c': 'clike',
'coffeescript': 'javascript',
'cpp': 'c',
'csharp': 'clike',
'go': 'clike',
'groovy': 'clike',
'java': 'clike',
'javascript': 'clike',
'objectivec': 'c',
'php': 'clike',
'ruby': 'clike',
'scala': 'java',
'scss': 'css',
'swift': 'clike',
}
class Renderer(mistune.Renderer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.languages = set()
def block_code(self, code, lang=None):
if lang in PRISM_LANGUAGE_ALIASES:
lang = PRISM_LANGUAGE_ALIASES[lang]
if lang is not None:
self.languages.add(lang)
return super().block_code(code, lang)
def render(markdown):
"""Render given Markdown input.
Returns a 2-tuple (renderer, HTML).
"""
renderer = Renderer()
rendered = mistune.markdown(markdown, renderer=renderer)
return (renderer, rendered,)
def render_to_html(markdown):
"""Render given Markdown input to HTML.
Returns rendered HTML as string.
"""
return render(markdown)[1]
| d4269ea83947536d899cfb83f4946dc701f80903 | [
"Python",
"Text",
"reStructuredText"
] | 40 | Python | SP2224/macdown-site-django | b11c4b55156eb5e964403a6e40788e1bf590b611 | f087b396af249ad9360659d5bf052c0f1fae3899 | |
refs/heads/master | <file_sep><?php
/**
* @copyright Copyright 2014 <NAME>
* @package Fastreverse
* @version 0.1
*/
namespace Fastreverse;
/* Global options */
$config['global']['name'] = "Fastreverse"; // Projectname
$config['global']['lrf'] = "../"; // Local root folder
$config['global']['models'] = "\Model"; // Model folder (with backslash)
$config['global']['schema_filename'] = "schema.xml"; // Schema filename
/* Search and replace options */
$config['sar']['search'] = 'defaultPhpNamingMethod="underscore"';
/* MySQL options */
$config['mysql']['host'] = "127.0.0.1"; // Database host
$config['mysql']['dbname'] = "fastreverse"; // Database name
$config['mysql']['dbuser'] = "root"; // Database user
$config['mysql']['dbpwd'] = "<PASSWORD>"; // Database password
if ( $_SERVER['REQUEST_METHOD'] == "POST") {
$exec_time = microtime(true);
// Reverse the database
$reverse_db = shell_exec("cd " . $config['global']['lrf'] . "; rm " . $config['global']['schema_filename'] . "; vendor/propel/propel/bin/propel reverse 'mysql:host=" . $config['mysql']['host'] . ";dbname=" . $config['mysql']['dbname'] . ";user=" . $config['mysql']['dbuser'] . ";password=" . $config['mysql']['dbpwd'] . "' --database-name='" . $config['mysql']['dbname'] . "' --output-dir='./'");
if ( $reverse_db == true ) {
echo "1. Reverse the database - SUCCESS<br />";
} else {
echo "1. Reverse the database - FAIL<br />";
}
// Open schema and add namespace
$open_schema = file_get_contents($config['global']['lrf'] . $config['global']['schema_filename']);
$open_schema = str_replace($config['sar']['search'], $config['sar']['search'] . ' namespace="' . $config['global']['name'] . $config['global']['models'] .'"', $open_schema);
$write_schema = file_put_contents($config['global']['lrf'] . $config['global']['schema_filename'], $open_schema);
if ( $write_schema == true ) {
echo "2. Schema rebuild - SUCCESS<br />";
} else {
echo "2. Schema rebuild - FAIL<br />";
}
// Build the models
$build_models = shell_exec("cd " . $config['global']['lrf'] . "; rm -r src/" . $config['global']['name'] . "/Model/*; vendor/propel/propel/bin/propel build --output-dir='src';");
if ( $build_models == true ) {
echo "3. Models rebuild - SUCCES<br />";
} else {
echo "3. Models rebuild - FAIL<br />";
}
echo "<p><strong>4. Done - time: " . number_format(microtime(true) - $exec_time, 2) . "</strong></p>";
} else {
echo '<p>Reverse database schema and build new models</p>';
echo '<form method="post">';
echo '<button type="submit">Lets do it.</button>';
echo '</form>';
}
?> | 40910113dc183a8a5d935ed022306f766e8e16eb | [
"PHP"
] | 1 | PHP | marxmeinen/fastreverse | 9bc2c797249a60aefe9f590c95d11048f869fe2b | bc47cd5f5751f0814e9d2f6848db3a5540562cc6 | |
refs/heads/master | <file_sep>//from LanguageCard
// Globals
import React, { Component } from 'react';
// Styles
import localStyles from './styles/CardName.scss';
const styles = Object.assign({}, localStyles);
export default class CardName extends Component {
render() {
return (
<div className={`${styles.CardName} ${this.props.isSelected ? styles.selected : null}`}>
{this.props.cardName}
</div>
);
}
}
CardName.propTypes = {
cardName: React.PropTypes.string.isRequired,
isSelected: React.PropTypes.bool.isRequired
};<file_sep>// from CommandLine
// Globals
import React, { Component } from 'react';
// Styles
import styles from './styles/CommandText.scss';
export default class CommandText extends Component {
render() {
const input = this.props.text ? "yo trails:trailpack " + this.props.text : ""
return (
<div className={`${styles.CommandText}`}>
{input}
</div>
);
}
}
<file_sep>/**
* Routes Configuration
* (trails.config.routes)
*
* Configure how routes map to views and controllers.
*
* @see http://trailsjs.io/doc/config/routes.js
*/
module.exports = [
/**
* Render the HelloWorld view
*/
{
method: 'GET',
path: '/',
handler: 'ViewController.render'
}
]
<file_sep>// from Header
// Globals
import React, { Component } from 'react';
// Components
import BashDollar from '../atoms/BashDollar';
import HelpIcon from '../atoms/HelpIcon';
import CommandText from '../atoms/CommandText';
// Styles
import styles from './styles/CommandLine.scss';
export default class CommandLine extends Component {
render() {
return (
<div className={`${styles.flexContainer} ${styles.CommandLine}`}>
<div className={`${styles.flexContainer}`}>
<BashDollar />
<CommandText text={this.props.text} />
</div>
<div className={`${styles.flexContainer}`}>
<HelpIcon />
</div>
</div>
);
}
}
<file_sep>import { combineReducers } from 'redux'
import * as rowReducers from './reducers';
const rootReducer = combineReducers(
rowReducers
);
export default rootReducer;<file_sep>//from CardRow
// Globals
import React, { Component } from 'react';
// Components
import CardName from '../atoms/CardName'
// Styles
import localStyles from './styles/LanguageCard.scss';
const styles = Object.assign({}, localStyles);
export default class LanguageCard extends Component {
render() {
return (
<div className={`${styles.LanguageCard} ${this.props.isSelected ? styles.selected : null}`} onClick={this.props.selectCard}>
<div>
<img className={`${styles.image}`} src={require(`src/assets/images/logos/${this.props.pictureName}.svg`)}></img>
</div>
<CardName isSelected={this.props.isSelected} cardName={this.props.pictureName}/>
</div>
);
}
}
LanguageCard.propTypes = {
pictureName: React.PropTypes.string.isRequired,
selectCard: React.PropTypes.func.isRequired,
isSelected: React.PropTypes.bool.isRequired
};<file_sep>// from TrailsMix
// Globals
import React, { Component } from 'react';
import { connect } from 'react-redux';
// Components
import CommandLine from '../molecules/CommandLine';
import Title from '../molecules/Title';
// Styles
import localStyles from './styles/Header.scss';
const styles = Object.assign({}, localStyles);
// Utils
import { parseSelections } from '../../utils/parsingService';
function mapPropsToState(state) {
return {
selectedTaskRunner: state.selectedTaskRunner,
selectedFrontEnd: state.selectedFrontEnd,
selectedRouter: state.selectedRouter,
selectedAuth: state.selectedAuth,
};
}
class Header extends Component {
render() {
const {
dispatch,
selectedTaskRunner,
selectedFrontEnd,
selectedRouter,
selectedAuth
} = this.props;
const allSelections = {
taskRunner: selectedTaskRunner,
frontEnd: selectedFrontEnd,
router: selectedRouter,
auth: selectedAuth
};
const commandLine = parseSelections(allSelections);
console.log('commandLine', commandLine);
return (
<div className={`${styles.flexContainer}`}>
<Title />
<CommandLine text={commandLine} />
</div>
);
}
}
export default connect(mapPropsToState)(Header);
<file_sep>const _ = require('lodash')
const Service = require('trails-service')
/**
* Parse object with selection info and return install command
*/
export function parseSelections (settings) {
const server = parseRouters(settings.router);
const frontends = parseFrontEnds(settings.frontEnd);
const taskrunners = parseTaskRunners(settings.taskRunner);
const auths = parseAuths(settings.auth);
return [server, frontends, taskrunners, auths].filter((e) => e).join(' ');
}
export function parseRouters (settings) {
const servers = _.invertBy(settings)['selected'];
const trailpacks = ((server) => {
switch (server) {
case 'Hapi':
return 'trailpack-hapi';
case 'Express':
return 'trailpack-express4';
case 'Koa':
return 'trailpack-koa';
}
})
const serverTrailPacks = _.map(servers, trailpacks)
return serverTrailPacks ? serverTrailPacks.join(' ') : '';
}
export function parseTaskRunners (settings) {
const taskRunners = _.invertBy(settings)['selected'];
return taskRunners ? taskRunners.join(' ') : '';
}
export function parseFrontEnds (settings) {
const frontEnds = _.invertBy(settings)['selected'];
return frontEnds ? frontEnds.join(' ') : '';
}
export function parseAuths (settings) {
const auths = _.invertBy(settings)['selected'];
return auths ? auths.join(' ') : '';
}
<file_sep>const data = {
frontend: {
tools: ['Browserify', 'Webpack'],
description: {
main: '..you like bundlers?..',
supp: ''
}
},
taskrunner: {
tools: ['Grunt', 'Bower', 'Gulp'],
description: {
main: '..now, for task runners..',
supp: ''
}
},
router: {
tools: ['Hapi', 'Express', 'Koa'],
description: {
main: 'Start with your favorite server!',
supp: ''
}
},
auth: {
tools: ['Auth0', 'JWT', 'Passport'],
description: {
main: '..a little bit of auth never hurt anyone..',
supp: ''
}
}
};
export default data;<file_sep>// from CommandLine
// Globals
import React, { Component } from 'react';
// Styles
import styles from './styles/HelpIcon.scss';
export default class HelpIcon extends Component {
render() {
return (
<div>
<i className={`fa fa-question-circle fa-lg ${styles.HelpIcon}`}></i>
</div>
);
}
}<file_sep>import { combineReducers } from 'redux';
import {
SELECT_TASKRUNNER_CARD,
SELECT_FRONTEND_CARD,
SELECT_ROUTER_CARD,
SELECT_AUTH_CARD,
SELECT_NO_CHOICE_CARD
} from '../actions/actions';
export function selectedTaskRunner(state = {}, action) {
switch (action.type) {
case SELECT_TASKRUNNER_CARD:
if (!state[action.id]) {
return Object.assign({}, state, {
[action.id]: 'selected'
});
} else {
return Object.assign({}, state, delete state[action.id]);
}
case SELECT_NO_CHOICE_CARD:
if(action.kind === 'taskrunner'){
return Object.assign({}, state = {});
}
default:
return state;
}
}
export function selectedFrontEnd(state = {}, action) {
switch (action.type) {
case SELECT_FRONTEND_CARD:
if (!state[action.id]) {
return Object.assign({}, state, {
[action.id]: 'selected'
});
} else {
return Object.assign({}, state, delete state[action.id]);
}
case SELECT_NO_CHOICE_CARD:
if(action.kind === 'frontend'){
return Object.assign({}, state = {});
}
default:
return state;
}
}
export function selectedRouter(state = {}, action) {
switch (action.type) {
case SELECT_ROUTER_CARD:
if (!state[action.id]) {
return Object.assign({}, {
[action.id]: 'selected'
});
} else {
return Object.assign({}, delete state[action.id]);
}
case SELECT_NO_CHOICE_CARD:
if(action.kind === 'router'){
return Object.assign({}, state = {});
}
default:
return state;
}
}
export function selectedAuth(state = {}, action) {
switch (action.type) {
case SELECT_AUTH_CARD:
if (!state[action.id]) {
return Object.assign({}, state, {
[action.id]: 'selected'
});
} else {
return Object.assign({}, state, delete state[action.id]);
}
case SELECT_NO_CHOICE_CARD:
if(action.kind === 'auth'){
return Object.assign({}, state = {});
}
default:
return state;
}
}
<file_sep>// from Index
// Globals
import React, { Component } from 'react';
// Components
import Header from '../ecosystems/Header';
import Takeahike from '../ecosystems/Takeahike';
// Styles
import 'src/assets/styles/globals.scss';
import localStyles from './styles/TrailsMix.scss';
export default class TrailsMix extends Component {
render() {
return (
<div className={`${localStyles.flexContainer} ${localStyles.containerStyles}`}>
<Header />
<Takeahike />
</div>
);
}
}
<file_sep>//from CardRow
// Globals
import React, { Component } from 'react';
// Styles
import localStyles from './styles/NoChoiceCard.scss';
const styles = Object.assign({}, localStyles);
export default class NoChoiceCard extends Component {
render() {
return (
<div className={`${styles.NoChoiceCard} ${Object.keys(this.props.selectedCards).length === 0 ? styles.selected : null}`} onClick={this.props.selectNoChoiceCard}>
<i className={`fa fa-times-circle fa-5x`}></i>
</div>
);
}
}
NoChoiceCard.propTypes = {
selectedCards: React.PropTypes.object.isRequired,
selectNoChoiceCard: React.PropTypes.func.isRequired
};<file_sep>//from Takeahike
// Globals
import React, { Component } from 'react';
// Styles
import localStyles from './styles/InfoIcon.scss';
const styles = Object.assign({}, localStyles);
export default class InfoIcon extends Component {
render() {
return (
<div className={`${styles.InfoIcon}`}>
<i className="fa fa-info-circle fa-3x"></i>
</div>
);
}
}<file_sep>//from App
// Globals
import React, { Component } from 'react';
// Components
import CardRow from '../ecosystems/CardRow';
// Styles
import styles from './styles/Takeahike.scss';
export default class Takeahike extends Component {
render() {
return (
<div className={`${styles.Takeahike}`}>
<div className={`${styles.flexLeft}`}></div>
<div className={`${styles.flexMiddle}`}>
<CardRow type="router"/>
<CardRow type="taskrunner" />
<CardRow type="frontend"/>
<CardRow type="auth"/>
</div>
<div className={`${styles.flexRight}`}></div>
</div>
);
}
}<file_sep>
| 20df88ad02f02c06b8e86d304a1b55fdccccf627 | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | trailsjs/trailsmix | b56edca88b6a100c01c13e206f02e781594a1845 | 5fd0dc6c41daa96217fc7679597c24e0eda660ca | |
refs/heads/master | <file_sep>#!/usr/bin/env ruby
require 'ak47'
Ak47::CLI.run(*$*)
<file_sep>module Ak47
class Runner
attr_reader :watch_dirs, :maximum, :interval, :error_time, :command, :interrupt
def initialize(opts = nil, &blk)
@watch_dirs = Array(opts && opts[:watch_dirs] || Dir.pwd)
@maximum = opts && opts[:maximum]
@interval = opts && opts[:interval] || 0.01
@error_time = opts && opts[:error_time] || 5
@command = opts && opts[:command]
@interrupt = opts && opts.key?(:interrupt) ? opts[:interrupt] : true
@blk = blk
end
def start
listeners = watch_dirs.map {|wd| Guard::Listener.select_and_init(:watchdir => wd, :watch_all_modifications => true) }
change_detected = false
running = false
listeners.each do |l|
l.on_change { |f|
if @interrupt
Thread.main.raise Reload, "File system changed"
else
change_detected = true
Thread.main.raise Reload, "File system changed" unless running
end
}
Thread.new { l.start }
end
at_exit { kill_pid }
puts "[Starting ak47 #{VERSION} in #{watch_dirs.join(', ')}]".green
loop do
begin
puts "[Running... #{Time.new.to_s}]".yellow
puts "# #{command}" if command
if maximum
@thread = Thread.new { sleep maximum; Thread.main.raise Reload, "Cancelled due to maximum time" }
end
running = true
change_detected = false
begin
@pid = fork(&@blk)
Process.detach(@pid)
_, status = Process.waitpid2(@pid)
rescue Errno::ECHILD
@pid = nil
ensure
running = false
end
@thread.kill if @thread
if @pid.nil? || status.success?
if change_detected
puts "[Change detected while previously running]".green
change_detected = false
else
puts "[Terminated, waiting for file system change]".green
maximum ? sleep(interval) : sleep
end
else
puts "[Terminated abnormally (#{status.inspect}), retrying in 5s]".red
sleep error_time
end
rescue Reload => e
kill_pid
sleep interval
puts "[Reloading (#{e.message}) #{Time.new.to_s}]".yellow
rescue Interrupt
puts "[Interrupted, exiting]".yellow
exit
end
end
end
def kill_pid
if @pid
begin
unless wait_pid('INT')
unless wait_pid('KILL')
raise "[Unable to kill #{@pid}]"
end
end
rescue Errno::ESRCH
end
end
end
def wait_pid(sig)
count = 0
while count < 5
begin
Process.kill(sig, @pid)
count += 1
sleep 1
rescue Errno::ESRCH
@pid = nil
return true
end
end
false
end
end
end<file_sep>require 'guard'
require 'shell_tools'
require "smart_colored/extend"
require 'optparse'
require "ak47/version"
require "ak47/runner"
require 'ak47/cli'
module Ak47
Reload = Class.new(RuntimeError)
end
def Ak47(opts = nil, &blk)
Ak47::Runner.new(opts, &blk).start
end<file_sep># Ak47
Ak47 is a general purpose reloader. It allows you to reload any command line argument based on either time or
file system change events. File system change events are only supported on Windows, Mac, and Linux.
## Installation
gem install ak47
## Usage
To start an application using ak47, just prepend the entire command with ak47. For example:
ak47 bundle exec thin -R config.ru start
This will run your webserver, but will reload it if there are any changes in your working directory.
There are a few command line options as well:
* -m / --maximum Maximum time to wait before restarting, if unspecified wait forever.
* -i / --interval Interval of time to wait before restarting in the event of a restart. Defaults to 0.01 seconds.
* -e / --error-time Amount of time to wait between restarts if there was an error. Defaults to 5 seconds.
Any remaining arguments passed to the path will be interpretted as directories to watch. To stop parsing command line arguments
and enter your command, use `--` to seperate options from your command. For example:
ak47 -i2 test -- rake test
This will watch your `test` directory and wait two seconds between restarts.
### Programmatic Usage
You can use Ak47 within a Ruby program in the following way.
require 'ak47'
Ak47 {
puts "Reloading!"
}
<file_sep>module Ak47
module CLI
def self.run(*argv)
argv_opts, commands = if argv == ['--help'] or argv == ['-help']
[argv, []]
elsif divider_index = argv.index('--')
[argv[0...divider_index], argv[divider_index.succ...argv.size]]
else
[[], argv]
end
interval, maximum, error_time, interrupt = nil, nil, 5, true
optparse = OptionParser.new do |opts|
opts.banner = "Usage: ak47 [cmd] / ak47 [options] -- [cmd]"
opts.on( '-i', '--interval [FLOAT]', 'Interval before restarting' ) do |i|
interval = Float(i) rescue raise("Interval must be a valid floating point number (e.g. -i0.5)")
raise("Interval must be a positive number") unless interval >= 0
end
opts.on( '-m', '--maximum [FLOAT]', 'Maximum time to wait before restarting' ) do |m|
maximum = Float(m) rescue raise("Maximum must be a valid floating point number (e.g. -m60)")
raise("Maximum must be a positive number") unless maximum >= 0
end
opts.on( '-e', '--error-time [FLOAT]', 'Maximum time to wait before restarting if there was an abnormal status code' ) do |e|
error_time = Float(e) rescue raise("Error time must be a valid floating point number (e.g. -e10)")
raise("Maximum must be a positive number") unless error_time >= 0
end
opts.on( '-d', '--dont-interrupt', 'Don\'t interrupt a running process, wait for it to finish before reloading' ) do
interrupt = false
end
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
optparse.parse!(argv_opts)
watch_dirs = argv_opts
watch_dirs << Dir.pwd if watch_dirs.empty?
watch_dirs.map! { |wd| File.expand_path(wd, Dir.pwd) }
command = ShellTools.escape(commands).strip
if command.empty?
puts optparse
puts
raise "No command supplied"
end
Runner.new(:watch_dirs => watch_dirs, :maximum => maximum, :interval => interval, :error_time => error_time, :command => command, :interrupt => interrupt) {
exec(command)
}.start
rescue
puts $!.backtrace.join("\n ") if ENV['DEBUG']
puts $!.message.red
exit 1
end
end
end | 0a64315bef40b9efef635c01235704f63ee97576 | [
"Markdown",
"Ruby"
] | 5 | Ruby | joshbuddy/ak47 | b9ee0b9cc064fa1939c9039cd65ef5a3a4c74c33 | 97167f52d1b31572aa1ffb97ba3f57686d199730 | |
refs/heads/master | <repo_name>Caiosilva8/Projeto2<file_sep>/src/app/index/index.page.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-index',
templateUrl: './index.page.html',
styleUrls: ['./index.page.scss'],
})
export class IndexPage implements OnInit {
constructor() { }
ngOnInit() {
}
slideOpts = {
initialSlide:0,
speed: 20,
autoplay:true,
loop: true,
slidesPerView: 1,
};
}<file_sep>/src/app/service/storage.service.ts
import { Injectable } from "@angular/core";
import { Pedido } from '../model/pedido';
@Injectable()
export class StorageService {
setCart(obj: Pedido) {
localStorage.setItem('carrinho', JSON.stringify(obj));
}
getCart(): Pedido {
let p = new Pedido();
let str = localStorage.getItem("carrinho");
if(str!=null){
return JSON.parse(str);
}else{
return null;
}
}
} | 4e4bcf8aea5cbb06aafa4e55dd9bf44e4de24990 | [
"TypeScript"
] | 2 | TypeScript | Caiosilva8/Projeto2 | c1d32e1cce3cd0ccfa889423ace0dc2e5a3684ec | 917fdd2524cbd662ef8b42fde86bc97a7ca7cdaf | |
refs/heads/master | <file_sep>var tableDiv = document.getElementById('tableDiv');
function getReservationsByDate(){
var date = document.getElementById('dateField').value;
var data = {dt: date};
$.post('http://localhost:3000/reservations/restaurant/all_reservations/', data, function(response){
var reservationArray = response;
var sortedReservations = [];
//Sort reservations by table
reservationArray.forEach(function(reservation){
sortedReservations[reservation.table_id] = sortedReservations[reservation.table_id] || [];
sortedReservations[reservation.table_id].push(reservation);
});
console.log(sortedReservations);
tableDiv.innerHTML = tableBuilder(sortedReservations);
sortTable();
})
}
function tableBuilder(reservationArray){
var table = "<div class='row'>";
for(var key in reservationArray){
var table = table + "<div class='col-lg-6'><h3>Table " + key +"</h3>\n<table class='table table-hover table-bordered reservationTable'><tr><th>Name</th><th>Number of people</th><th>Start Time</th><th>End Time</th><th>Phone</th></tr>";
var j;
for(j = 0; j < reservationArray[key].length; j++){
var startTime = new Date(reservationArray[key][j].start_dateTime);
startTime = startTime.getHours() - 1 + ":" + (startTime.getMinutes()<10?'0':'') + startTime.getMinutes();
var endTime = new Date(reservationArray[key][j].end_dateTime);
endTime = endTime.getHours() - 1 + ":" + (endTime.getMinutes()<10?'0':'') + endTime.getMinutes();
table += "<tr>";
table = table + "<td>" + reservationArray[key][j].name + "</td>";
table = table + "<td>" + reservationArray[key][j].number_of_people + "</td>";
table = table + "<td>" + startTime + "</td>";
table = table + "<td>" + endTime + "</td>";
table = table + "<td>" + reservationArray[key][j].phone_number + "</td>";
table += "</tr>";
}
table += "</table></div>";
}
table += "</div>";
return table;
}
function sortTable() {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementsByClassName('reservationTable');
var j;
for(j = 0; j < table.length; j++){
switching = true;
/* Make a loop that will continue until
no switching has been done: */
while (switching) {
// Start by saying: no switching is done:
switching = false;
rows = table[j].rows;
/* Loop through all table rows (except the
first, which contains table headers): */
for (i = 1; i < (rows.length - 1); i++) {
// Start by saying there should be no switching:
shouldSwitch = false;
/* Get the two elements you want to compare,
one from current row and one from the next: */
x = rows[i].getElementsByTagName("TD")[2];
y = rows[i + 1].getElementsByTagName("TD")[2];
// Check if the two rows should switch place:
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
// If so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch
and mark that a switch has been done: */
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}
}<file_sep># Lotus Garden
Distributed Systems Project
<file_sep>var tbls = [];
var tblMinSeats = [1,1,2,1,1,3,4,4,3];
var tblMaxSeats = [2,2,4,2,2,6,8,8,6];
var numTables = 9;
var seats = 1;
$(document).ready(function(){
createDropDownMenu();
$("#reserveButton").on("click", reserveButtonHandler);
disableAllTables();
});
// Adds the items to the Dropdown menu
function createDropDownMenu() {
var dropdown = $("#numberSeatsItems");
for (var i = 1; i < 9; i++) {
dropdown.append('<a class="dropdown-item" onclick="changeNumberSeats(' + i + ')">' + i + '</a>');
}
}
// The function that is called when the user selects a value from the dropdown
function changeNumberSeats (numseats) {
$("#numberSeats").html(numseats);
seats = numseats;
selected = null;
if (timePicked) {
getReservedFromDb();
}
}
function mouseOverHandler(e) {
var id = e.currentTarget.id;
if ( (tbls[id.replace("rtb","")-1].minutes_available) < 120) colorYellow(id);
else colorGreen(id);
}
function mouseOffHandler(e) {
var id = e.currentTarget.id;
if (id != selected) removeGreen(id);
}
function colorGreen (tableID) {
var src = $("#" + tableID).attr("src");
if (src.indexOf("_green") == -1 && src.indexOf("_yellow") == -1 ) {
$("#" + tableID).attr("src", src.replace(".png", "_green.png"));
}
}
function colorYellow (tableID) {
var src = $("#" + tableID).attr("src");
if (src.indexOf("_green") == -1 && src.indexOf("_yellow") == -1 ) {
$("#" + tableID).attr("src", src.replace(".png", "_yellow.png"));
}
}
function removeGreen (tableID) {
var src = $("#" + tableID).attr("src");
src = src.replace("_green", "");
src = src.replace("_yellow", "");
$("#" + tableID).attr("src", src);
}
function createTableList (tblList) {
enableAllTables();
tbls = [];
for (var i = 1; i <= numTables; i++) {
var tbl = {
id: i,
elem: $("#rtb" + i),
minutes_available: 120,
free: true,
minSeats: seats >= tblMinSeats[i-1],
maxSeats: seats <= tblMaxSeats[i-1]
}
tbls.push(tbl);
}
for(table of tblList) {
var id = table.table_id - 1;
if(!tbls[id]) continue;
tbls[id].minutes_available = table.minutes_available;
tbls[id].free = table.minutes_available >= 60;
}
mangageTableViewer();
}
function getReservedFromDb () {
var dateTime = selectedDate + " " + timePicked + "Z";
console.log("Fetch reservations for "+ dateTime);
$.post("/reservations/tables/", {
dt: dateTime
},
function (data) {
console.log(data);
createTableList(data);
});
}
// Gray out all the tables that are not to be reserved
function mangageTableViewer () {
for (table of tbls) {
table.elem.attr("title", "");
if (!table.free || !(table.maxSeats && table.minSeats)) {
table.elem.fadeTo(500, 0.3);
table.elem.unbind('mouseenter mouseleave click');
table.elem.attr("title", "This table is not available");
if (table.free && !table.minSeats) table.elem.attr("title", "Please reserve more seats for this table");
if (table.free && !table.maxSeats) table.elem.attr("title", "This table has not enough seats");
} else {
if (table.minutes_available < 120) {
table.elem.attr("title", "This is only available for " + table.minutes_available + " Minutes!");
}
}
}
}
function enableAllTables () {
$(".reserveTable").unbind("click");
$(".reserveTable").fadeTo(800, 1);
$(".reserveTable").bind("mouseenter", mouseOverHandler);
$(".reserveTable").bind("mouseleave", mouseOffHandler);
$(".reserveTable").bind("click", clickHandler);
selected = null;
$("#reserveButton").removeClass("btn-success");
$("#personalDataInputContainer").slideUp("fast");
for (var i = 1; i < 10; i++) {
removeGreen("rtb" + i);
}
}
function disableAllTables () {
$(".reserveTable").fadeTo(100, 0.2);
$(".reserveTable").bind("click", function() {
alert("Please select a time first!");
});
}
function clickHandler(e) {
for (table of tbls) {
removeGreen("rtb" + table.id);
}
selected = e.currentTarget.id;
colorGreen(selected);
$("#personalDataInputContainer").slideDown("slow", function () {
$("#reserveButton").addClass("btn-success");
$("#nameInput").focus();
});
console.log("Click on: " + selected);
}
function refreshTableView () {
getReservedFromDb();
}
function reserveButtonHandler () {
if (!$("#reserveButton").hasClass('btn-success')) return false;
var reservation = {
name: $("#nameInput").val(),
email: $("#mailInput").val(),
phone_number: $("#phoneInput").val(),
start_dateTime: selectedDate + " " + timePicked + "Z",
end_dateTime: calcEndTime(selected.replace("rtb", "")),
table_id: selected.replace("rtb", ""),
number_of_people: seats
}
$.post("/reservations/add/", reservation, function (data, err) {
console.log(err, data);
if (data) {
alert("Reservation was SUCCESSFULL!");
$("#reserveButton").removeClass("btn-success");
$("#personalDataInputContainer").slideUp("fast");
disableAllTables();
}
});
}
function calcEndTime (tableID) {
var time = timePicked;
var available = tbls[tableID-1].minutes_available;
var endTime = time.split(":");
endTime[0] = parseInt(endTime[0]) + Math.floor(available / 60);
endTime[1] = (parseInt(endTime[1]) + available) % 60
if (endTime[1].toString().length == 1) endTime[1] = "0" + endTime[1];
var endDateTime = selectedDate + " " + endTime[0] + ":" + endTime[1] + "Z";
return (endDateTime);
}<file_sep>var selectedDate;
function setDateToToday () {
//Prevent previous dates in datepicker
var input = document.getElementById("dateField");
var today = new Date();
var day = today.getDate();
// Set month to string to add leading 0
var mon = new String(today.getMonth()+1); //January is 0!
var yr = today.getFullYear();
if(mon.length < 2) { mon = "0" + mon; }
var date = new String( yr + '-' + mon + '-' + day );
selectedDate = date;
input.value = date;
input.disabled = false;
input.setAttribute('min', date);
}
function setDate () {
console.log($("#dateField").val());
selectedDate = $("#dateField").val();
if (timePicked) {
refreshTableView();
}
}
$(document).ready(function(){
//$("#dateField").datepicker();
setDateToToday();
$("#dateField").change(setDate);
});<file_sep>
//Set datetime in form to current time
var now = new Date();
var utcString = now.toISOString().substring(0,19);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var localDatetime = year + "-" +
(month < 10 ? "0" + month.toString() : month) + "-" +
(day < 10 ? "0" + day.toString() : day) + "T" +
(hour < 10 ? "0" + hour.toString() : hour) + ":" +
(minute < 10 ? "0" + minute.toString() : minute) +
utcString.substring(16,19);
var datetimeField = document.getElementById("dateField");
datetimeField.value = localDatetime; | 14003463a463151f08480bc5bf49eb480ad218c1 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | philippschiweck/lotusgarden | e74e783e6d4fdbbbd65291fc8f07cf1df8cc94a1 | d2de0ccb147ae406eaadd3bfff2aa75bc5707d40 | |
refs/heads/master | <repo_name>dinhvanhieu18/gsmap_adjustment<file_sep>/lib/conv2d_gsmap/data_preprocessing_conv2d_gsmap.py
import numpy as np
from pandas import read_csv
from netCDF4 import Dataset
import os
import glob
"""GET NAME, LON, LAT, HEIGHT OF GAUGE DATA"""
def get_lon_lat_gauge_data():
preprocessed_data_dir = './data/conv2d_gsmap/preprocessed_txt_data/'
start_index = len(preprocessed_data_dir)
type_file = '.csv'
end_index = -len(type_file)
data_paths_preprocessed_data = glob.glob(preprocessed_data_dir + '*' +
type_file)
lon_arr = np.empty(shape=(len(data_paths_preprocessed_data)))
lat_arr = np.empty(shape=(len(data_paths_preprocessed_data)))
for index, file in enumerate(data_paths_preprocessed_data):
file_name = file[start_index:end_index]
file_name_list = file_name.split('_')
lon = float(file_name_list[1])
lat = float(file_name_list[2])
lon_arr[index] = lon
lat_arr[index] = lat
lon_arr = np.round(lon_arr, 3)
lat_arr = np.round(lat_arr, 3)
return lat_arr, lon_arr
def find_lat_lon_remapnn():
# find nearest lon_lat
precip_list = read_csv('./data/conv2d_gsmap/remapnn.csv')
precip_list = precip_list.to_numpy()
original_nc = Dataset('data/conv2d_gsmap/gsmap_2011_2018.nc', 'r')
# check dataset
gsmap_time = np.array(original_nc['time'][:])
gsmap_lon = np.array(original_nc['lon'][:])
gsmap_lat = np.array(original_nc['lat'][:])
gsmap_precip = np.array(original_nc['precip'][:])
gsmap_precip = np.round(gsmap_precip, 6)
index_pos = []
# precip_list - 2 due to the header and 0-based index
for i in range(0, len(precip_list)):
if precip_list[i] > 0:
index_pos = np.where(gsmap_precip[i, :, :] == np.round(
precip_list[i, 0], 6)) # 0 because of precip_list is (xxx,1)
if len(index_pos[0]) == 1 and len(index_pos[1]) == 1:
break
# get lat and long
# 0 is lat
# 1 is lon
return gsmap_lat[index_pos[0][0]], gsmap_lon[index_pos[1][0]]
def set_gauge_data_to_gsmap():
input_lat_arr = []
input_lon_arr = []
lat_arr, lon_arr = get_lon_lat_gauge_data()
for i in range(0, len(lat_arr)):
os.system(
'cdo -outputtab,value -remapnn,lon={}_lat={} data/conv2d_gsmap/gsmap_2011_2018.nc > data/conv2d_gsmap/remapnn.csv'
.format(lon_arr[i], lat_arr[i]))
lat, lon = find_lat_lon_remapnn()
input_lat_arr.append(lat)
input_lon_arr.append(lon)
input_lat_arr.sort()
input_lon_arr.sort()
# get precipitation
input_precip_arr = np.empty(shape=(1766,
len(input_lat_arr), len(input_lon_arr)))
for i in range(0, len(input_lat_arr)):
os.system(
'cdo -outputtab,value -remapnn,lon={}_lat={} data/conv2d_gsmap/gsmap_2011_2018.nc > data/conv2d_gsmap/precip.csv'
.format(input_lon_arr[i], input_lat_arr[i]))
precipitation = read_csv('data/conv2d_gsmap/precip.csv')
precipitation = precipitation.to_numpy()
input_precip_arr[:, i, i] = precipitation[:,0]
return input_lat_arr, input_lon_arr, input_precip_arr
def save_to_npz():
input_lat, input_lon, input_precip = set_gauge_data_to_gsmap()
output_nc = Dataset('data/conv2d_gsmap/gsmap_2011_2018.nc', 'r')
time = np.array(output_nc['time'][:])
output_lon = np.array(output_nc['lon'][:])
output_lat = np.array(output_nc['lat'][:])
output_precip = np.array(output_nc['precip'][:])
np.savez('data/npz/conv2d_gsmap.npz',
time=time,
input_lon=input_lon,
input_lat=input_lat,
input_precip=input_precip,
output_lon=output_lon,
output_lat=output_lat,
output_precip=output_precip)
def test():
input_precip = np.load('data/npz/conv2d_gsmap.npz')['input_precip']
print(input_precip[4,70,70])
# test()
save_to_npz()<file_sep>/lib/conv2d_gsmap/read_netcdf.py
from netCDF4 import Dataset
from datetime import datetime
import numpy as np
# input_nc = Dataset('data/conv2d_gsmap/tmp.nc', 'r')
# # check dataset
# for i in input_nc.variables:
# print(i, input_nc.variables[i].shape)
# time = np.array(input_nc['time'][:])
# input_lon = np.array(input_nc['lon'][:])
# input_lat = np.array(input_nc['lat'][:])
# input_precip = np.array(input_nc['precip'][:])
output_nc = Dataset('data/conv2d_gsmap/gsmap_2011_2018.nc', 'r')
output_time = np.array(output_nc['time'][:])
output_lon = np.array(output_nc['lon'][:])
output_lat = np.array(output_nc['lat'][:])
output_precip = np.array(output_nc['precip'][:])
print(output_lat)
print(output_lon)
print(len(output_precip))
# Test nearist grid point
print(output_lat[0], output_lon[1], output_lon[2])
print(output_lat[1], output_lon[1], output_lon[2])
# Neu tu 0.85 den 0.95, lay 0.9 thi no' thien ve 0.95
print(output_precip[2,0,1])
print(output_precip[2,0,2])
print("Goc 3: ",output_precip[0,1,1])
print("Goc 4: ",output_precip[9,1,2])
print(output_lon[60])
print(output_lat[92])
np.savez('data/npz/conv2d_gsmap.npz',
time=time,
input_lon=input_lon,
input_lat=input_lat,
input_precip=input_precip,
output_lon=output_lon,
output_lat=output_lat,
output_precip=output_precip)
# for i in range(0, 5):
# print(datetime.fromtimestamp(time[i]))<file_sep>/requirements.txt
numpy==1.18.4
pandas==1.0.3
pyyaml==5.3.1
scipy==1.4.1
netcdf4==1.5.3
sklearn==0.0
keras==2.3.1
matplotlib==3.2.1
tensorflow==2.1.0<file_sep>/test.py
print(int(round((23.95-14.75)/0.1)))<file_sep>/lib/conv2d_gsmap/gauge_data_preprocessing.py
import numpy as np
from pandas import read_csv
from netCDF4 import Dataset
import os
import glob
def get_lon_lat_gauge_data():
preprocessed_data_dir = './data/conv2d_gsmap/preprocessed_txt_data/'
start_index = len(preprocessed_data_dir)
type_file = '.csv'
end_index = -len(type_file)
data_paths_preprocessed_data = glob.glob(preprocessed_data_dir + '*' +
type_file)
lon_arr = np.empty(shape=(len(data_paths_preprocessed_data)))
lat_arr = np.empty(shape=(len(data_paths_preprocessed_data)))
precipitation = []
for index, file in enumerate(data_paths_preprocessed_data):
file_name = file[start_index:end_index]
file_name_list = file_name.split('_')
lon = float(file_name_list[1])
lat = float(file_name_list[2])
lon_arr[index] = lon
lat_arr[index] = lat
precip = read_csv(file, usecols=['precipitation'])
precip = precip.to_numpy()
precipitation.append(precip[-1766:])
lon_arr = np.round(lon_arr, 3)
lat_arr = np.round(lat_arr, 3)
return lat_arr, lon_arr, precipitation
def find_lat_lon_remapnn():
# find nearest lon_lat
precip_list = read_csv('./data/conv2d_gsmap/remapnn.csv')
precip_list = precip_list.to_numpy()
original_nc = Dataset('data/conv2d_gsmap/gsmap_2011_2018.nc', 'r')
# check dataset
gsmap_time = np.array(original_nc['time'][:])
gsmap_lon = np.array(original_nc['lon'][:])
gsmap_lat = np.array(original_nc['lat'][:])
gsmap_precip = np.array(original_nc['precip'][:])
gsmap_precip = np.round(gsmap_precip, 6)
index_pos = []
# precip_list - 2 due to the header and 0-based index
for i in range(0, len(precip_list)):
if precip_list[i] > 0:
index_pos = np.where(gsmap_precip[i, :, :] == np.round(
precip_list[i, 0], 6)) # 0 because of precip_list is (xxx,1)
if len(index_pos[0]) == 1 and len(index_pos[1]) == 1:
break
# get lat and long
# 0 is lat
# 1 is lon
return gsmap_lat[index_pos[0][0]], gsmap_lon[index_pos[1][0]]
def set_gauge_data_to_gsmap():
gauge_lat_arr = []
gauge_lon_arr = []
gauge_precip_arr = np.empty(shape=(1766, 72))
gsmap_precip_arr = np.empty(shape=(1766, 72))
# get precipitation
lat_arr, lon_arr, precipitation = get_lon_lat_gauge_data()
for i in range(0, len(lat_arr)):
os.system(
'cdo -outputtab,value -remapnn,lon={}_lat={} data/conv2d_gsmap/gsmap_2011_2018.nc > data/conv2d_gsmap/remapnn.csv'
.format(lon_arr[i], lat_arr[i]))
lat, lon = find_lat_lon_remapnn()
gauge_lat_arr.append(lat)
gauge_lon_arr.append(lon)
precip = precipitation[i]
gauge_precip_arr[:, i] = precip[:, 0]
gsmap_precipitation = read_csv('data/conv2d_gsmap/remapnn.csv')
gsmap_precipitation = gsmap_precipitation.to_numpy()
gsmap_precip_arr[:, i] = gsmap_precipitation[:, 0]
cal_error(gauge_precip_arr[-353:,:], gsmap_precip_arr[-353:,:])
return gauge_lat_arr, gauge_lon_arr, gauge_precip_arr
def save_to_npz():
gauge_lat, gauge_lon, gauge_precip = set_gauge_data_to_gsmap()
np.savez('data/conv2d_gsmap/npz/gauge_data.npz',
gauge_lon=gauge_lon,
gauge_lat=gauge_lat,
gauge_precip=gauge_precip)
def cal_error(test_arr, prediction_arr):
from sklearn.metrics import mean_squared_error, mean_absolute_error
with np.errstate(divide='ignore', invalid='ignore'):
# cal mse
error_mae = mean_absolute_error(test_arr, prediction_arr)
# cal rmse
error_mse = mean_squared_error(test_arr, prediction_arr)
error_rmse = np.sqrt(error_mse)
# cal mape
y_true, y_pred = np.array(test_arr), np.array(prediction_arr)
error_mape = np.mean(np.abs((y_true - y_pred) / y_true)) * 100
error_list = [error_mae, error_rmse, error_mape]
print("MAE: %.4f" % (error_mae))
print("RMSE: %.4f" % (error_rmse))
print("MAPE: %.4f" % (error_mape))
return error_list
save_to_npz()<file_sep>/lib/conv2d_gsmap/txt_preprocessing.py
import glob
import pandas as pd
from datetime import datetime
import re
import numpy as np
data_dir = 'data/conv2d_gsmap/raw_data_daily/'
data_paths = glob.glob(data_dir + '*.txt')
def satisfy(year, month, day):
month_31 = [1, 3, 5, 7, 8, 10, 12]
month_30 = [4, 6, 9, 11]
if month in month_31:
return True
elif month in month_30:
if day <= 30:
return True
else:
if day <= 28:
return True
if day <= 29 and year % 4 == 0:
return True
return False
def process(file_pth):
f = open(file_pth, "r")
"""Read name, lon, lat"""
name = f.readline()
name = re.sub(' +', ' ', name).strip()
address = f.readline()
address = re.sub(' +', ' ', address).strip().split()
lon = address[0]
lat = address[1]
height = address[2]
"""Preprocessing time and precipitation"""
time = []
precipitation = []
day_arr = []
month_arr = []
year_arr = []
year = 2011
while year < 2019:
f.readline()
for day in range(1, 32):
data = f.readline()
data = re.sub(' +', ' ', data).strip().split()
for month in range(1, len(data)):
data[month] = float(data[month])
if satisfy(year, month, day):
time.append(datetime(year, month, day).timestamp())
day_arr.append(day)
month_arr.append(month)
year_arr.append(year)
if data[month] < 0:
data[month] = 0.0
precipitation.append(data[month])
year += 1
df = pd.DataFrame()
df['time'] = time
df['day'] = day_arr
df['month'] = month_arr
df['year'] = year_arr
df['precipitation'] = precipitation
df = df.sort_values('time', ascending=True)
df.to_csv(f'./data/conv2d_gsmap/preprocessed_txt_data/{name}_{lon}_{lat}_{height}.csv',
index=False)
for file in data_paths:
process(file)
<file_sep>/model/utils/conv2d.py
import numpy as np
from model import common_util
from sklearn.preprocessing import MinMaxScaler
def create_data(**kwargs):
data_npz = kwargs['data'].get('dataset')
seq_len = kwargs['model'].get('seq_len')
horizon = kwargs['model'].get('horizon')
time = np.load(data_npz)['time']
# horizon is in seq_len. the last
T = len(time) - seq_len
lon = np.load(data_npz)['input_lon']
lat = np.load(data_npz)['input_lat']
precip = np.load(data_npz)['input_precip']
target_lon = np.load(data_npz)['output_lon']
target_lat = np.load(data_npz)['output_lat']
target_precip = np.load(data_npz)['output_precip']
channels = 3 # Two channels are lon, lat and precip
input_conv2d_gsmap = np.zeros(shape=(T, seq_len,
len(lat), len(lon), channels))
target_conv2d_gsmap = np.zeros(shape=(T, horizon,
len(target_lat), len(target_lon),
channels))
"""fill input_data"""
# preprocessing data
lon_res = lon.reshape(1, lon.shape[0])
lat_res = lat.reshape(lat.shape[0], 1)
lon_dup = np.repeat(lon_res, len(lat), axis=0)
lat_dup = np.repeat(lat_res, len(lon), axis=1)
# because lon and lat are the same over the period, therefore we duplicate
lon_dup = np.repeat(lon_dup[np.newaxis, :, :], seq_len, axis=0)
lat_dup = np.repeat(lat_dup[np.newaxis, :, :], seq_len, axis=0)
lon_dup = np.repeat(lon_dup[np.newaxis, :, :], T, axis=0)
lat_dup = np.repeat(lat_dup[np.newaxis, :, :], T, axis=0)
# fill channels
input_conv2d_gsmap[:, :, :, :, 0] = lat_dup
input_conv2d_gsmap[:, :, :, :, 1] = lon_dup
"""fill target_data"""
# preprocessing data
target_lon_res = target_lon.reshape(1, target_lon.shape[0])
target_lat_res = target_lat.reshape(target_lat.shape[0], 1)
target_lon_dup = np.repeat(target_lon_res, len(target_lat), axis=0)
target_lat_dup = np.repeat(target_lat_res, len(target_lon), axis=1)
# because lon and lat are the same over the period, therefore we duplicate
target_lon_dup = np.repeat(target_lon_dup[np.newaxis, :, :],
horizon,
axis=0)
target_lat_dup = np.repeat(target_lat_dup[np.newaxis, :, :],
horizon,
axis=0)
target_lon_dup = np.repeat(target_lon_dup[np.newaxis, :, :],
T,
axis=0)
target_lat_dup = np.repeat(target_lat_dup[np.newaxis, :, :],
T,
axis=0)
# fill channels
target_conv2d_gsmap[:, :, :, :, 0] = target_lat_dup
target_conv2d_gsmap[:, :, :, :, 1] = target_lon_dup
# shape convlstm2d (batch_size, n_frames, height, width, channels)
_x = np.empty(shape=(seq_len, len(lat), len(lon), channels))
_y = np.empty(shape=(horizon, 160, 120, channels))
for i in range(0, T):
_x = precip[i:i + seq_len]
_y = target_precip[i + seq_len - horizon]
input_conv2d_gsmap[i, :, :, :, 2] = _x
target_conv2d_gsmap[i, :, :, :, 2] = _y
# target_conv2d_gsmap_2 = np.zeros(shape=(T, horizon, 72, 72, 3))
# target_conv2d_gsmap_2[:,:,:,:,2] = target_conv2d_gsmap[:, :, 0:72, 0:72, 2].copy()
# target_conv2d_gsmap_2[:, :, :, :, 0:2] = target_conv2d_gsmap[:, :, 0:72, 0:72, 0:2].copy()
return input_conv2d_gsmap2, target_conv2d_gsmap
def create_data_prediction(**kwargs):
data_npz = kwargs['data'].get('dataset')
seq_len = kwargs['model'].get('seq_len')
horizon = kwargs['model'].get('horizon')
time = np.load(data_npz)['time']
# horizon is in seq_len. the last
T = len(time) - seq_len - horizon
lon = np.load(data_npz)['output_lon']
lat = np.load(data_npz)['output_lat']
precip = np.load(data_npz)['output_precip']
input_conv2d_gsmap = np.zeros(shape=(T, seq_len,
len(lat), len(lon), 1))
target_conv2d_gsmap = np.zeros(shape=(T, seq_len,
len(lat), len(lon), 1))
for i in range(T):
input_conv2d_gsmap[i, :, :, :, 0] = precip[i:i+seq_len]
target_conv2d_gsmap[i, :, :, :, 0] = precip[i+horizon:i+seq_len+horizon]
# # channel 2 - gauge data
# gauge_dataset = kwargs['data'].get('gauge_dataset')
# gauge_lon = np.load(gauge_dataset)['gauge_lon']
# gauge_lat = np.load(gauge_dataset)['gauge_lat']
# gauge_precipitation = np.load(gauge_dataset)['gauge_precip']
# for i in range(len(gauge_lat)):
# lat = gauge_lat[i]
# lon = gauge_lon[i]
# temp_lat = int(round((23.95-lat)/0.1))
# temp_lon = int(round((lon-100.05)/0.1))
# gauge_precip = gauge_precipitation[:, i]
# for j in range(T):
# input_conv2d_gsmap[j, :, temp_lat, temp_lon, 1] = gauge_precip[j:j+seq_len]
# # remap the target gsmap by gauge data
# target_conv2d_gsmap[j, :, temp_lat, temp_lon, 0] = gauge_precip[j:j+seq_len]
return input_conv2d_gsmap, target_conv2d_gsmap
def load_dataset(**kwargs):
# get preprocessed input and target
input_conv2d_gsmap, target_conv2d_gsmap = create_data_prediction(**kwargs)
# get test_size, valid_size from config
test_size = kwargs['data'].get('test_size')
valid_size = kwargs['data'].get('valid_size')
# split data to train_set, valid_set, test_size
input_train, input_valid, input_test = common_util.prepare_train_valid_test(
input_conv2d_gsmap, test_size=test_size, valid_size=valid_size)
target_train, target_valid, target_test = common_util.prepare_train_valid_test(
target_conv2d_gsmap, test_size=test_size, valid_size=valid_size)
data = {}
for cat in ["train", "valid", "test"]:
x, y = locals()["input_" + cat], locals()["target_" + cat]
data["input_" + cat] = x
data["target_" + cat] = y
return data
<file_sep>/model/conv2d.py
from keras.models import Sequential
from keras.layers import Flatten, Dense, MaxPooling2D, Conv2D, Conv2DTranspose, UpSampling2D, Cropping2D, Cropping3D, MaxPooling3D, UpSampling3D
from keras.layers.convolutional import Conv3D, Conv3DTranspose
from keras.layers.convolutional_recurrent import ConvLSTM2D
from keras.layers.normalization import BatchNormalization
import numpy as np
from model import common_util
import model.utils.conv2d as utils_conv2d
import os
import yaml
from pandas import read_csv
class Conv2DSupervisor():
def __init__(self, **kwargs):
self.config_model = common_util.get_config_model(**kwargs)
# load_data
self.data = utils_conv2d.load_dataset(**kwargs)
self.input_train = self.data['input_train']
self.input_valid = self.data['input_valid']
self.input_test = self.data['input_test']
self.target_train = self.data['target_train']
self.target_valid = self.data['target_valid']
self.target_test = self.data['target_test']
# other configs
self.log_dir = self.config_model['log_dir']
self.optimizer = self.config_model['optimizer']
self.loss = self.config_model['loss']
self.activation = self.config_model['activation']
self.batch_size = self.config_model['batch_size']
self.epochs = self.config_model['epochs']
self.callbacks = self.config_model['callbacks']
self.seq_len = self.config_model['seq_len']
self.horizon = self.config_model['horizon']
self.model = self.build_model_prediction()
def build_model_prediction(self):
model = Sequential()
# Input
model.add(
ConvLSTM2D(filters=16,
kernel_size=(3, 3),
padding='same',
return_sequences=True,
activation = self.activation,
name = 'input_layer_convlstm2d',
input_shape=(self.seq_len, 160, 120, 1)))
# model.add(BatchNormalization())
# Max Pooling - Go deeper
model.add(MaxPooling3D(pool_size=(2, 2, 1)))
model.add(
ConvLSTM2D(filters=16,
kernel_size=(3, 3),
padding='same',
activation = self.activation,
name='hidden_layer_convlstm2d_1',
return_sequences=True))
# model.add(BatchNormalization())
model.add(MaxPooling3D(pool_size=(2, 2, 1)))
model.add(
ConvLSTM2D(filters=32,
kernel_size=(3, 3),
padding='same',
activation = self.activation,
name='hidden_layer_convlstm2d_2',
return_sequences=True))
# model.add(BatchNormalization())
# Up Sampling
model.add(UpSampling3D(size=(2, 2, 1)))
model.add(
ConvLSTM2D(filters=16,
kernel_size=(3, 3),
padding='same',
activation = self.activation,
name='hidden_layer_convlstm2d_3',
return_sequences=True))
# model.add(BatchNormalization())
model.add(UpSampling3D(size=(2, 2, 1)))
model.add(
ConvLSTM2D(filters=16,
kernel_size=(3, 3),
padding='same',
activation = self.activation,
name='hidden_layer_convlstm2d_4',
return_sequences=True))
# model.add(BatchNormalization())
model.add(
Conv3D(filters=1,
kernel_size=(3, 3, 1),
padding='same',
name='output_layer_conv3d',
activation=self.activation))
print(model.summary())
# plot model
from keras.utils import plot_model
plot_model(model=model,
to_file=self.log_dir + '/conv2d_model.png',
show_shapes=True)
return model
def train(self):
self.model.compile(optimizer=self.optimizer,
loss=self.loss,
metrics=['mse', 'mae'])
training_history = self.model.fit(self.input_train,
self.target_train,
batch_size=self.batch_size,
epochs=self.epochs,
callbacks=self.callbacks,
validation_data=(self.input_valid,
self.target_valid),
shuffle=True,
verbose=2)
if training_history is not None:
common_util._plot_training_history(training_history,
self.config_model)
common_util._save_model_history(training_history,
self.config_model)
config = dict(self.config_model['kwargs'])
# create config file in log again
config_filename = 'config.yaml'
config['train']['log_dir'] = self.log_dir
with open(os.path.join(self.log_dir, config_filename), 'w') as f:
yaml.dump(config, f, default_flow_style=False)
def test_prediction(self):
import sys
print("Load model from: {}".format(self.log_dir))
self.model.load_weights(self.log_dir + 'best_model.hdf5')
self.model.compile(optimizer=self.optimizer, loss=self.loss)
input_test = self.input_test
actual_data = self.target_test
predicted_data = np.zeros(shape=(len(actual_data), self.horizon, 160,
120, 1))
from tqdm import tqdm
iterator = tqdm(range(0,len(actual_data)))
for i in iterator:
input = np.zeros(shape=(1, self.seq_len, 160, 120, 1))
input[0] = input_test[i].copy()
yhats = self.model.predict(input)
predicted_data[i, 0] = yhats[0, -1]
print("Prediction: ", np.count_nonzero(predicted_data[i, 0] > 0), "Actual: ", np.count_nonzero(actual_data[i, -1]>0))
data_npz = self.config_model['data_kwargs'].get('dataset')
lon = np.load(data_npz)['input_lon']
lat = np.load(data_npz)['input_lat']
gauge_dataset = self.config_model['data_kwargs'].get('gauge_dataset')
gauge_lon = np.load(gauge_dataset)['gauge_lon']
gauge_lat = np.load(gauge_dataset)['gauge_lat']
gauge_precipitation = np.load(gauge_dataset)['gauge_precip']
actual_arr = []
preds_arr = []
gauge_arr = []
# MAE for 72x72 matrix including gauge data
for index, lat in np.ndenumerate(lat):
temp_lat = int(round((23.95-lat)/0.1))
for index, lon in np.ndenumerate(lon):
temp_lon = int(round((lon-100.05)/0.1))
# actual data
actual_precip = actual_data[:, 0, temp_lat, temp_lon, 0]
actual_arr.append(actual_precip)
# prediction data
preds = predicted_data[:, 0, temp_lat, temp_lon, 0]
preds_arr.append(preds)
common_util.mae(actual_arr, preds_arr)
preds_arr = []
# MAE for only gauge data
for i in range(len(gauge_lat)):
lat = gauge_lat[i]
lon = gauge_lon[i]
temp_lat = int(round((23.95-lat)/0.1))
temp_lon = int(round((lon-100.05)/0.1))
# gauge data
gauge_precip = gauge_precipitation[-353:, i]
gauge_arr.append(gauge_precip)
# prediction data
preds = predicted_data[:, 0, temp_lat, temp_lon, 0]
preds_arr.append(preds)
common_util.cal_error(gauge_arr, preds_arr)
def plot_result(self):
from matplotlib import pyplot as plt
preds = np.load(self.log_dir + 'pd.npy')
gt = np.load(self.log_dir + 'gt.npy')
plt.plot(preds[:], label='preds')
plt.plot(gt[:], label='gt')
plt.legend()
plt.savefig(self.log_dir + 'result_predict.png')
plt.close()
| 3b628d7bb7bd548730cd36651ebf09a9d96decdb | [
"Python",
"Text"
] | 8 | Python | dinhvanhieu18/gsmap_adjustment | dc616cbeebd2a2acb965d922146648d37da50d20 | 3e7e442ec93644a36298f4834e97716b9f124e77 | |
refs/heads/master | <file_sep>n = int(input("Enter the length of the sequence: ")) # Do not change this line
sum_int = 0
num1 = 1
num2 = 2
num3 = 3
for i in range(1,n+1):
if i <= 3:
print(i)
else:
sum_int = num1 + num2 + num3
num1 = num2
num2 = num3
num3 = sum_int
print(sum_int) | 126674c77152beac389d3bce52b2b1d798620d32 | [
"Python"
] | 1 | Python | solons20/yeeetaroni | e71911bbb9683925c91e1a298539b40bbca71224 | 55f240b63cdd4fabb03ce1bfd4b6f53045786cf0 | |
refs/heads/main | <repo_name>novandri511/stim<file_sep>/js/fullvalidation.js
function validateForm() {
var x = document.forms["form_pembayaran"]["fullname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
// CHECK EMAIL
var z = document.forms["form_pembayaran"]["email"].value;
var mailformat = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[com]{3,}$/;
if (z == null || z == "") {
alert("Name must be filled out");
return false;
} else if (z.match(mailformat)) {
return validatePassword();
} else {
alert("You have entered an invalid email address!");
return false;
}
}
function validatePassword() {
// CHECK PASSWORD
var y = document.forms["form_pembayaran"]["password"].value;
var passw = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/;
if (y == null || y == "") {
alert("Name must be filled out");
return false;
} else if (y.match(passw)) {
return validateCredit();
} else {
alert('Coba Password lain...');
return false;
}
}
function validateCredit() {
// CHECK CREDIT CARD
var cred = document.forms["form_pembayaran"]["cardnumber"].value;
if (cred.length < 16 || cred.length >= 17) {
alert('Please input 16 number');
return false;
} else {
return validateDate();
}
}
function validateDate() {
// CHECK DATE
var d = document.forms["form_pembayaran"]["date"].value;
var dated = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
if (d.match(dated)) {
setTimeout(function() { window.location = "./thankyou.html" });
return true;
} else {
alert('date salah')
return false;
}
} | 875fd50d822448b9f9afb210710a3438fc769c83 | [
"JavaScript"
] | 1 | JavaScript | novandri511/stim | 285fdf60672655a8269ceb5ca6826cf32036baa1 | d61032cc68aae5567c286a833666d0f14d362a61 | |
refs/heads/master | <file_sep>import superagent from 'superagent'
import {logError} from '../lib/utils'
// ACTION CREATORS
export const albumSet = albums => ({
type: 'ALBUM_SET',
payload: albums
})
export const albumCreate = album => ({
type: 'ALBUM_CREATE',
payload: album
})
export const albumUpdate = album => ({
type: 'ALBUM_UPDATE',
payload: album
})
export const albumDelete = album => ({
type: 'ALBUM_DELETE',
payload: album
})
// ASYNC ACTIONS
export const albumFetchRequest = () => dispatch => {
return superagent.get(`${__API_URL__}/api/v1/album`)
.then(res => dispatch(albumSet(res.body)))
.catch(logError)
}
export const albumCreateRequest = album => (dispatch, getState) => {
return superagent.post(`${__API_URL__}/api/v1/album`)
.send(album)
.then(res => dispatch(albumCreate(res.body)))
.catch(logError)
}
export const albumUpdateRequest = album => dispatch => {
return superagent.put(`${__API_URL__}/api/v1/album/${album._id}`)
.send(album)
.then(() => dispatch(albumUpdate(album)))
.catch(logError)
}
export const albumDeleteRequest = album => dispatch => {
return superagent.delete(`${__API_URL__}/api/v1/album/${album._id}`)
.then(() => dispatch(albumDelete(album)))
.catch(logError)
}
<file_sep> 41: OAuth
===
## Learning Objectives
* Students will learn to set up a Google Cloud application
* Students will learn to implement OAuth2 on the server side
## Readings
* Skim [OAuth wiki](https://en.wikipedia.org/wiki/OAuth)
* Read [OAuth2 simplified](https://aaronparecki.com/oauth-2-simplified/)
* Read [Google OAuth2 Docs](https://developers.google.com/identity/protocols/OAuth2)
* Read [Google OAuth Server Side](https://developers.google.com/identity/protocols/OAuth2WebServer)
* Read [Google OpenId Docs](https://developers.google.com/identity/protocols/OpenIDConnect)
## OAUTH2.0
OAuth is an open standard for access delegation. It servers as a way to give users the ability to grant apps access to services, without giving the apps their password.
#### Access Code
* First the client needs to grant the application permission.
* To do this you need to give an anchor tag that will take them to the services authorization page
* The anchor tag should pass the following information through a query string to the authorization server
* `response_type=code` indicates that your server wants to receive an authorization code
* `client_id=<your client id>` tells the authorization server which app the user is granting access to
* `redirect_uri=<your redirect uri>` tells the auth server which server endpoint to redirect to
* `scope=<list of scopes>` tells the auth server what you want the user to give access to
* `state=<anything you want>` a place where you can store info to pass to your server if you want
#### Access Token
* If the users grants access to the app the auth server will redirect to your redirect uri callback with a code
* Once you have a code you can exchange it for and access token by making a post request to the authorization server and providing the following information
* `grant_type=authorization_code`
* `code=<the code your received`
* `redirect_uri=REDIRECT_URI` must be same as the redirect uri your client provided
* `client_id=<your client id>` tells the auth server which app is making the requests
* `client_secret=<your client secret>` authenticates that the app making the request is the app registered with the `client_id`
* once you get an Access Token you can use it to make API calls to the service on be have of that user
<file_sep> 32: Combining Reducers
===
## Daily Plan
- Notes
- Anything top of mind?
- Code Review
- Combining Reducers using Redux
- Adds a second resource to our kanban board
- Testing our React/Redux App with Jest and Enzyme
- Lab preview
## Learning Objectives
* Students will learn to combine reducers to simplify the management of complex application state
## Readings
* Read [combine reducers](http://redux.js.org/docs/api/combineReducers.html)
## combineReducers
Reducers are great tools for defining state and state changes to your applications. However as your application state gets more complex, your reducers become hard to manage. `combineReducers` is a redux method that enables you to create a single reducer from many reducers that define sub states and their interactions. a state returned from a combined reducer is an object where each _sub state reducer_ defines a property on that object.
<file_sep>'use strict'
// function inclusiveRandom(min, max) {
// return Math.random() * (max - min) + 1
// }
module.exports = function randomNum(min, max) {
return Math.random() * (max - min) + 1
}<file_sep>'use strict'
const server = require('../../lib/server')
const superagent = require('superagent')
const mocks = require('../lib/mocks')
const faker = require('faker')
require('jest')
describe('DELETE /api/v1/track', function () {
beforeAll(() => this.base = `:${process.env.PORT}/api/v1/track`)
beforeAll(server.start)
afterAll(server.stop)
describe('Valid requests', () => {
beforeAll(() => {
return mocks.album.createOne()
.then(album => this.mockAlbum = album)
.then(() => {
this.fakeTrack = {
title: faker.hacker.ingverb(),
artist: faker.hacker.noun(),
album: this.mockAlbum._id,
}
return superagent.post(`${this.base}`)
.send(this.fakeTrack)
.then(res => this.response = res)
})
})
it('should return a status 204 on successful deletion', () => {
return superagent.delete(`${this.base}/${this.response.body._id}`)
.then(res => expect(res.status).toEqual(204))
})
})
describe('inValid requests', () => {
it('should return a 404 given an invalid ID', () => {
return superagent.delete(`${this.base}/1234`)
.catch(err => expect(err.status).toEqual(404))
})
})
})
<file_sep> 29: Component Composition
===
## Daily Plan
- Notes:
- Anything top of mind?
- Hash Tables
- Code Review: _Are we really solid on state and props?_
- Composition vs Inheritance: _Just compose..._
- Building Reusable Components through `props.children`
- Lab Preview
- _reminder for scott... no CSS challenge this week. next week._
## Learning Objectives
* Students will learn to about composition vs inheritance
* Students will learn to compose react components using props
## Readings
* Read [Conditional Rendering](https://facebook.github.io/react/docs/conditional-rendering.html)
* Read [Lists and Keys](https://facebook.github.io/react/docs/lists-and-keys.html)
* Read [Composition vs Inheritance](https://facebook.github.io/react/docs/composition-vs-inheritance.html)
* Read [Thinking in React](https://facebook.github.io/react/docs/thinking-in-react.html)
## Component Composition
#### Composition
Some components don't know their children a head of time. React components can use the special `children` prop to pass children directly into their output. For example a `SpeechBubble` component could be passed a `SuccessMessage` or `ErrorMessage` component to be used as a child component.
#### Specialization
Composition can be used to create special cases of another component. For example a `Modal` component could be composed to create a `SignupModal` or a `LoginModal`.
<file_sep>'use strict'
const debug = require('debug')('http:storage')
const storage = module.exports = {}
const memory = {}
// memory = {
// 'Notes': {
// '1234.5678.9012': {
// '_id': '1234.5678.9012',
// 'title': '',
// 'content': '',
// },
// },
// 'Categories': {
// ...
// },
// }
storage.create = function(schema, item) {
debug('Created a new thing')
return new Promise((resolve, reject) => {
if(!schema || !item) return reject(new Error('Cannot create a new item; Schema and Item required'))
if(!memory[schema]) memory[schema] = {}
memory[schema][item._id] = item
return resolve(memory[schema][item._id])
})
}
storage.fetchOne = function() {
}
storage.fetchAll = function() {
}
storage.update = function() {
}
storage.delete = function() {
}
<file_sep>'use strict'
const EE = require('events').EventEmitter
const ee = module.exports = new EE()
ee.on('someEvent', function (data) {
console.log('ran the thing!', data)
})<file_sep>import reducer from '../reducer/category'
require('jest')
describe('category reducer', () => {
it('should return the initial state on first call', () => {
expect(reducer(undefined, {})).toEqual([])
})
it('should handle CATEGORY_CREATE', () => {
let categoryOne = { _id: '1234', title: 'wat', timestamp: new Date() }
let categoryTwo = { _id: '4567', title: 'who', timestamp: new Date() }
let state = reducer([categoryOne], {
type: 'CATEGORY_CREATE',
payload: categoryTwo,
})
expect(state).toContain(categoryOne)
expect(state).toContain(categoryTwo)
})
})
<file_sep> 27: Forms and Props
===
## Daily Plan
- Notes:
- anything top of mind?
- Code Review
- SCSS Syntax Introduction
- Forms and Props!!
- Lifecycle Hooks
- Lab Preview
## Learning Objectives
* Students will learn to test react components using jest and enzyme
* Students will learn to manage controlled inputs
* Students will learn to pass data from parent to child through props
## Readings
* Read [Components and Props](https://facebook.github.io/react/docs/components-and-props.html)
* Read [State and Lifecycle](https://facebook.github.io/react/docs/state-and-lifecycle.html)
* Read [Handling Events](https://facebook.github.io/react/docs/handling-events.html)
* Read [Forms](https://facebook.github.io/react/docs/forms.html)
## Forms and Inputs
React form elements maintain internal state. Think of React inputs as stateful child components. This means that we must manage the state of inputs through our own stateful component and one way data binding. We create a parent component I'll refer to as a _form-container_ that manages the state for all child components of the form, passing any necessary state down into inputs through props. Each input has an `onChange` event that we can handle and use to update our _form-container's_ state each time the user interacts with an input.
## Props
Components accept arbitrary inputs called "props". In jsx props are passed into a component with a syntax that looks like html attributes. `props` is the name of the object passed into a component constructor, any prop added to a component in the jsx will be accessible as a property on `props`. After `props` is passed into the constructor's `super` they are available on the context by using `this.props`. **`props` are READ ONLY**
``` javascript
// props is the argument passed to the constructor
// props can be accessed on `this` after being passed into super
class Foo extends React.Component {
constructor(props){
super(props)
console.log('title', props.title)
console.log('content', props.content)
}
render(){
return (
<div>
<h1> {this.props.title} </h1>
<p> {this.props.content} </p>
</div>
)
}
}
// adding props to a component
<Foo title='some literal value value' content={this.state.article.content}>
```
## One Way Data flow
State can only be passed from parent to child through props. This enforces the idea of one way data flow. One way data flow is the way to describe that state can only be passed down the component tree (not up). If a child wants to pass some data to its parent, the parent can pass a function to the child through props and the child may invoke that function and pass it data for the parent to manage.
<file_sep># Lab 10 - Express
## API endpoints
* POST: "/api/v1/note"
Requires: Title and Content as JSON;
This endpoint takes a JSON string containing a title and content, it then feeds that into the note constructor before finally passing it to the storage module. The storage module then writes the JSON to a file under the correct directory.
* PUT: "/api/v1/note/:_id"
Requires: ID as a parameter; Title Content and ID as JSON;
This endpoint takes the parameter provided and verifies it against the JSON provided it then builds a new note object using the provided data including the ID provided. It then passes the note and ID to the storage module which writes it to the appropriate file.
* GET: "/api/v1/note" or "/api/v1/note/:_id"
Required: No requirements for getting a list of available files; ID as a parameter for one file;
This endpoint first verifies whether an ID was passed as a parameter. If ID is not present it will get a list of the file names from the storage module and pass them back as a response. If ID is present it will pass that ID to the storage module and get a single file with that name.
* DELETE: "/api/v1/note/:_id"
Required: ID as a parameter;
This endpoint using the ID provided locates and deletes the file that shares the same ID.<file_sep>'use strict'
const Note = require('../model/note')
const storage = require('../lib/storage')
const bodyParser = require('body-parser').json()
const errorHandler = require('../lib/error-handler')
module.exports = function(router) {
router.post('/', bodyParser, (req, res) => {
let newNote
new Note(req.body.title, req.body.content)
.then(note => newNote = note)
.then(note => JSON.stringify(note))
.then(json => storage.create('note', newNote._id, json))
.then(() => res.status(201).json(newNote))
.catch(err => errorHandler(err, res))
})
router.get('/:_id', (req, res) => {
storage.fetchOne('note', req.params._id)
.then(buffer => buffer.toString())
.then(json => JSON.parse(json))
.then(note => res.status(200).json(note))
.catch(err => errorHandler(err, res))
})
router.get('/', (req, res) => {
storage.fetchAll('note')
.then(paths => {
console.log('paths', paths)
return paths.map(p => p.split('.')[0])
})
.then(ids => {
console.log('ids', ids)
res.status(200).json(ids)
})
.catch(err => errorHandler(err, res))
})
router.delete('/:_id', (req, res) => {
storage.destroy('note', req.params._id)
// .then(() => res.status(200).send('some message'))
.then(() => res.sendStatus(204))
.catch(err => errorHandler(err, res))
})
router.put('/:_id', bodyParser, (req, res) => {
storage.fetchOne('note', req.params._id)
.then(buffer => buffer.toString())
.then(json => JSON.parse(json))
.then(note => ({
_id: req.params._id,
title: req.body.title || note.title,
content: req.body.content || note.content
}))
.then(note => JSON.stringify(note))
.then(json => storage.update('note', req.params._id, json))
.then(() => res.sendStatus(204))
.catch(err => errorHandler(err, res))
})
}<file_sep>'use strict'
const server = require('../../lib/server')
const superagent = require('superagent')
const mocks = require('../lib/mocks')
const faker = require('faker')
require('jest')
describe('GET /api/v1/track', function () {
beforeAll(() => this.base = `:${process.env.PORT}/api/v1/track`)
beforeAll(server.start)
afterAll(server.stop)
afterEach(mocks.album.removeAll)
afterEach(mocks.track.removeAll)
describe('Valid requests', () => {
beforeAll(() => {
return mocks.track.createMany(25)
.then(results => this.trackData = results)
})
it('should return an array of IDs given no ID parameter in the route', () => {
return superagent.get(`${this.base}`)
.then(res => {
expect(res.body).toBeInstanceOf(Array)
expect(res.body.includes(this.trackData.tracks[0]._id.toString())).toBeTruthy()
expect(res.body.includes(this.trackData.tracks[10]._id.toString())).toBeTruthy()
expect(res.body.includes(this.trackData.tracks[18]._id.toString())).toBeTruthy()
})
it('should return a status 200', () => {
return superagent.get(`${this.base}`)
.then(res => expect(res.status).toEqual(200))
})
it('should return a status 200 given a valid ID', () => {
return superagent.get(`${this.base}/${this.trackData.tracks[0]._id}`)
.then(res => expect(res.status).toEqual(200))
})
it('should return the correct data from a given objects ID', () => {
return superagent.get(`${this.base}/${this.trackData.tracks[0]._id}`)
.then(res => {
expect(res.body._id).toEqual(this.trackData.tracks[0]._id)
expect(res.body.title).toEqual(this.trackData.tracks[0].title)
expect(res.body.artist).toEqual(this.trackData.tracks[0].artist)
})
})
})
})
describe('inValid requests', () => {
})
})
<file_sep>'use strict';
const server = require('../../lib/server.js');
const superagent = require('superagent');
const mock = require('../lib/mock.js');
const faker = require('faker');
require('jest');
describe('POST', function() {
beforeAll(server.start);
afterAll(server.stop);
afterAll(mock.rider.removeAll);
afterAll(mock.bike.removeAll);
describe('Valid req/res', () => {
beforeAll(() => {
this.rider = {name: faker.name.firstName()};
return superagent.post(':4000/api/v1/rider')
.send(this.rider)
.then(res => this.res = res);
});
it('should post a new rider object with a name and bike property', () => {
expect(this.res.body.name).toBe(this.rider.name);
expect(this.res.body).toHaveProperty('bikes');
});
it('should respond with a status of 201', () => {
expect(this.res.status).toBe(201);
});
});
describe('Invalid req/res', () => {
it('should return a status 404 on bad path', () => {
return superagent.post(':4000/api/v1/doesnotexist')
.send(this.rider)
.catch(err => {
expect(err.status).toBe(404);
expect(err.response.text).toMatch(/path error/i);
});
});
it('should return a status 400 on a bad request body', () => {
return superagent.post(':4000/api/v1/bike')
.send({})
.catch(err => expect(err.status).toBe(400));
});
});
});<file_sep>'use strict'
const fs = require('fs')
const Bmp = require('./lib/bitmap')
// console.log(process.argv[2])
fs.readFile('./assets/bitmap.bmp', (err, data) => {
let bmp = new Bmp(data)
console.log(bmp)
// console.log(bmp.pixelArray.length)
// console.log(bmp.colorTable[0], bmp.colorTable[1], bmp.colorTable[2], bmp.colorTable[3])
for(let i = 0; i < bmp.pixelArray.length; i+4) {
let gray = (bmp.pixelArray[i] + bmp.pixelArray[i + 1] + bmp.pixelArray[i + 2]) / 3
bmp.pixelArray[i] = gray
bmp.pixelArray[i+1] = gray
bmp.pixelArray[i+2] = gray
}
fs.writeFile(`${__dirname}/assets/new.bmp`, bmp.allData, (err, data) => {
if(err) throw new Error(err)
console.log('made it')
})
})<file_sep>'use strict';
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'});
const storage = module.exports = {};
storage.create = (schema, item) => {
let json = JSON.stringify(item);
return fs.writeFileProm(`${__dirname}/../data/${schema}/${item._id}.json`, json) // O(1) Normal Operation (Best Case)
.then(() => item);
};
storage.fetchOne = (schema, id) => {
return fs.readFileProm(`${__dirname}/../data/${schema}/${id}.json`); // O(1) Normal Operation (Best Case)
};
storage.fetch = (schema) => {
return fs.readdirProm(`${__dirname}/../data/${schema}`) // O(n) Normal Operation (Best Case)
.then(dir => dir.map(file => file.split('.')[0]));
};
storage.update = (schema, id, item) => {
if (item._id !== id) return Promise.reject(new Error('Validation Error: Cannot update file with unmatched ID'));
let json = JSON.stringify(item);
return fs.writeFileProm(`${__dirname}/../data/${schema}/${id}.json`, json) // O(1) Normal Operation (Best Case)
.then(() => item);
};
storage.destroy = (schema, id) => {
return fs.unlinkProm(`${__dirname}/../data/${schema}/${id}.json`); // O(1) Normal Operation (Best Case)
};
<file_sep>'use strict'
const server = require('../../lib/server')
const superagent = require('superagent')
const mocks = require('../lib/mocks')
const faker = require('faker')
require('jest')
describe('POST /api/v1/track', function() {
beforeAll(() => this.base = `:${process.env.PORT}/api/v1/track`)
beforeAll(server.start)
afterAll(server.stop)
afterEach(mocks.album.removeAll)
afterEach(mocks.track.removeAll)
describe('Valid requests', () => {
beforeAll(() => {
return mocks.album.createOne()
.then(album => this.mockAlbum = album)
.then(() => {
this.fakeTrack = {
title: faker.hacker.ingverb(),
artist: faker.hacker.noun(),
album: this.mockAlbum._id,
}
return superagent.post(`${this.base}`)
.send(this.fakeTrack)
.then(res => this.response = res)
})
})
it('should return a status of 201', () => {
expect(this.response.status).toEqual(201)
})
it('should return a new track instance', () => {
expect(this.response.body).toHaveProperty('_id')
})
})
describe('inValid requests', () => {
it('should return a status 400 given no request body', () => {
return superagent.post(`${this.base}`)
.send()
.catch(err => expect(err.status).toEqual(400))
})
it('should return a status 400 given an improperly formatted body', () => {
return superagent.post(`${this.base}`)
.send({gnarf: 200})
.catch(err => expect(err.status).toEqual(400))
})
})
})
<file_sep> 34: UI Styling
===
----
## Daily Plan
- Notes:
- Anything top of mind?
- Code Review
- Review of SCSS: _What questions are there?_
- Review of SMACSS-ish structure for component-based architecture
- Custom forms: _Build a slider checkbox_
- Lab Preview
## Learning Objectives
* students will be able to use SCSS to create component based and modular CSS styles
* students will be able to *generally* conform to the SMACCS principles for creating base, layout, and theme containers for their application styles
* students will be able to create and use global SCSS variables for reusable styles
* students will have a level of competency is styling custom form elements within an application
## Resources
* [sass getting started guide](http://sass-lang.com/guide)
## Overview
* SCSS is a variation of SASS, which stands for "syntactically awesome stylesheets"
* SCSS gives us the ability to do the following things with our CSS styles
* creation of modular css "partials"
* nesting of CSS rules
* ability to import partials into/from other partial files
* ability to create functional CSS components and mixins
* ability to use math operators in CSS
* SCSS partials are often modularized to fit the following structure:
- **style**
- **lib**
- **base**
- `_base.scss`
- `_reset.scss`
- **theme**
- `_vars.scss`
- **layout**
- `_header.scss`
- `_footer.scss`
- `_content.scss`
- **component**
- **my-component-dir**
- `_my-component-dir.scss`
- **another-component-dir**
- `_another-component-dir.scss`
<file_sep>import './_slider.scss'
import React from 'react'
class SliderCheckbox extends React.Component {
render() {
return (
<div className={this.props.config.className + ' slider-checkbox'}>
<input
type='checkbox'
name={this.props.config.name}
id={this.props.config.id}
defaultChecked={false}
onChange={this.props.onChange}/>
<label htmlFor={this.props.config.id}><div></div></label>
</div>
)
}
}
export default SliderCheckbox
<file_sep>'use strict'
const reader = require('../lib/reader')
require('jest')
describe('Reader Module', function() {
describe('#read', () => {
let paths = [`${__dirname}/data/one.txt`, `${__dirname}/data/two.txt`, `${__dirname}/data/three.txt`]
describe('Valid inputs', () => {
it('should return the file data in the same order passed; one, two, three', (done) => {
let expected = 'Short.Long.Medium.'
reader.read(paths, (err, results) => {
let arr = [results[0].split(' ')[0], results[1].split(' ')[0], results[2].split(' ')[0]].join('')
expect(expected).toEqual()
done()
})
})
it('should accept an array of file paths and return a null argument for err', (done) => {
reader.read(paths, (err, results) => {
// console.log('err', err)
expect(err).toBeNull()
done()
})
})
it('should accept an array of file paths and return an array of results', (done) => {
reader.read(paths, (err, results) => {
expect(results).toBeInstanceOf(Array)
done()
})
})
it('should accept an array of file paths and return something', (done) => {
reader.read(paths, (err, results) => {
expect(results).not.toBeNull()
done()
})
})
it('should return an array with the length of 3', (done) =>{
reader.read(paths, (err, results) => {
expect(results.length).toBe(3)
done()
})
})
})
// describe('Invalid inputs', () => {
// it('should return an error given invalid file paths', () => {
// })
// })
})
// describe('#writer', () => {
// it('should ...', () => {})
// it('should ...', () => {})
// it('should ...', () => {})
// })
})
<file_sep>'use strict';
// Testing Dependencies
const server = require('../../lib/server');
const superagent = require('superagent');
require('jest');
// Test Variables
let port = process.env.PORT;
let api = `:${port}/api/v1/note`;
describe('Route Testing', () => {
this.mockNote = {title: 'test', content: 'run'};
beforeAll(() => server.start(port, () => console.log(`listening on ${port}`)));
afterAll(() => server.stop());
describe('POST /api/v1/note', () => {
beforeAll(() => {
return superagent.post(api)
.send(this.mockNote)
.then(res => this.response = res);
});
describe('Valid Routes/Data', () => {
it('Should respond with a status of 201', () => {
expect(this.response.status).toBe(201);
});
it('Should post a single note and return it', () => {
expect(this.response.body).toHaveProperty('title');
expect(this.response.body).toHaveProperty('content');
expect(this.response.body).toHaveProperty('_id');
});
it('Should respond with a correct title and content', () => {
expect(this.response.body.title).toBe('test');
expect(this.response.body.content).toBe('run');
});
});
describe('Invalid Routes/Data', () => {
it('Should return a 404 for an invalid path', () => {
return superagent.post(':4000/api/v1/node')
.catch(err => {
expect(err.status).toBe(404);
expect(err.response.text).toMatch(/Path/);
});
});
it('Should respond with a bad request if bad data is sent', () => {
return superagent.post(api)
.catch(err => {
expect(err.status).toBe(400);
});
});
});
});
});
<file_sep>'use strict';
const Bike = require('../../model/bike.js');
const mocks = require('../lib/mock')
require('jest');
describe('Bike Module', function() {
describe('Bike schema', () => {
this.mockRider = mocks.rider.createOne()
let newBike = new Bike({
make: 'Huffy',
category: 'BMX',
rider: this.mockRider._id
});
it('should create a object', () => {
expect(newBike).toBeInstanceOf(Object);
});
it('should have a rider ID property that matches the mockRider', () => {
expect(newBike.rider).toEqual(this.mockRider._id)
})
});
});<file_sep>import cardReducer from './card'
import {combineReducers} from 'redux'
import categoryReducer from './category'
export default combineReducers({
cards: cardReducer,
categories: categoryReducer,
})
<file_sep>'use strict';
const reader = require('../lib/reader.js');
const imagePath = `${__dirname}/asset/bitmap.bmp`;
const newPath = `${__dirname}/asset/test-bitmap.bmp`;
const badPath = `${__dirname}/assets/test-bitmap.bmp`;
const bitmap = require('../lib/bitmap.js');
const transform = require('../lib/transform.js');
const fs = require('fs');
require('jest');
describe('Reader Module', function() {
describe('#Read', () => {
it('should read file', (done) => {
reader.read(imagePath, (err, fd) => {
if(err) console.error(err);
expect(fd).not.toBeNull();
done();
});
});
it('should not read a file if it does not exist', (done) => {
reader.read(badPath, (err, fd) => {
if(err) console.error(err);
expect(err).not.toBeNull();
done();
});
});
it('should error if file path is missing.', (done) => {
reader.read('', (err, fd) => {
if(err) console.error(err);
expect(err).not.toBeNull();
done();
});
});
});
describe('#Write', () => {
it('should create a new file', (done) => {
reader.read(imagePath, (err, fd) => {
if(err) console.error(err);
expect(fd).not.toBeNull();
bitmap.parse(fd, (err, bmp) => {
if(err) console.error(err);
reader.write(bmp, newPath, err => {
if(err) return console.error(err);
expect(fs.existsSync(newPath)).toBe(true);
done();
});
});
});
});
it('should write data to a new file', (done) => {
reader.read(imagePath, (err, fd) => {
let original_data = fd;
if(err) console.error(err);
expect(fd).not.toBeNull();
bitmap.parse(fd, (err, bmp) => {
if(err) console.error(err);
reader.write(bmp, newPath, err => {
if(err) return console.error(err);
reader.read(imagePath, (err, fd) => {
let new_data = fd;
expect(Buffer.compare(original_data, new_data)).toBe(0);
done();
});
});
});
});
});
it('should not write a new file if the directory does not exist', (done) => {
reader.read(imagePath, (err, fd) => {
if(err) console.error(err);
expect(fd).not.toBeNull();
bitmap.parse(fd, (err, bmp) => {
if(err) console.error(err);
reader.write(bmp, badPath, err => {
if(err) console.error(err);
expect(err).not.toBeNull();
done();
});
});
});
});
});
describe('#Bitmap', () => {
it('should read file and create new bmp object', (done) => {
reader.read(imagePath, (err, fd) => {
if(err) console.error(err);
expect(fd).not.toBeNull();
bitmap.parse(fd, (err, bmp) => {
if(err) console.error(err);
expect(bmp).not.toBeNull();
done();
});
});
});
});
describe('#Transform', () => {
it('should write a changed file', (done) => {
reader.read(imagePath, (err, fd) => {
if(err) console.error(err);
bitmap.parse(fd, (err, bmp) => {
if(err) console.error(err);
let original = bmp.allData;
transform.reverse(bmp, (err, bmpNew) => {
if(err) console.error(err);
let altered = bmpNew.allData;
reader.write(bmpNew, newPath, err => {
if(err) return console.error(err);
expect(Buffer.compare(original, altered)).toBe(0);
done();
});
});
});
});
});
});
});
<file_sep>import React from 'react'
import {Provider} from 'react-redux'
import createStore from '../lib/store'
import Adapter from 'enzyme-adapter-react-16'
import { configure, shallow, mount } from 'enzyme'
import Dashboard from '../component/dashboard/dashboard'
require('jest')
configure({ adapter: new Adapter() })
describe('<Dashboard />', function () {
beforeAll(() => {
let wrapper = mount(<Provider store={createStore()}><Dashboard/></Provider>)
wrapper.setProps({ categories: [
{ _id: '1234', title: 'wat', timestamp: new Date() },
{ _id: '4567', title: 'who', timestamp: new Date() }]})
this.wrapper = wrapper
})
afterAll(() => this.wrapper.unmount())
it('should render two category items in the DOM', () => {
// console.log(this.wrapper.html())
// expect(this.wrapper.find('.dashboard').length).toBe(1)
})
})
<file_sep> 14: Relationship Modeling
===
## Daily Plan
- Notes:
- Anything top of mind?
- [Sign up for 1:1s](https://calendar.google.com/calendar/selfsched?sstoken=UU1Zb1dLQnF<KEY>&pli=1)
- Code Review _Review Mongoose Connection Updates_
- Mongodb Relationships / Populations
- Lifecycle Hooks _Middleware_
- Testing _DB Mocks_
- Lab Preview
## Learning Objectives
* Students will learn about relationship modeling
* Students will be able to create "one to one", "one to many", and "many to many" model relationships using a MongoDB ODM
## Resources
* Read [mongoose populate docs](http://mongoosejs.com/docs/populate.html)
* Skim [mongoose api docs](http://mongoosejs.com/docs/api.html)
## Model Relationships
When the modeling real world as data you will quickly discover that data has relationships to other data. In fact in the real world it is rare, if not impossible, for something to exist that has no relationships to other things. On the other hand in theoretical world we can describe a thing with out describing its relationships to other things. Software engineers have discovered useful ways to describe the relationships (or lack of) between data that can easily be mapped to a database.
#### One
A Model that stands on its own. A web app example includes a simple Note that has no relationship with any other model, It contains all the data it needs.
```
Note
id: 1
content 'get milk and cookies.'
```
#### One to One
When a Model Foo that is related to a single Model Bar. Some web app examples include every user having a single profile, every profile having a single profile photo, every client is limited to a single contact email.
```
User
id: 888
username: slugbyte
profileID: 123
Profile
id: 123
bio: 'i love javascript'
url: 'www.codefellows.com'
userID: 888
```
#### One to Many
A Model Foo that is related to many Bar Models. Some web app examples include every user having may posts but posts have a singe user, every photo having many comments but each comment is to a single photo, every post having many likes but each like is to a single post.
```
Photo
id: 5678
url: 'www.example.com/image/sunset.jpg'
comments: [ 44 65 78 ]
Comment
id: 44
content: 'SO MUCH BEAUTY! <3'
Comment
id: 65
content: 'awesome photo'
Comment
id: 78
content: 'LUL, look at the clouds'
```
#### Many to Many
Many Foo models that can each have relationships to many Bar Models. A web app examples includes every user having a relation ship with many friends and each of those users have relationships with a many different friends.
Some databases (including MongoDB) do not natively support models having many to many relationships, but many to many can still be created through the use of a second model.
###### Using One Model
```
User
id: 1234
username: 'teapot'
friends: [ 1001 3333 4321 ]
User
id: 1001
username: 'peach'
friends: [ 1234 5000 ]
```
###### Using A Second Model
```
User
id: 1234
username: 'teapot'
friendsID: 33
User
id: 1001
username: 'peach'
freindsID: 77
Friends
id: 33
users: [ 1001 3333 4321]
Friends
id: 77
users: [ 1234 5000 ]
```
<file_sep>'use strict'
const Note = require('../model/note')
const storage = require('../lib/storage')
const debug = require('debug')('http:route-note')
module.exports = function(router) {
router.post('/api/v1/note', (req, res) => {
debug('POST /api/v1/note')
try {
debugger;
let newNote = new Note(req.body.title, req.body.content)
storage.create('Note', newNote)
.then(storedNote => {
res.writeHead(201, {'Content-Type': 'application/json'})
res.write(JSON.stringify(storedNote))
res.end()
})
} catch(err) {
debug(`There was a bad request: ${err}`)
res.writeHead(400, {'Content-Type': 'text/plain'})
res.write('Bad Request')
res.end()
}
})
router.get('/api/v1/note', (req, res) => {
})
router.put('/api/v1/note', (req, res) => {
})
router.delete('/api/v1/note', (req, res) => {
})
}
<file_sep>import React from 'react'
class ExpenseCreateForm extends React.Component {
constructor(props) {
super(props)
this.state = {
name: '',
price: 0,
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(e) {
this.setState({[e.target.name]: e.target.value})
}
handleSubmit(e) {
e.preventDefault()
let expense = {...this.state}
expense._id = Math.random().toString()
this.props.dashboard.setState({expenses: [...this.props.dashboard.state.expenses, expense]})
// this.props.dashboard.setState(prevState => ({
// expenses: [...prevState.expenses, expense]
// }))
}
render() {
return (
<form className="expense-create-form" onSubmit={this.handleSubmit}>
<input
type="text"
name="name"
value={this.state.name}
onChange={this.handleChange}
placeholder="Bought Dan a new (Matchbox) car"/>
<input
type="number"
name="price"
value={this.state.price}
onChange={this.handleChange}
placeholder='3.50'/>
<button type="submit">Spend</button>
{/* <SomeComponent dashboard={this.props.dashboard}/> */}
</form>
)
}
}
export default ExpenseCreateForm
<file_sep>'use strict'
const myMath = require('./lib/math')
myMath.absolute(-10000)<file_sep>const reader = require('../lib/reader.js');
const imagePath = `${__dirname}/asset/bitmap.bmp`;
const not_imagePath = `${__dirname}/asset/not_image.txt`;
const wrongBMP_imagePath = `${__dirname}/asset/MARBLES.BMP`;
const bitmap = require('../lib/bitmap.js');
describe('#bitmap test Module', function() {
it('should return error if buffer is null', (done) => {
bitmap.parse(null, (err, bmp) => {
if(err) console.error(err);
expect(err).not.toBeNull();
done();
});
});
it('should return object when passed a buffer', (done) => {
reader.read(imagePath, (err, data) => {
bitmap.parse(data, (err, bmp) => {
if(err) console.error(err);
expect(bmp).toBeInstanceOf(Object);
done();
});
});
});
it('should return an error when passed a buffer that is not from a bitmap', (done) => {
reader.read(not_imagePath, (err, data) => {
bitmap.parse(data, (err, bmp) => {
if(err) console.error(err);
expect(err).not.toBeNull();
done();
});
});
});
// it('should return an error when passed a buffer that is not from a windows bitmap of the proper format', (done) => {
// reader.read(wrongBMP_imagePath, (err, data) => {
// bitmap.parse(data, (err, bmp) => {
// if(err) console.error(err);
// expect(err).not.toBeNull();
// done();
// });
// });
// });
});<file_sep>'use strict'
const mongoose = require('mongoose')
const Track = mongoose.Schema({
'speechiness': Number,
'key' : { type: Number },
'time_signature': { type: Number },
'liveness' : { type: Number },
'loudness': { type: Number },
'duration_ms' : { type: Number },
'danceability': { type: Number },
'duration' : { type: Number },
'valence': { type: Number },
'acousticness' : { type: Number },
'spotify_id': { type: String },
'volume_number' : { type: Number },
'energy': { type: Number },
'tempo' : { type: Number },
'instrumentalness': { type: Number },
'mode' : { type: Number },
'number': { type: Number },
'artist' : { type: String, require: true },
'title': { type: String, require: true },
}, {timestamps: true})
module.exports = mongoose.model('tracks', Track)<file_sep>import * as actions from '../action/category-actions'
require('jest')
describe('category actions', () => {
it('should create an action to add a category', () => {
let category = {title: 'hello world'}
let action = actions.categoryCreate(category)
expect(action.type).toEqual('CATEGORY_CREATE')
expect(action.payload).toHaveProperty('_id')
expect(action.payload).toHaveProperty('timestamp')
})
})
<file_sep>import React from 'react'
class ExpenseUpdateForm extends React.Component {
constructor(props) {
super(props)
this.state = this.props.expense
? this.props.expense
: {
_id: '',
name: '',
price: 0,
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(e) {
e.preventDefault()
this.props.dashboard.setState(prevState => {
expenses: prevState.expenses.map(expense => {
if(expense._id === this.state._id) {
console.log('made it')
return this.state
}
return expense
})
})
// this.props.dashboard.setState(prevState => {
// expenses: prevState.expenses.map(expense =>
// expense._id === this.state._id ? this.state : expense)
// })
}
handleChange(e) {
this.setState({[e.target.name]: e.target.value})
}
render() {
return (
<form
className="expense-update-form"
onSubmit={this.handleSubmit}>
<input
type="text"
name="name"
value={this.state.name}
onChange={this.handleChange}/>
<input
type="number"
name="price"
value={this.state.price}
onChange={this.handleChange}/>
<button type="submit">update</button>
<button type="button" onClick={this.props.toggleEdit}>cancel</button>
</form>
)
}
}
export default ExpenseUpdateForm
<file_sep>import React from 'react';
import {connect} from 'react-redux';
import {categoryCreate, categoryDelete, categoryUpdate} from '../../action/category-actions';
import CategoryForm from '../category-form/index';
import CategoryItem from '../category-list/index';
class Dashboard extends React.Component {
render() {
return(
<section>
<h1>Expenses Categories</h1>
<CategoryForm
buttonText='create'
onComplete={this.props.dashboardCategoryCreate}/>
{this.props.categories ?
this.props.categories.map(cat =>
<CategoryItem key={cat._id}
category={cat}
handleDelete={this.props.dashboardCategoryDelete}
handleUpdate={this.props.dashboardCategoryUpdate}
/>)
:
undefined
}
</section>
);
}
}
const mapStateToProps = state => ({
categories: state,
});
const mapDispatchToProps = (dispatch, getState) => ({
dashboardCategoryCreate: category => dispatch(categoryCreate(category)),
dashboardCategoryDelete: category => dispatch(categoryDelete(category)),
dashboardCategoryUpdate: category => dispatch(categoryUpdate(category)),
});
export default connect(mapStateToProps, mapDispatchToProps) (Dashboard);
<file_sep>'use strict';
const mongoose = require('mongoose');
const Rider = module.exports = mongoose.Schema({
name: {type: String, max: 32},
bikes: [{type: mongoose.Schema.Types.ObjectId, ref: 'bikes'}],
});
Rider.pre('save', function(next) {
this.validate((err) => {
if(err) next(() => console.error(err))
next()
})
})
module.exports = mongoose.model('riders', Rider);<file_sep> 03: Asynchronous Callbacks
=====================================
## Daily Plan
- Notes:
- Anything top of mind?
- Career Coaching Assignments _heads up that they're coming!!_
- Node Callback Pattern
- The Event Loop
- Recursion
- Quick code challenge _sum all numbers from 0 to n_
- Lets solve it with a call stack exercise
- Async (concurrency)
- FS Module _working with the file system_
- Buffers _Introduction_
- Testing Async Code
- Tell it when it can be `done` OR just `return` the async code...
- Lab Preview
- Lab Setups _Code challenges and general labs_
- Whiteboard Process Discussion
# Learning Objectives
* Students will understand the how synchronous and asynchronous code runs in the Javascript runtime
* Students will be able to manage asynchronous data flow using error first callbacks
* Students will be able to utilize the asynchronous methods on the built-in Node modules
* Students will be able to work with raw data using Node's Buffers
* Students will be able to test asynchronous code using a BDD testing framework
# Resources
* Watch [What the Heck is the Event Loop Anyway](https://www.youtube.com/watch?v=8aGhZQkoFbQ)
* Read [Understanding Error First Callbacks](http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/)
* Skim [Node's File System Module Docs](https://Nodejs.org/dist/latest-v9.x/docs/api/fs.html)
* Skim [Node's buffer documentation](https://Nodejs.org/api/buffer.html#buffer_buffer)
# Javascript Runtime
* There are many Javascript runtimes.
* V8 is the name of the runtime used in Chrome browsers and NodeJS.
* V8 will be used in the following descriptions of how JavaScript a runtime works, but other browsers and JavaScript environments have the same behaviors.
# Concurrency
* In programing, concurrency means that a program can run more than one thing at a time.
* The ability to do multiple things at a time can greatly increase the amount of things your program can do in a given moment in time. However, traditional means of handling concurrency are extremely complex, and often lead to bugs!
* Javascript is a single threaded language.
* Which means that it can only do a single thing at a time.
* However, the JavaScript runtime is setup in such a way that your programs can still have some concurrent behavior, as long as the concurrent behavior is not implemented in JavaScript.
## Node's Concurrency
* The Node C++ apis are written in such a way that they deal with all the complexities of concurrency for us!
* We are programming at a higher abstraction - removing the need to deal with lower level threading
* The NodeJS event loop operates under a single thread
* NodeJS uses many threads "underneath the hood" (libuv)
* NodeJs concurrency through the use of events and callbacks
* When a JavaScript function makes a call to Node APIs, it passes the Node API a callback.
* The Node api does it thing
* Passes its results into the callback
* Enqueues the callback onto the callback queue
### Call Stack
* The stack keeps track of each function that is currently running in JavaScript
* At any given point in time JavaScript is only running the function on top of the call stack
* Each time a function gets invoked it gets pushed onto the call stack
* Each time a function returns it gets popped from the call stack
### Event Loop
* when NodeJS starts up, it processes the input script then begins processing the event loop
* The event loop constantly checks if the call stack is empty
* When the stack is empty it dequeues any functions on the callback queue and pushes them onto the stack
### Callback Queue
* The callback queue holds completion handling functions from passed Node APIs
* Functions stored on the Callback Queue are not executing, they are only waiting to be put on to the Call Stack.
## Node asynchronous callback pattern
* Node functions that have asynchronous input or output take a callback as the last argument
* Node functions that do not pass back data always have callback functions take the form `(err) => { }`
* Node functions that do pass back data always have callback functions take the form `(err, data) => { }`
# Working With Binary Data (Part 1)
## Bits and bytes
* A bit is the smallest unit of data in a computer
* A bit contains a single binary value, 0 or 1
* A byte is comprised of 8 bits
* We often refer to a nibble as 4 bits (half of a byte)
## Endianness
* Refers to the order of bytes
* Little endian
* Bytes are written from left to right
* Big endian
* Bytes are written from right to left
## Buffers
* Buffers are an array of bytes
* Example:
```Javascript
var buff = Buffer.from('Welcome to Bufferville');
console.log(buff);
<Buffer 77 65 6c 63 6f 6d 65 20 74 6f 20 62 75 66 66 65 72 76 69 6c 6c 65>
```
* Common encoding types:
* UTF-8 (default)
* `buff.toString('utf-8')`
* Base64
* `buff.toString('base64')`
* Hex
* `buff.toString('hex')`
## File System (a.k.a FS) Module
* The FS module is the Node interface to the file system
* The FS module has synchronous and asynchronous methods
* If the method does not have sync in its name you can assume its synchronous
* In this class we will **NEVER** use the synchronous methods
* Useful globals
* `__dirname` - the absolute path to the directory the current file is in
* `__filename` - the absolute path to the current file
* Create File
* `fs.writeFile(filepath, data [, options], callback);`
* The callback should take the form `(error) => {}`
* Read File
* `fs.readFile(filepath [, options], callback);`
* The callback should take the form `(error, data) => {}`
* Delete File
* `fs.unlink(filepath, callback);`
* The callback should take the form `(error) => {}`
* Other useful methods
* `readdir` - reads the contents of a directory
* `mkdir` - create a directory
* `stat` - get information about a file/dir/link
* `watch` - watch a file for changes
#### Asynchronous Testing
* **Calling `done`**
* Jest gives us a short timeframe to call `done` before a timeout error occurs
* be sure to call `done` in the appropriate location (usually, this in your internal logic)
* calling `done` in the wrong block will likely cause a false positive test result
* **demo:** testing file system I/O<file_sep>let initialState = {
// 'uncategorized': [] // maybe we want to force any cards to this key when we delete a category?
}
// {
// 'id1234': [],
// 'id456': [],
// }
export default (state=initialState, action) => {
let {type, payload} = action
switch(type) {
case 'CATEGORY_CREATE': return {...state, [payload._id]: []}
case 'CATEGORY_DELETE':
let changedState = {...state}
delete changedState[payload._id]
return changedState
case 'CARD_CREATE': return // you do the thing
case 'CARD_UPDATE': return // you do the thing
case 'CARD_DELETE': return // you do the thing
case 'CARD_RESET': return initialState
default: return state
}
}
<file_sep>'use strict'
const Album = require('../model/album')
const bodyParser = require('body-parser').json()
const errorHandler = require('../lib/error-handler')
module.exports = function(router) {
router.route('/album/:_id?')
.get((req, res) => {
if(req.params._id) {
return Album.findById(req.params._id)
.then(album => res.status(200).json(album))
.catch(err => errorHandler(err, res))
}
Album.find()
// .then(albums => albums.map(a => a._id))
.then(ids => res.status(200).json(ids))
.catch(err => errorHandler(err, res))
})
.post(bodyParser, (req, res) => {
new Album(req.body).save()
.then(album => res.status(201).json(album))
.catch(err => errorHandler(err, res))
})
.put(bodyParser, (req, res) => {
Album.findByIdAndUpdate(req.params._id, req.body, {upsert: true, runValidators: true})
.then(() => res.sendStatus(204))
.catch(err => errorHandler(err, res))
})
.delete((req, res) => {
Album.findByIdAndRemove(req.params._id)
.then(() => res.sendStatus(204))
.catch(err => errorHandler(err, res))
})
}
<file_sep>
- Merge Sort
- Quick Sort
- Selection Sort
- Radix Sort
<file_sep>'use strict'
const faker = require('faker')
const Album = require('../../model/album')
const Track = require('../../model/track')
const mock = module.exports = {}
// Album Mocks - One, Many, RemoveAll
mock.album = {}
mock.album.createOne = () => new Album({ name: faker.hacker.adjective() }).save()
mock.album.createMany = n =>
Promise.all(new Array(n).fill(0).map(mock.album.createOne))
mock.album.removeAll = () => Promise.all([Album.remove()])
// Track Mocks - One, Many, RemoveAll
mock.track = {}
mock.track.createOne = () => {
let result = {}
return mock.album.createOne()
.then(album => {
result.album = album
return new Track({
artist: `${faker.name.firstName()} ${faker.name.lastName()}`,
title: faker.hacker.ingverb(),
album: album._id.toString(),
}).save()
})
.then(track => result.track = track)
.then(() => result)
}
mock.track.createMany = n => {
let result = {}
return mock.album.createOne()
.then(album => {
result.album = album
let trackProms = new Array(n).fill(0).map(() => new Track({
artist: `${faker.name.firstName()} ${faker.name.lastName()}`,
title: faker.hacker.ingverb(),
album: album._id.toString(),
}).save())
return Promise.all(trackProms)
})
.then(tracks => result.tracks = tracks)
.then(() => result)
}
mock.track.removeAll = () => Promise.all([Track.remove()])
<file_sep>'use strict'
const math = require('../lib/math')
require('jest') // This is not required
// This is a basic Jest assertion
expect(math.floor(1.123)).not.toEqual(1.123)
expect(math.floor(1.123)).toEqual(1)
describe('Math Module', function() {
describe('#Floor', function() {
it('should take in a floating point number, and return the previous whole integer', function() {
expect(math.floor(1.123)).toEqual(1)
expect(math.floor(1.123)).not.toEqual(1.123)
})
it('should validate that the input for `num` is a numeric value', function() {
// expect(...)
})
})
describe('#Ceiling', function() {
})
describe('#Absolute', function() {
})
})<file_sep>'use strict'
// Application dependencies
const net = require('net')
const Client = require('./model/client')
const cmd = require('./lib/cmd')
// Application setup
const server = module.exports = net.createServer()
const PORT = process.env.PORT || 3000
let clientPool = []
// Server instance setup
server.on('connection', function(socket) {
let client = new Client(socket)
clientPool.push(client)
clientPool.map(c => c.socket.write(`\t${client.nick} has joined the game\n`))
socket.on('data', function(data) {
// This is where you will abstract away to your command parser module...
// console.log('socket data', data)
let message = data.toString()
clientPool.filter(
c => c.user !== client.user).map(
c => c.socket.write(`${client.nick}: ${message}\n`))
})
socket.on('close', function() {
clientPool = clientPool.filter(c => c.user !== client.user)
clientPool.map(c => c.socket.write(`\t${client.nick} has left the channel\n`))
})
socket.on('error', function(err) {
console.error(err)
})
})
server.listen(PORT, () => console.log(`Listening on ${PORT}`))<file_sep>'use strict'
const uuid = require('uuid/v4')
module.exports = function Note(title, content) {
return new Promise((resolve, reject) => {
if(!title || !content) return reject(new Error('Validation Error. Cannot create Note. Title and Content required.'))
this._id = uuid()
this.title = title
this.content = content
return resolve(this)
})
}<file_sep>'use strict'
const colors = require('./lib/colors')
// colors => {makeBlue: function() {}, ...}
colors.makeBlue(/* pass in some args */) // => turn something blue
colors.makeRed(/* pass in some args */) // => turn something red
<file_sep>'use strict';
const index = require('../index.js');
require('jest');
describe('Index Module', function() {
describe('#Start', () => {
it('should not run without arguments', () => {
expect(index.processImage([])).toEqual(expect.stringContaining('Invalid arguments'));
});
it('should not run with less than three arguments', () => {
expect(index.processImage(['./__test__/asset/bitmap.bmp', 'test'])).toEqual(expect.stringContaining('Invalid arguments'));
});
it('should not run with invalid transform method', () => {
expect(index.processImage(['node', 'index.js', './__test__/asset/bitmap.bmp', 'test', 'foo'])).toEqual(expect.stringContaining('Invalid transform method'));
});
});
});
<file_sep>'use strict';
const server = require('../../lib/server.js');
const superagent = require('superagent');
const mock = require('../lib/mock.js');
const faker = require('faker');
require('jest');
describe('POST', function() {
beforeAll(server.start);
afterAll(server.stop);
afterAll(mock.rider.removeAll);
afterAll(mock.bike.removeAll);
beforeAll(() => {
return mock.rider.createOne()
.then(rider => this.rider = rider)
.then(() => {
this.fakeBike = {
make: faker.hacker.noun(),
category: faker.hacker.verb(),
rider: this.rider._id,
};
});
});
describe('Valid req/res', () => {
beforeAll(() => {
return superagent.post(':4000/api/v1/bike')
.send(this.fakeBike)
.then(res => this.response = res);
});
it('should post a new bike with make, and _id', () => {
expect(this.response.body).toHaveProperty('make');
// expect(this.resBike.body).toHaveProperty('year');
expect(this.response.body).toHaveProperty('_id');
});
it('should respond with a status of 201', () => {
expect(this.response.status).toBe(201);
});
});
describe('Invalid req/res', () => {
it('should return a status 404 on bad path', () => {
return superagent.post(':4000/api/v1/doesnotexist')
.send(this.mockNote)
.catch(err => {
expect(err.status).toBe(404);
expect(err.response.text).toMatch(/path error/i);
});
});
it('should return a status 400 on a bad request body', () => {
return superagent.post(':4000/api/v1/bike')
.send({})
.catch(err => expect(err.status).toBe(400));
});
});
});<file_sep>// you all get to define your expense actions!
<file_sep> 10: Doubly Linked Lists, Stacks, Queues & Binary Search
===
## Daily Plan
- Notes:
- Anything top of mind?
- Data Structures Repos _at some point..._
- Code Review _Implement FS Storage?_
- Stacks & Queues
- Lab Preview
## Learning Objectives
* Students will be able to implement a doubly linked list
* Students will be able to implement a stack
* Students will be able to identify use cases for a stack
* Students will be able to implement a queue
* Students will be able to identify use cases for a queue
* Students will understand the inner workings or Binary Search
## Resources
* Watch [stacks and queues](https://www.youtube.com/watch?v=wjI1WNcIntg)
* Skim [stack wiki](https://en.wikipedia.org/wiki/Stack_(abstract_data_type))
* Skim [queue wiki](https://en.wikipedia.org/wiki/Queue_(abstract_data_type))
#### Stacks
Stacks are a data structure that serve as a collection of elements. These elements are stacked in a last in, first out sequence **(aka FILO - first in, last out)**. It may help to think about a stack as a collection of plates and the way that you add and remove them.
Common methods include:
* `pop` removes the most recent element from the stack
* `push` adds a new element to the stack
#### Queues
Queues are also a data structure that serve as a collection of elements. Elements in a queue are added in a first in, first out sequence **(aka FIFO - first in first out)**. It may help to think about a queue as a bunch of people standing in line at a concert - the first person in line is the first person in the venue.
Common methods include:
* `enqueue` is used to add an element to the end of a queue
* `dequeue` is used to retrieve and remove an element from the beginning of a queue<file_sep>'use strict';
const Note = require('../model/note');
const debug = require('debug')('http:route-note');
const bodyParser = require('body-parser').json();
const storage = require('../lib/storage');
const errorHandler = require('../lib/error-handler');
module.exports = function (router) {
router.post('/note', bodyParser, (req, res) => {
debug('Begin Post');
new Note(req.body.title, req.body.content) // O(1) Normal Operation (Best Case)
.then(note => storage.create('Note', note))
.then(item => res.status(201).json(item))
.catch(err => errorHandler(err, res));
});
router.get('/note/:_id', (req, res) => {
debug('Begin Get One');
storage.fetchOne('Note', req.params._id) // O(1) Normal Operation (Best Case)
.then(buffer => buffer.toString())
.then(json => JSON.parse(json))
.then(note => res.status(200).json(note))
.catch(err => errorHandler(err, res));
});
router.get('/note', (req, res) => {
debug('Begin Get All');
storage.fetch('Note') // O(n) Normal Operation (Best Case)
.then(files => res.status(200).json(files))
.catch(err => errorHandler(err, res));
});
router.put('/note/:_id', bodyParser, (req, res) => {
debug('Begin Put');
storage.update('Note', req.params._id, req.body) // O(1) Normal Operation (Best Case)
.then(() => res.status(204).send())
.catch(err => errorHandler(err, res));
});
router.delete('/note/:_id', (req, res) => {
debug('Begin Delete');
storage.destroy('Note', req.params._id) // O(1) Normal Operation (Best Case)
.then(() => res.status(204).send())
.catch(err => errorHandler(err, res));
});
};<file_sep>import React from 'react'
import {renderIf} from '../../../lib/utils'
import ExpenseUpdateForm from '../expense-update-form/expense-update-form';
class ExpenseItem extends React.Component {
constructor(props) {
super(props)
this.state = {
item: this.props.item ? this.props.item : {},
editing: false,
}
this.handleEditing = this.handleEditing.bind(this)
}
handleEditing() {
this.setState({editing: !this.state.editing})
}
render() {
return (
<li
className="expense-item"
id={this.state.item._id}
onDoubleClick={this.handleEditing}>
<p>Name: {this.state.item.name}</p>
<p>Price: ${this.state.item.price}</p>
{renderIf(this.state.editing,
<ExpenseUpdateForm
expense={this.state.item}
toggleEdit={this.handleEditing}
dashboard={this.props.dashboard}/>
)}
</li>
)
}
}
export default ExpenseItem
<file_sep>'use strict'
const server = require('../server')
const net = require('net')
require('jest')
describe('Server module', function() {
afterAll(() => server.close())
describe('setting up a connection to the server', () => {
it('should connect and notify me that I joined the channel', done => {
let socket = net.connect({port: 3000})
// console.log(socket)
socket.on('data', data => {
expect(data.toString()).toMatch(/has joined the chat/)
// expect(data.toString()).not.toMatch(/BOOGIE NIGHTS/)
socket.end()
done()
})
})
})
// SCOTT WILL FIX THIS ONE
// describe('testing facepalm command', () => {
// it('should facepalm', done => {
// let messages = []
// let socket = net.connect({port: 3000})
// socket.write('@facepalm', () => {
// socket.on('data', data => {
// console.log('data', data.toString())
// messages.push(data.toString())
// socket.end(null, () => {
// console.log(messages)
// expect(messages[0]).toMatch(/is disappointed/)
// done()
// })
// })
// })
// })
})
})<file_sep>import './styles/reset.scss'
import './styles/main.scss'
import React from 'react'
import ReactDom from 'react-dom'
import Select from './components/form-elements/select/select'
import FormInput from './components/form-elements/input/input'
import Slider from './components/form-elements/slider-checkbox/slider'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
title: '',
dropDown: {},
slider: false,
}
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
this.sliderToggle = this.sliderToggle.bind(this)
this.handleDropdown = this.handleDropdown.bind(this)
}
handleSubmit(e) {
e.preventDefault()
console.log(this.state)
}
handleChange(e) {
this.setState({[e.target.name]: e.target.value})
}
sliderToggle(e) {
console.log('slider is:', e.target.checked)
this.setState({slider: e.target.checked})
}
handleDropdown(item) {
this.setState({dropDown: item})
}
render() {
return (
<div className="application">
<h1>Hello world!</h1>
<h3>Check out my custom form elements</h3>
<div className="form-container">
<form onSubmit={this.handleSubmit}>
<FormInput
config={({
className: 'form-inputs',
name: 'title',
value: this.state.title,
type: 'text',
placeholder: 'React Documentation'
})}
onChange={this.handleChange}/>
<Slider
config={({
id: 'slider-one',
className: 'slider-checkbox',
value: this.state.sliderOne,
name: 'slider-one'
})}
onChange={this.sliderToggle}/>
<Select
config={{
classes: '',
items: [{_id: '1234', name: 'Hello'}, {_id: '4567', name: 'Goodbye'}, {_id: '8901', name: 'Wat'}]
}}
onComplete={this.handleDropdown}/>
<button type="submit">submit</button>
</form>
</div>
</div>
)
}
}
ReactDom.render(<App />, document.getElementById('root'))
<file_sep> 33: Redux Middleware
===
## Daily Plan
- Notes
- Anything top of mind?
- Code Review
- Redux Middleware
- Thunk
- Lab Preview
## Learning Objectives
* Students will be able to create middleware for redux
* Students will be able to add third party middleware to redux
## Readings
* Read [redux middleware](http://redux.js.org/docs/advanced/Middleware.html)
## Overview
Redux middleware provides a third-party extension point between dispatching and action and the moment it reaches the reducer. It can be used for logging actions, adding promise support, making api requests, caching, throttling, and much more.
<file_sep>'use strict'
// Application dependencies
const express = require('express')
const cors = require('cors')
const errorHandler = require('./error-handler')
// Application setup
const app = express()
const router_notes = express.Router()
// const router_users = express.Router()
// const router_images = express.Router()
app.use('/api/v1/note', router_notes)
// app.use('/api/v1/users', router_users)
// app.use('/api/v1/images', router_images)
// app.use(bodyParser) // Applies the package to every route in the app
app.use(cors())
// Route setup
require('../route/route-note')(router_notes)
// require('../route/route-category')(router)
app.use('/{0,}', (req, res) => errorHandler(new Error('Path Error. Route not found.'), res))
// Server controls
const server = module.exports = {}
server.isOn = false
server.http = null
server.start = function(port, callback) {
if(server.isOn) return callback(new Error('Server running. Cannot start server again.'))
server.isOn = true
server.http = app.listen(port, callback)
}
server.stop = function(callback) {
if(!server.isOn) return callback(new Error('Server not running. You\'re dumb. Don\'t do that.'))
server.isOn = false
server.http.close()
}<file_sep> 37: Cookies
===
## Daily Plan
- Notes:
- Anything top of mind?
- Project Teams & Planning
- Final Exams - Next week: Scott will put out a schedule.
- Code Review
- Review of Cookies / Browser State
- Client-side Auth
- Lab Preview
## Learning Objectives
* Students will be able to manage Basic and Bearer authentication on the client side
* Students will be able to manage cookies on the client side
## Readings
* Read [cookies](https://www.quirksmode.org/js/cookies.html)
* Read [Http Cookie Wiki](https://en.wikipedia.org/wiki/HTTP_cookie)
## Cookies
Cookies are key value pairs that can store text. They are meant to be a reliable place to store stateful information on the browser. Cookies can be given an expiration date, and the browser will automatically remove them when that date occurs.
<file_sep>let validateAlbum = payload => {
if(!payload._id) throw new Error('VALIDATION ERROR. Album must have an ID')
if(!payload.name) throw new Error('VALIDATION ERROR. Album must have name')
}
export default (state=[], action) => {
let {type, payload} = action
// validateAlbum(payload) // Reminder that we can't do this in every case, so it's situational.
switch(type) {
case 'ALBUM_SET': return payload
case 'ALBUM_CREATE':
validateAlbum(payload)
return [...state, payload]
case 'ALBUM_UPDATE':
validateAlbum(payload)
return state.map(album => album._id === payload._id ? payload : album)
case 'ALBUM_DELETE':
validateAlbum(payload)
return state.filter(album => album._id !== payload._id)
default: return state
}
}
<file_sep>import React from 'react';
class ExpenseForm extends React.Component{
constructor(props){
super(props);// Vinicio - we HAVE to call this super()
this.state = {
name : '',
price : 0,
};
//----------------------------------------------------
// Binding Handlers
//----------------------------------------------------
let memberFunctions = Object.getOwnPropertyNames(ExpenseForm.prototype);
for(let functionName of memberFunctions){
if(functionName.startsWith('handle')){
this[functionName] = this[functionName].bind(this);
}
}
//----------------------------------------------------
}
//------------------------------------------------------
// Member Function
//------------------------------------------------------
handleSubmit(event){
event.preventDefault();
this.props.handleAddExpense(this.state);
// vinicio - clearing the form
this.setState({
name : '',
price : 0,
});
}
handleChange(event){
let {name,value} = event.target;
// vinicio - name will be the name of the input we are working with
this.setState({
[name]: value,
});
}
//------------------------------------------------------
// Lifecycle hooks
//------------------------------------------------------
render(){
return(
<form className='expense-form' onSubmit={this.handleSubmit}>
<input
type='text'
name='name'
placeholder='name'
value={this.state.name}
onChange={this.handleChange}
/>
<input
type='number'
name='price'
placeholder='price'
value={this.state.price}
onChange={this.handleChange}
/>
<button type='submit'> create expense </button>
</form>
);
}
};
export default ExpenseForm;<file_sep>'use strict';
const Bike = require('../model/bike.js');
const bodyParser = require('body-parser').json();
const errorHandler = require('../lib/error-handler.js');
module.exports = function(router) {
router.route('/bike/:_id?')
.get((req, res) => {
if(req.params._id) {
return Bike.findById(req.params._id)
.populate('rider')
.then(bike => res.status(200).json(bike))
.catch(err => errorHandler(err, res));
}
Bike.find()
.then(bike => bike.map(bike => bike._id))
.then(bike => res.status(200).json(bike))
.catch(err => errorHandler(err, res));
})
.post(bodyParser, (req, res) => {
new Bike(req.body).save()
.then(bike => res.status(201).json(bike))
.catch(err => errorHandler(err, res));
})
.put(bodyParser, (req, res) => {
Bike.findOneAndUpdate(req.params._id, req.body, {upsert: true, runValidators: true})
.then(() => res.sendStatus(204))
.catch(err => errorHandler(err, res));
})
.delete((req, res) => {
Bike.findById(req.params._id)
.then(bike => bike.remove())
.then(() => res.sendStatus(204))
.catch(err => errorHandler(err, res));
});
};<file_sep> 39: TBD
===
## Learning Objectives
<!-- * need more content here... svg and fonts isn't enough for a full day -->
* Students will be able to load fonts with webpack
* Students will be able to create icons using SVGs
* Students will learn the difference between icon fonts and inline svgs
## Readings
* Skim [url-loader docs](https://webpack.js.org/loaders/url-loader/)
* Read [icon-font vs inline-vg](https://css-tricks.com/icon-fonts-vs-svg/)
## URL Loader
The url loader can either copy an imported asset into the build path, or turn it into a DataURL. This DataURL can be used to preview the image in the browser, prior to gaining a response from S3, with the newly created AWS CDN url.
## SVGs
SVGs are natively supported in HTML. By using inline SVG's you open the potential for much more styling control.
<file_sep>import React from 'react'
import {connect} from 'react-redux'
import {
albumFetchRequest,
albumCreateRequest} from '../../actions/album-actions'
class Dashboard extends React.Component {
componentWillMount() {
this.props.fetchAlbums()
}
render() {
return (
<div className="dashboard-container">
<h1>Hello world - music things</h1>
{this.props.albums ?
this.props.albums.map(album =>
<div key={album._id}>
{/* <span onClick={() => this.props.deleteAlbum(album)}>x</span> */}
<p>{album.name}</p>
</div>)
:
undefined
}
</div>
)
}
}
let mapStateToProps = state => ({
albums: state.albums,
})
let mapDispatchToProps = dispatch => ({
fetchAlbums: () => dispatch(albumFetchRequest()),
createAlbum: album => dispatch(albumCreateRequest(album)),
// deleteAlbum: album => dispatch(albumDeleteRequest(album)),
})
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)
<file_sep>import superagent from 'superagent'
import { logError } from '../lib/utils'
export const trackSet = tracks => ({
type: 'TRACK_SET',
payload: tracks
})
export const trackCreate = track => ({
type: 'TRACK_CREATE',
payload: track
})
export const trackUpdate = track => ({
type: 'TRACK_UPDATE',
payload: track
})
export const trackDelete = track => ({
type: 'TRACK_DELETE',
payload: track
})
export const trackFetchRequest = () => dispatch => {
return superagent.get(`${__API_URL__}/api/v1/track`)
.then(res => dispatch(trackSet(res.body)))
.catch(logError)
}
export const trackCreateRequest = track => dispatch => {
return superagent.post(`${__API_URL__}/api/v1/track`)
.send(track)
.then(res => dispatch(trackCreate(res.body)))
.catch(logError)
}
export const trackUpdateRequest = track => dispatch => {
return superagent.put(`${__API_URL__}/api/v1/track/${track._id}`)
.send(track)
.then(() => dispatch(trackUpdate(track)))
.catch(logError)
}
export const trackDeleteRequest = track => dispatch => {
return superagent.delete(`${__API_URL__}/api/v1/track/${track._id}`)
.then(() => dispatch(trackDelete(track)))
.catch(logError)
}
<file_sep>'use strict'
const server = require('../lib/server')
const superagent = require('superagent')
describe('Server module', function() {
beforeAll(() => server.start(4444))
afterAll(() => server.stop())
describe('Valid Request to the API', () => {
describe('GET /time', () => {
it('should respond with a status 200', () => {
return superagent.get(':4444/time')
.then(res => {
expect(res.status).toBe(200)
})
//.catch() // usually not needed in a case of successful request
})
it('should return a date/time object', () => {
return superagent.get(':4444/time')
.then(res => {
expect(res.body).toHaveProperty('now')
expect(res.body).toBeInstanceOf(Object)
})
})
})
})
describe('Invalid Request to the API', () => {
it('should return a 404 status code', () => {
return superagent.get(':4444/doesNotExist')
.catch(err => {
expect(err.status).toBe(404)
})
})
})
})<file_sep>'use strict'
const fs = require('fs')
fs.readFile(`${__dirname}/data/one.html`, (err, data) => {
if(err) console.error(err)
let buffer = data
let fd = data.toString()
let hex = data.toString('hex')
let tim = hex * 3 // will return NaN
// some manipulation or aggregation of the data, buffer or otherwise
fs.writeFile(`${__dirname}/data/new.html`, tim, err => err ? console.error(err) : undefined)
})<file_sep>import React from 'react'
import {connect} from 'react-redux'
import CardForm from '../card-form/card-form'
import {cardUpdate, cardDelete} from '../../../action/card-actions'
class CardItem extends React.Component {
render() {
return (
<section id={this.props.card._id}>
<h3>{this.props.title}</h3>
<span onClick={() => this.props.cardDelete(this.props.card)}>x</span>
<CardForm
buttonText="update"
card={this.props.card}
onComplete={this.props.cardUpdate}/>
</section>
)
}
}
let mapStateToProps = () => ({})
let mapDispatchToProps = (dispatch, getState) => ({
cardUpdate: card => dispatch(cardUpdate(card)),
cardDelete: card => dispatch(cardDelete(card)),
})
export default connect(mapStateToProps, mapDispatchToProps)(CardItem)
<file_sep> 01: Node Ecosystem
=====================================
## Daily Plan
- Notes:
- Anything top of mind? _expect this question every day!_
- Housekeeping Items _see whiteboard_
- Course Overview
- 1st Half _Node, Express, MongoDB_
- 2nd Half _React & Redux_
- Daily Process Introduction _Normally_
- 9a: Lecture
- 12p: Lunch
- 1p: Whiteboard challenge
- 130p - 6p: Labs
- Git/Github & Other Tools
- Developer Environment _You should not be thinking much about it at this point_
- NodeJS _Reintroduction_
- Strict Mode: Use. Always. It's helping your code run as optimal as possible for the JS Engine!
- CommonJS Modules _and a quick chat about import/export_
- Testing with Jest _Test Driven Development_
- Lab & Whiteboard Challenge Preview
- Whiteboarding Process _Time permitting_
# Learning Objectives
* Students will be able to set up a node project
* Students will be able to create node modules that conform to the CommonJS module pattern
* Students will be able to construct and run unit tests
* Students will be able explain the TDD philosophy of red, green, refactor
-----
## Readings
### Node.js
* Read [About Node]
* Read/Skim [Node Modules](https://nodejs.org/docs/latest/api/modules.html#modules_modules)
* Skim [Node API](https://nodejs.org/docs/latest-v7.x/api/)
* Skim [About V8]
* Skim [What is NPM]
### Test-Driven Development
* Read [A Gentle Intro to TDD in JS]
* Read only part 1
* We'll be using a different framework than the one used in this article, but most of the concepts and principles are applicable to the framework we'll be using (Jest)
* Read [Getting Started with Jest](https://facebook.github.io/jest/docs/en/getting-started.html)
* Skim [Expect Docs](https://facebook.github.io/jest/docs/en/expect.html)
### ES6
* Read [Just Another Guide to ES6]
* Skim [Node's ES6 Docs]
-----
## Setting up a development workspace
Before people are developers, they often develop many habits they will need to unlearn:
* Use the command line whenever possible. In the long run it will save you a lot of time.
* It is highly important to keep our file system organized.
* If your problem is finding your code, you are in deep trouble!.
* Create a dir structure for keeping track of you class work.
* File naming tips
* Never put space bars in your file names.
* Use `-` or `_` instead. But choose one and stick with it... don't use both!.
* Never use capital letters in your filenames, unless its convention (like README.md).
* Some file systems (like osx) don't keep track of Case and will cause git issues.
``` text
* $HOME/
| - Desktop/
| - Downloads/
| - ...
| - cf-401/
| | - labs/
| | | - lab-01-node-ecosystem
| | | - lab-02-tools-and-context
| | | - ...
| | - lecture-notes/
| | | - class-01-node-ecosystem
| | | - class-02-tools-and-context
| | | - ...
```
## Node.JS
* Node is an asynchronous, event-driven runtime used to build back-end (a.k.a Server Side) JavaScript applications.
* Node uses an "event loop" to work only when events are triggered.
* When Node has no work to be done, Node sleeps.
* Node input and output (I/O) is non-blocking.
* This save developers from having to worry about concurrent programming patterns.
* At a high level, Node is composed of two main components:
* __Javascript API__ :
* Internally, Node uses [libuv](https://github.com/libuv/libuv) for I/O.
* __V8 Javascript engine__
* Node's documentation has a stability index.
* 0 - deprecated - don't use the feature.
* 1 - Experimental - don't use this feature in something you care about.
* 2 - Stable - fine to use.
* 3 - Locked - fine to use.
* *Make sure you read the docs for the version of node you're using.*
## NPM
* NPM is a package manager for installing javascript libraries.
* NPM is composed of the following.
* A registry where all the packages are hosted.
* A search engine where you can find packages.
* A CLI where that helps you interface with the registry.
* A for profit organization.
## CommonJS modules
* Modules are used to break down applications into smaller pieces.
* Why are modules useful?
* The common `<script src=""></script>` pattern used to work with JavaScript loads variables and functions into global scope.
* Relying in the global space is error-prone due to naming conflicts and unexpected side-effects.
* Modules allow us to explicitly define what's loaded in the global scope.
* This plays a huge role in allowing Javascript developers to build large scale applications.
### Using CommonJS modules
* In Node.js, every JavaScript file is a module.
* CommonJS modules work based on 2 main elements:
* The `module.exports` object
* Anything that is assigned to module.exports can be accessed by other modules via the `require` function.
* Everything else will be hidden from other modules.
* The `require` function
* Searches and loads CommonJS modules.
* The require function expects a relative or absolute path to the module being imported.
* Like: `require('./relative/path/to/the/module.js')`.
* CommonJS modules cannot be co-dependent
* If module "A" requires module "B" then "B" can not also require "A".
* *ES6 introduced a different module format that is not compatible with CommonJS modules.*
* *At this time, both ES6 and CommonJS modules are common in JavaScript codebases, so we'll learn both in this course.*
## Testing and TDD
* TDD is a software development process where you write tests before you write code.
* It relies on a very short development cycle.
* It encourages to build small things at a time.
### TDD Process
* This process is called __red, green, refactor__:
* __Red__
* Bake a plan for the features needed to make a program work.
* Choose a feature to implement.
* Write code that tests that features behavior.
* The tests now should fail, because the feature has not been implemented.
* __Green__
* Write the feature itself.
* The tests now should pass, because the feature has been implemented.
* __Refactor__
* Refactor you code to optimize it.
* The tests should still pass, because the behavior should not have changed.
## Jest
* Jest is a testing framework.
* Its job is to facilitate writing and running tests.
* Expect is an assertion library.
* Its job facilitate writing expectations and then throw errors when the expectations are not met.
* When testing with jest, we'll primarily work with 3 functions:
* `descride`
* `test`
* `expect`
<!--links -->
[About Node]: https://nodejs.org/en/about/
[Node's ES6 Docs]: https://nodejs.org/en/docs/es6/
[libuv Docs]: https://github.com/libuv/libuv
[About V8]: https://developers.google.com/v8/
[What is NPM]: https://docs.npmjs.com/getting-started/what-is-npm
[A Gentle Intro to TDD in JS]: http://jrsinclair.com/articles/2016/gentle-introduction-to-javascript-tdd-intro/
[Just Another Guide to ES6]: https://medium.com/sons-of-javascript/javascript-an-introduction-to-es6-1819d0d89a0f#.wb7rj1gin<file_sep>import React from 'react'
import {connect} from 'react-redux'
import {renderIf} from '../../../lib/utils'
import CardForm from '../../card/card-form/card-form'
import CardItem from '../../card/card-item/card-item'
import {cardCreate} from '../../../action/card-actions'
import CategoryForm from '../category-form/category-form'
import {categoryUpdate, categoryDelete} from '../../../action/category-actions'
class CategoryItem extends React.Component {
constructor(props) {
super(props)
this.state = {
category: this.props.category ? this.props.category : {},
editing: false,
}
this.handleEditing = this.handleEditing.bind(this)
}
handleEditing() {
this.setState({editing: !this.state.editing})
}
render() {
return (
<div className="category-item" onDoubleClick={this.handleEditing}>
<h3>{this.state.category.title}</h3>
<p onClick={() => this.props.categoryDelete(this.state.category)}>x</p>
<CategoryForm
buttonText="update"
onComplete={this.props.categoryUpdate}/>
<CardForm
buttonText="create"
categoryId={this.props.category._id}
onComplete={this.props.cardCreate}/>
{renderIf(this.props.cards[this.props.category._id],
this.props.cards[this.props.category._id].map(card => <CardItem key={card._id} card={card}/>)
)}
</div>
)
}
}
const mapStateToProps = state => ({
cards: state.cards,
})
const mapDispatchToProps = (dispatch, getState) => ({
categoryUpdate: category => dispatch(categoryUpdate(category)),
categoryDelete: category => dispatch(categoryDelete(category)),
cardCreate: card => dispatch(cardCreate(card)),
})
export default connect(mapStateToProps, mapDispatchToProps)(CategoryItem)
<file_sep>'use strict';
const net = require('net');
const Client = require('./model/client');
const cmd = require('./lib/cmd');
const ascii = require('./assets/ascii');
const server = module.exports = net.createServer();
const PORT = process.env.PORT || 3000;
let clientPool = [];
server.on('connection', function (socket) {
let client = new Client(socket);
clientPool.push(client);
clientPool.map(c => c.socket.write(`\n\t${client.nick} has joined the chat\n`))
socket.on('data', function (data) {
let msg = cmd(data, clientPool);
socket.emit(msg.command, msg);
});
socket.on('list', function () {
client.socket.write('\n\tConnected Users:\n');
clientPool.map (c => client.socket.write(`\n\t${c.nick}\n`));
});
socket.on('nickname', function(data) {
clientPool.map(c => c.socket.write(`\n\t\t${client.nick} has changed their name to ${data.name}\n`));
client.nick = data.name;
});
socket.on('message', function (data) {
let message = data.said;
clientPool.filter(c => c.user !== client.user)
.map(c => c.socket.write(`\n${client.nick}: ${message}\n`));
client.socket.write(`\nYou (${client.nick}) Said: ${message}\n`);
});
socket.on('dm', function (data) {
let who = clientPool.filter(c => c.nick === data.name);
who[0].socket.write(`\nDirectly From ${client.nick}: ${data.said}\n`);
client.socket.write(`\nDirectly To ${data.name}: ${data.said}\n`);
});
socket.on('jeep', function () {
let jeep = ascii.jeep.split('%');
clientPool.map(c => c.socket.write(`\n${jeep[0]}${client.nick}'s A JEEP\n\n`));
});
socket.on('facepalm', function () {
clientPool.map(c => c.socket.write(`\n${client.nick} is disappointed\n\n${ascii.facepalm}`));
});
socket.on('close', function () {
clientPool = clientPool.filter(c => c.user !== client.user);
clientPool.map(c => c.socket.write(`\n\t${client.nick} has left the chat\n`));
socket.end();
});
socket.on('error', function (data) {
client.socket.write(`\n\t\t!!!\tError\t!!!:\n \t\t${data.err}\n`);
});
});
server.listen(PORT, () => console.log(`listening on ${PORT}`));<file_sep>#!/usr/bin/env node
'use strict';
const start = module.exports = {};
const reader = require('./lib/reader.js');
const bitmap = require('./lib/bitmap.js');
const transform = require('./lib/transform.js');
start.processImage = function(args) {
if(args.length < 5) {
let arg_err = 'Invalid arguments - Expecting: <file-Path> <new-file-name> <transform-method>';
console.log(arg_err);
// process.stdOut.write()
return arg_err;
}
let [imagePath, newName, tm] = args.slice(2);
let imgDir = imagePath.split('/').slice(0, -1).join('/');
let newPath = `${imgDir}/${newName}.bmp`;
if(!transform.hasOwnProperty(tm)) {
let method_error = 'Invalid transform method - Expecting one of: <random> <invert> <reverse> <boostGreen> <boostRed> <boostBlue> <redChannel> <blackWhite> <invert2> <invert3> <invert4>';
console.log(method_error);
return method_error;
}
reader.read(imagePath, (err, fd) => {
if(err) return err;
bitmap.parse(fd, (err, bmp) => {
if(err) err; // return err?
transform[tm](bmp, (err, bmp) => {
if(err) err; // return err?
reader.write(bmp, newPath, err => {
if(err) err; // return err?
});
});
});
});
};
start.processImage(process.argv);
<file_sep>export const PICTURES_ROUTE = '/photos';<file_sep>'use strict'
// Application dependencies
const http = require('http')
const Router = require('./router')
// Router setup
const router = new Router()
require('../route/route-note')(router)
// Application setup
const app = http.createServer(router.route())
// Server controls
const server = module.exports = {}
server.start = (port, cb) => app.listen(port, cb)
server.stop = (cb) => app.close(cb)<file_sep> 36: Asynchronous Actions
===
## Daily Plan
- Notes:
- Anything top of mind?
- What's happening this week; Topics, Schedule, etc...
- Code Review
- Redux Thunk Middleware
- Working with asynchronous actions (functions)
- Lab Preview
## Learning Objectives
* Students will be able to create thunk middleware for redux
* Students will be able to create asynchronous actions
## Readings
* [Async Actions](https://redux.js.org/advanced/async-actions#async-action-creators)
## Redux Thunk
Redux thunk middleware allows you to dispatch function actions as well as function actions. Function actions will have access to `dispatch`, and `getState`. Function actions can trigger async events and dispatch new actions when they are completed. This is often used to make AJAX requests to the a HTTP server.
<file_sep>'use strict';
const bitmap = module.exports = {};
function Bmp(buffer) {
this.allData = buffer;
this.sig = buffer.toString('utf-8', 0, 2);
this.fileSize = buffer.readUInt32LE(2);
this.offset = buffer.readUInt32LE(10);
this.width = buffer.readUInt32LE(18);
this.height = buffer.readUInt32LE(22);
this.colorArray = buffer.slice(54, this.offset);
this.pixelArray = buffer.slice(this.offset);
}
bitmap.parse = function(buffer, callback) {
if(!buffer) return callback(`Error: buffer is ${buffer}`);
let imgBuff;
try {
imgBuff = new Bmp(buffer);
}
catch(e){
imgBuff = {sig:null};
}
if (imgBuff.sig !== 'BM') return callback('Error: is not a Windows format bitmap');
callback(null, imgBuff);
};
<file_sep>'use strict';
let storage = require('../../lib/storage');
let fs = require('fs');
require('jest');
let testData = { title: 'testdatarun', content: 'test data run', _id: 'testdatafile' };
let testUpdate = { title: 'testupdaterun', content: 'test data run', _id: 'testdatafile' }
let testWrong = { title: 'testwrongrun', content: 'test data run', _id: 'invalidid'}
storage.create('Note', testData);
describe('Storage Module', () => {
describe('#create', () => {
it('Should create a file if passed valid arguments', () => {
expect(fs.readdirSync(`${__dirname}/../../data/Note`)).toContain('testdatafile.json');
});
});
describe('#update', () => {
it('Should properly update the file given new information', () => {
return storage.update('Note', testData._id, testUpdate)
.then(file => {
expect(file.title).toBe('testupdaterun');
});
});
it('Should return a validation error if the id in the file does not match the requested file', () => {
return storage.update('Note', testData._id, testWrong)
.catch(err => {
expect(err).toBeInstanceOf(Error);
});
});
});
describe('#fetch', () => {
it('Should return an array of file names', () => {
return storage.fetch('Note')
.then(file => {
expect(Array.isArray(file)).toBeTruthy();
});
});
});
describe('#fetchOne', () => {
it('Should return valid data contained in a specific file', () => {
return storage.fetchOne('Note', testData._id)
.then(file => {
file = JSON.parse(file.toString());
expect(file.content).toBe('test data run');
});
});
});
describe('#destroy', () => {
it('Should successfully delete a file from the storage directory', () => {
return storage.destroy('Note', testData._id)
.then(() => {
return storage.fetch('Note')
.then(files => {
expect(files).not.toContain('testdatafile');
});
});
});
});
});<file_sep>#Lab 31 Redux
in this app a category should contain at least the following properties
id a uuid
timestamp a date from when the category was created
name a string that is the name of the category
budget a number that is the total amount of $ in the category
feel free to add more to your categories
Dashboard Component
should be displayed on the / route
should use react-redux's connect to map state and dispatchable methods to props
should display a CategoryForm for adding categories to the app state
should display a CategoryItem for each category in the app state
CategoryForm Component
should expect an onComplete prop to be a function
that function should be invoked with the CategoryForms state when the form is submitted
should expect a buttonText prop to configure the submit buttons text
should support an optional category prop that will initialize the state of the form
CategoryItem Component
should display the category's name and budget
should display a delete button
onClick the category should be removed from the application state
should display a CategoryForm
onComplete the form should update the component in the application state
## Installing
```
npm install
```
This will install the required depencencies
## Running the application
```
npm run watch
```
This will start the webpack dev server so that the app has a build.
Then you can go to
```
http://localhost:8080/
```
in the web browser. This will display the app.
## Testing
There is no testing at this time.
## Authors
* **<NAME>** - *RND*
## License
This project is licensed under the MIT License -
## Acknowledgments
* <NAME>
* Google
*<file_sep>'use strict'
const debug = require('debug')('http:storage')
// Example setup for promisifying the fs module (any callback based module/api)
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'})
// fs.readFile(path, callback)
// fs.readFileProm(path).then().catch()
// fs.readDir
const storage = module.exports = {}
// memory = {
// 'Notes': {
// '1234.5678.9012': {
// '_id': '1234.5678.9012',
// 'title': '',
// 'content': '',
// },
// },
// 'Categories': {
// ...
// },
// }
storage.create = function(schema, item) {
debug('Created a new thing')
return new Promise((resolve, reject) => {
if(!schema) return reject(new Error('Cannot create a new item; Schema required'))
let jsonData = JSON.stringify(item)
return fs.writeFileProm(`${__dirname}/../data/${schema}/${item._id}.json`, jsonData)
.then(() => resolve(jsonData))
.catch(reject)
})
}
storage.fetchOne = function(schema, itemId) {
return new Promise((resolve, reject) => {
if(!schema) return reject(new Error('400, Cannot find record. Schema required.'))
if(!itemId) return reject(new Error('400, Cannot find record. Item ID required.'))
return fs.readFileProm(`${__dirname}/../data/${schema}/${itemId}.json`)
.then(data => resolve(data.toString()))
.catch(reject)
})
}
storage.fetchAll = function(schema) {
return new Promise((resolve, reject) => {
if(!schema) return reject(new Error('400, Cannot find record. Schema required.'))
return fs.readdirProm(`${__dirname}/../data/${schema}`)
.then(data => data.map(id => id.split('.')[0]))
.then(ids => resolve(ids))
.catch(reject)
})
}
storage.update = function(schema, itemId, item) {
return new Promise((resolve, reject) => {
if(!schema) return reject(new Error('Cannot update. Schema required.'))
if(!itemId) return reject(new Error('Cannot update. Item ID required.'))
if(!item) return reject(new Error('Cannot update. Item required.'))
if(item._id !== itemId) return reject(new Error('Cannot update. Invalid ID'))
return fs.readFileProm(`${__dirname}/../data/${schema}/${item._id}.json`)
.then(data => data.toString())
.then(json => JSON.parse(json))
.then(oldData => {
return {
title: item.title || oldData.title,
content: item.content || oldData.content,
_id: oldData._id,
}
})
.then(JSON.stringify)
.then(json => fs.writeFileProm(`${__dirname}/../data/${schema}/${item._id}.json`, json))
.then(resolve)
.catch(reject)
})
}
storage.delete = function(schema, itemId) {
}<file_sep>'use strict'
const superagent = require('superagent')
const server = require('../../lib/server')
const Track = require('../../model/track')
require('jest')
describe('POST /api/v1/track', function() {
beforeAll(() => this.mockTrack = {title: 'shark in the dark', artist: 'slug'})
beforeAll(() => server.start())
afterAll(() => server.stop())
afterAll(() => Promise.all([Track.remove()]))
describe('valid requests', () => {
beforeAll(() => {
return superagent.post(`:${process.env.PORT}/api/v1/track`)
.send(this.mockTrack)
.then(res => this.response = res)
})
it('should return a status code of 201 CREATED', () => {
expect(this.response.status).toBe(201)
})
})
describe('invalid request', () => {
})
})<file_sep>'use strict'
// function concat(num, str) {
// return new Promise((resolve, reject) => {
// if(!num || !str) return reject(new Error('there be a problem!'))
// return resolve(num + str)
// })
// }
// console.log(concat(1, 'hello'))
const fs = require('fs')
let firstRead = fs.readFile(`${__dirname}/promise.js`, (err, data) => {
return new Promise((resolve, reject) => {
if(err) return reject(new Error('barf'))
return resolve(data.toString())
})
})
firstRead
.then()
.then()
.then()
.then()
.then()
.then()
.catch()
fs.readFile(`${__dirname}/promise.js`, (err, data) => {
if(err) throw new Error('barf')
console.log(data.toString())
})<file_sep>'use strict';
class TreeNode{
constructor(value,left=null,right=null){
this.value = value;
this.left = left;
this.right = right;
}
}
class BinaryTree{
constructor(root=null){
this.root = root;
}
inOrderTraversal(){
if(!this.root)
return null;
this._inOrderTraversal(this.root);
}
_inOrderTraversal(root){
// vinicio - this is a base case
if(root === null)
return null;
// visit left
this._inOrderTraversal(root.left);
// visit root
console.log(`Visiting ${root.value}`);
// visit right
this._inOrderTraversal(root.right);
}
}
let one = new TreeNode(1);
let two = new TreeNode(2);
let three = new TreeNode(3);
let four = new TreeNode(4);
let five = new TreeNode(5);
let six = new TreeNode(6);
let seven = new TreeNode(7);
let eight = new TreeNode(8);
let nine = new TreeNode(9);
let binaryTree = new BinaryTree();
binaryTree.root = one;
one.left = two;
one.right = three;
two.left = six;
three.left = four;
three.right = five;
six.right = seven;
seven.left = eight;
seven.right = nine;
binaryTree.inOrderTraversal();
<file_sep>'use strict';
// return values => {
// command: 'something',
// ... other key:values,
// }
module.exports = (data, connected) => {
let message = data.toString().trim().split(' ');
console.log('message', message)
if (message[0][0] === '@') {
switch (message[0]) {
case '@quit':
return {command: 'close'};
case '@list':
return {command: 'list'};
case '@nickname':
if (connected.filter(c => c.nick === message[1]).length) return {command: 'error', err: 'Nickname Already In Use'};
return message[2]? {command: 'error', err: '@nickname requires a name without spaces'} : {command: 'nickname', name: message[1]};
case '@dm':
if (connected.filter(c => c.nick === message[1]).length) return {command: 'dm', name: message[1], said: message.slice(2).join(' ')};
else return {command: 'error', err: 'Requested user does not exist'};
case '@jeep':
return message[1]? {command: 'error', err: 'Jeeps cannot talk'} : {command: 'jeep'};
case '@facepalm':
return message[1]? {command: 'error', err: 'Are you facepalming or talking?'} : {command: 'facepalm'};
default:
return {command: 'error', err: 'Command does not exist'};
}
} else return {command: 'message', said: message.join(' ')};
};<file_sep> 44: Frontend Deployment
===
## Learning Objectives
* Students will learn about Content Distribution Networks (CDN)
* Students will learn to set up AWS Cloudfront to host their static assets
## Readingsa
* Read [AWS CloudFront](https://aws.amazon.com/cloudfront/)
## Transport Layer Security (TLS / SSL)
The Transport Layer Security(TLS) was previously the Secure Socket Layer(SSL). TLS is a crypographic protocol that provides secure communications over a computer network. TLS enables communications between computers to be private. It does this by using asymmetric cyphers to encrypt data before sending it across the network.
When a client and server make a TLS connection they negotiate a stateful connection using the following handshake.
0. The client connects to the TLS enabled server and provides a list of supported ciphers
0. The server picks a cipher that it supports and notifies the client
0. The server sends its public encryption key or a digital certificate
0. The client confirms the validity digital certificate
0. The client generates and sends sessions keys used for the connection
#### Asymmetric Cypher
An asymmetric cypher is a cryptographic algorithm that uses separate keys for encrypting and decrypting data. These keys are often referred to as public and private keys. The public key is used to encrypt the data and the private key is used to decrypt the data. An analogy for this might be if a store owner had a two types of keys keys to her store several for locking it up (copies of a public key), and one for opening it (a private key). All her employees could have access to the key that locks the store, but once the store was locked she would be the only one that could open it.
#### Digital Certificate
A digital certificate is an document used to prove the ownership of a public key. The certificate contains the servers name, the trusted certificate authority, and the public encryption key. A certification authority is an entity that both issues and verifies digital certificates.
## HTTPS
HTTPS is an HTTP connection encrypted by TLS or SSL. HTTPS is supported by browsers and is used to authenticate the visited website and protect the privacy/integrity of the exchanged data.
## Content Delivery Network (CDN)
A CDN is a geographically distributed network of proxy servers and data centers. Its job is to distribute static assets to spatially relative end users and provide high availability and performance.
<file_sep># 14 Mongo Populate
This app creates, reads, updates, and deletes files using MongoDB as it's database and Mongoose as middleware.
---
## Intalling and Getting Started
To use this app, for and git clone this repository to your local computer. Navigate to the `lab-melanie` directory and enter `npm install` in your command line, this will install all necessary dependencies.
Either use the Postman app or Httpie to have the ability to create and modify bikes. The following examples will be demonstrated with Httpie.
#### Create a Rider
In your terminal type:
```
http POST :3000/api/v1/rider name=<name>
```
Be sure to use single quotes if the descriptions contain more than one word.
#### Get a Rider
In your terminal type:
```
http GET :3000/api/v1/rider
```
This will return all riders and their IDs, which will be needed to create a bicycle.
#### Create a Bicycle
In your terminal type:
```
http POST :3000/api/v1/bike year=<year> color=<color> make=<make> category=<category> rider=<rider ID (see above)>
```
Be sure to use single quotes if the descriptions contain more than one word.
If your filepath is incorrect, you will recieve an error message, otherwise you will see a status code of 201.
#### Get a Bike (or all bikes)
To get a specific bike, type in your command line:
```
http GET :3000/api/v1/bike/<bike id>
```
This will return the information about the bicycle and it's rider.
To get all bikes:
```
http GET :3000/api/v1/bike
```
This will return a list of all bike ids.
#### Update a Rider
In your command line, type:
```
http PUT :3000/api/v1/rider/<rider ID> name=<new name>
```
#### Update a Bike
In your command line, type:
```
http PUT :3000/api/v1/bike/<bike id> year=<new year> color=<new color> make=<new make> category=<new category>
```
Just as creating a bike, be sure to use single quotes if the descriptions are longer than one word.
#### Delete a Rider
In your command line, type:
```http DELETE :3000/api/v1/rider/<rider ID>
```
#### Delete a Bike
In your command line, type:
```
http DELETE :3000/api/v1/bike/<bike id>
```
This removes the bike from the database and it's relationship to the rider.
---
## Data Structures
### Route-Rider Module
This contains five methods that routes requests and responses from storage:
* `.post` - sends info from the http request to mongo to create a rider and sends a response back to the viewer
* `.get` - this has two methods, one that uses a specific id of a rider to read the file and send the response back to the viewer, the other only needs the schema (in this case `rider`) and returns the response from mongo as a list of rider ids
* `.put` - takes info from the http request and updates a rider in storage, then sends a response back to the viewer
* `.delete` - takes in the http request with a specific rider id, sends it to mongo to `remove` the file, then sends a status message back to the viewer
### Route-Bike Module
This contains five methods that routes requests and responses from storage:
* `.post` - sends info from the http request to mongo to create a bike and sends a response back to the viewer
* `.get` - this has two methods, one that uses a specific id of a bike to read the file and send the response back to the viewer, the other only needs the schema (in this case `bike`) and returns the response from mongo as a list of bike ids
* `.put` - takes info from the http request and updates a bike in storage, then sends a response back to the viewer
* `.delete` - takes in the http request with a specific bike id, sends it to mongo to `remove` the file and it's relationship to a rider, then sends a status message back to the viewer
---
## Tests
The test directory is separated into four subdirectories:
`integration-bike` contains files to test each http method, `POST`, `GET`, `PUT`, `DELETE`.
`integration-rider` contains files to test each http method, `POST`, `GET`, `PUT`, `DELETE`.
`lib` contains the jest port configuration
`unit-tests` contains files to test modules that the router and server rely on for requests and responses including:
* `bike` - builds a bike object
* `rider` - builds a rider object
* `error-handler` - customizes error messages and returns the corresponding response<file_sep>'use strict';
const server = require('../../lib/server.js');
const superagent = require('superagent');
const mock = require('../lib/mock.js');
require('jest');
describe('GET', function() {
beforeAll(server.start);
afterAll(server.stop);
afterAll(mock.rider.removeAll);
afterAll(mock.bike.removeAll);
describe('Valid req/res', () => {
beforeAll(() => {
return mock.rider.createMany(5)
.then(res => this.riderData = res);
});
it('should return a status 200 given a valid ID', () => {
return superagent.get(`:4000/api/v1/rider/${this.riderData[0]._id}`)
.then(res => expect(res.status).toEqual(200));
});
it('should return a rider from the database', () => {
return superagent.get(`:4000/api/v1/rider/${this.riderData[0]._id}`)
.then(res => expect(res.body.name).toBe(this.riderData[0].name));
});
});
describe('Invalid req/res', () => {
it('should return a status code 400 without schema', () => {
return superagent.get(':4000/api/v1/bike')
.send()
.catch(err => {
expect(err.status).toBe(404);
});
});
it('should return a 404 given an incorrect path', () => {
return superagent.get(':4000/api/v1/doesnotexist')
.send({title: '', content: ''})
.catch(err => {
expect(err.status).toBe(404);
});
});
});
});<file_sep>// import './styles/main.scss'
import React from 'react'
import ReactDom from 'react-dom'
import superagent from 'superagent'
const API_URL = 'https://pokeapi.co/api/v2'
class SearchForm extends React.Component {
constructor(props) {
super(props)
this.state = {
val: '',
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(e) {
this.setState({val: e.target.value})
}
handleSubmit(e) {
e.preventDefault()
// console.log(this.props.get_set_app)
this.props.update_state(this.state.val)
}
render() {
return (
<form
className="search-form"
onSubmit={this.handleSubmit}>
<input
type="text"
name="pokemon-name"
value={this.state.val}
onChange={this.handleChange}
placeholder="Bulbasaur"/>
<button type="submit">Search</button>
{/* <Navbar get_set_app={this.props.get_set_app}/> */}
</form>
)
}
}
class Results extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div className="results">
{this.props.pokemon ?
<section className="pokemon-data">
{console.log(this.props.pokemon)}
<h2>{this.props.pokemon.name}</h2>
<img
src={this.props.pokemon.sprites.front_default}
alt={this.props.pokemon.name}/>
</section>
:
undefined
}
{this.props.error ?
<section className="pokemon-error">
<h2>You broke it.</h2>
</section>
:
undefined
}
</div>
)
}
}
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
pokemon: null,
searchError: null,
}
this.searchApi = this.searchApi.bind(this)
this.updateState = this.updateState.bind(this)
}
updateState(name) {
this.searchApi(name)
.then(res => this.setState({pokemon: res.body, searchError: null}))
.catch(err => this.setState({pokemon: null, searchError: err}))
}
searchApi(name) {
return superagent.get(`${API_URL}/pokemon/${name}`)
}
render() {
return (
<div className="application">
<SearchForm update_state={this.updateState}/>
<Results pokemon={this.state.pokemon} error={this.state.searchError}/>
</div>
)
}
}
ReactDom.render(<App />, document.getElementById('root'))
<file_sep>'use strict'
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'})
const storage = module.exports = {}
storage.create = (schema, item) => {
let json = JSON.stringify(item)
return fs.writeFileProm(`${__dirname}/../data/${schema}/${item._id}.json`, json)
.then(() => item)
}
storage.fetchOne = (schema, itemId) =>
fs.readFileProm(`${__dirname}/../data/${schema}/${itemId}.json`)
storage.fetchAll = (schema) => {
}
storage.update = (schema, itemId, item) => {
}
storage.destroy = (schema, itemId) => {
}
<file_sep>### TCP Chat Server Lab
# Cmd Module
1. Parser is a function that takes in a buffer of data, turns it into a string and parses commands from the front of the string by seperating each "word" of the string and checking the first for an "@" command, it then verifies a valid command was given and returns an object with the information required for the chosen command or message type.
This function is O(n) on average case operation.
It requires two inputs, a valid buffer of data and an array of currently connected clients.
# Client Module
1. Client is a constructor function that takes in a socket provided by server connection and instantiates a Client object with a randomized uuid value as a nickname, a random user number, and an assigned socket.
This function is O(1) on average case operation.
It requires a single input, a valid socket.
# Server Module
The Server entry point file, this file handles all events emitted by processes. These events include the following:
1. Connection: On connection the server assigns a socket to the connection and calls for new client creation on that socket as well as assigns listeners for available commands.
2. Data: On submission of data from any connected client this sends that data into the command parser module and emits an event based on that data sending the data along to that event.
3. List: When the data event emits an @list command this creates a list of connected users for the client who executed it.
4. Nickname: When the data event emits an @nickname command this changes the clients nickname based on the name passed after the command.
5. Message: When the data event emits a message event because no @ command was used this passes the entire block of information provided as a message to the server.
6. Direct Message: When the data event emits an @dm command this targets the 2nd word of the message as a name of a user and attempts to send rest of the message to them.
7. Close: When the data event emits an @quit command it closes the connection of the requesting client.
8. Error: This event is emitted if the requested command is invalid in some way, it passes a message back to the Client saying what needs to be corrected.
9. Jeep & Facepalm: These are easter egg events emitted when @jeep or @facepalm are used as a command with nothing following it.<file_sep>'use strict'
const uuid = require('uuid/v4')
const debug = require('debug')('http:note-constructor')
module.exports = function(title, content) {
this.title = title
this.content = content
this._id = uuid()
debug(`Created a note: ${this}`)
}<file_sep>'use strict';
const Rider = require('../../model/rider.js');
require('jest');
describe('Rider Module', function() {
let newRider = new Rider();
describe('Rider schema', () => {
it('should create a object', () => {
expect(newRider).toBeInstanceOf(Object);
});
});
});<file_sep> 38: File Reader API
====
## Daily Plan
- Notes:
- Anything top of mind
- Reminder: 1215p Guest Lectures in the Event Space
- Weds: <NAME>: TypeScript
- Thurs: <NAME>: React Native
- Code Review
- Passing of the Projector Ceremonies!

- File Reader API
- Adding profiles and settings to your users!
- Lab Preview
## Learning Objectives
* Students will learn to use the `FileReader` API to preview image files
## Readings
* Read [Using files in web applications](https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications)
* Skim [FileReader.readAsDataURL docs](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL)
## Previewing images
Using the HTML5 FileReader API, browser applications can now ask users to read local files, and then read the contents of those files. Input tags of type file can retrieve files from the user. Those files can then be loaded through the a `FileReader`. Once a FileReader has loaded the contents of a file it can then be processed as an ArrayBuffer, BinaryString, DataURL, or Text. After a user selects a photo it can be previewed, by loading the contents using a FileReader and then passing a DataURL into an `<img>` tag.
<file_sep>'use strict'
const HashTable = module.exports = function(size=1024) {
this.size = size
this.memory = [...Array(this.size)] // => [SLL, SLL, SLL]
}
HashTable.prototype.hashKey = function(key) {
let hash = key.split('').reduce((a, b) => a + b.charCodeAt(0), 0) % this.size
return hash
}
HashTable.prototype.set = function(key, value) {
// Implement the collision detection and handle that through a SLL
// Stretch goal => Implement with buckets as binary trees
this.memory[this.hashKey(key)] = value
}
HashTable.prototype.get = function(key) {
// Implement the lookup for your buckets and their respective data structures
return this.memory[this.hashKey(key)]
}
HashTable.prototype.remove = function(key) {
let address = this.hashKey(key)
return this.memory[address] ? delete this.memory[address] : new Error('Invalid Key.')
}
<file_sep>'use strict'
// Application Dependencies
const cors = require('cors')
const express = require('express')
const mongoose = require('mongoose')
const debug = require('debug')('http:server')
const errorHandler = require('./error-handler')
// Application Setup
const PORT = process.env.PORT
const router = express.Router()
const app = express()
const MONGODB_URI = process.env.MONGODB_URI
// Middleware
require('../route/route-track')(router)
require('../route/route-album')(router)
app.use(cors())
app.use('/api/v1', router)
// 404 Error Handler
app.all('/*', (req, res) => errorHandler(new Error('PATH ERROR. Route does not exist'), res))
// Server Controls
let server = module.exports = {}
server.start = () => {
return new Promise((resolve, reject) => {
if(server.isOn) return reject('shit hit the fan')
server.http = app.listen(PORT, () => {
console.log('server up', PORT)
mongoose.connect(MONGODB_URI)
server.isOn = true
return resolve(server)
})
})
}
server.stop = () => {
return new Promise((resolve, reject) => {
if(!server.isOn) return reject()
server.http.close(() => {
console.log('server down')
mongoose.disconnect()
server.isOn = false
return resolve()
})
})
}
<file_sep>'use strict'
const Note = require('../model/note')
const storage = require('../lib/storage')
const bodyParser = require('body-parser').json()
const errorHandler = require('../lib/error-handler')
module.exports = function(router) {
router.post('/note', bodyParser, (req, res) => {
new Note(req.body.title, req.body.content)
.then(note => storage.create('note', note))
.then(item => res.status(201).json(item))
.catch(err => errorHandler(err, res))
})
router.get('/note/:_id', (req, res) => {
storage.fetchOne('note', req.params._id)
.then(buffer => buffer.toString())
.then(json => JSON.parse(json))
.then(note => res.status(200).json(note))
.catch(err => errorHandler(err, res))
})
// router.get()
// router.put()
// router.delete()
}<file_sep>'use strict';
class TreeNode{
constructor(value,left=null,right=null){
this.value = value;
this.left = left;
this.right = right;
}
}
class BST{
constructor(root=null){
this.root = root;
}
insert(nodeToInsert){
if(this.root === null)
this.root = nodeToInsert;
else
this._insert(this.root,nodeToInsert);
}
_insert(root,nodeToInsert){
if(nodeToInsert.value < root.value){
// Vinicio - going left
if(!root.left)
root.left = nodeToInsert;
else
this._insert(root.left,nodeToInsert);
} else {
// Vinicio - going right
if(!root.right)
root.right = nodeToInsert;
else
this._insert(root.right,nodeToInsert);
}
}
find(value){
return this._find(this.root,value);
}
_find(root,value){
if(!root)
return null;
else if(root.value === value)
return root;
else if(root.value < value)
return this._find(root.right,value);
else
return this._find(root.left,value);
}
}
let bst = new BST();
bst.insert(new TreeNode(5));
bst.insert(new TreeNode(2));
bst.insert(new TreeNode(8));
bst.insert(new TreeNode(16));
console.log(bst.find(8));
console.log(bst.find(16));
console.log(bst.find(100));
<file_sep>
 21: Backend Project
===
# Day one milestone objectives
* Work as a team to design the models for you application on a whiteboard
* You should have at least two more models than your team member count
* Number your models in the order that they need to be built
* Choose the two most important non auth models to be your MVP
* Work as a team to designe the routes for you application on a whiteboard
* Setup travis-ci continuous integration and heroku continuous deployment
* Write the auth layer of your application
# Day two milestone objectives
* Build your two MVP models with routes and 90% code coverage
* If you achieve 90% code coverage for routes of a model start on a streach model
# Day three milestone objectives
* Build your two stretch models with routes and 90% code coverage
* If you achieve 90% code coverage for routes of a model start on another streach model
# Day four milestone objectives
* Finsh any loose ends
* Write doumentation for all features of your application
* Pratice your presintation<file_sep>'use strict'
// const events = require('events')
// const EE = events.EventEmitter
// const ee = new EE()
const EE = require('events').EventEmitter
const ee = new EE()
// Defines a custom event and listener
ee.on('myEvent', function () {
console.log('I ran "myEvent"')
})
// Manually triggers the event, which runs the defined callback
ee.emit('myEvent')
// My event now needs to receive data as arguments when emitted
ee.on('dataEvent', function (data) {
console.log('Received data', data)
})
function runEvents() {
ee.emit('myEvent')
ee.emit('dataEvent', { data: 'data to send to the callback' })
}
runEvents()<file_sep> 19: Continuos Integration and Deployment
===
## Daily Plan
- Notes:
- Anything top of mind?
- Code Review _How did tests go?_
- Continuous Integration _w/Travis-CI_
- Heroku Deployment _Lets deploy your RESTful APIs_
- Lab Preview
## Learning Objectives
* Students will be able to deploy their application on Heroku with a continuos delivery pipeline
* Students will be able to configure TravisCI to run their tests on all pushes to GitHub
* Students will learn about Continuous Integration
* Students will learn about Continuous Delivery
## Resources
* Read [Deploying NodeJS Apps on Heroku](https://devcenter.heroku.com/articles/deploying-nodejs)
* Read [Getting started with NodeJS on TravisCI](https://docs.travis-ci.com/user/languages/javascript-with-nodejs)
## Continuous Integration
Continuous Integration (CI) is the process of regularly merging individually developed features of code into a shared repository as frequently as they are made. In the most basic setup a team could simply use Git to merge code into a master branch. However more advanced CI patterns can be developed, that automate static analysis (linting), running unit and integration tests, testing platform support, enforcing code reviews, and much more.
## Continuous Delivery
Continuous Delivery (CD) is the process of deploying software in short cycles, by ensuring that software can be deployed at any time. CD pairs very wil with advanced CI setups that help ensure the core product is always a stable code base.
## Heroku Deployment
- enable your repository to work with TravisCI
- *note: you may have to sync your account for TravisCI to show the repo as an option*
- add your environment variables to TravisCI by clicking on the **Settings** option in the **More options** drop-down
- log into the Heroku dashboard
- create a new app
- create a staging app *(ex: cfgram-staging)*
- click on the **Resources** tab
- in the **Add-ons** section, type *mongo* and choose the mLab option and associated free price plan
- *note: you will need to provide a credit card with Heroku to do this - even with the free option*
- click on the **Settings** tab
- click on the **Reveal Config Vars** button and add your environment variables
- *note: you do not need to add the MONGODB_URI variable as this was added by Heroku when you provisioned the DB - there's also no need to add a PORT, Heroku will handle this for you*
- click on the **Deploy** tab
- create a new pipeline called **staging**
- click the button to connect your application to GitHub
- in the **Automatic deploys** field, choose **staging** as your deployment branch *(you'll need to already have a `staging` branch pushed to GitHub)* and click the button to **Enable Automatic Deploys**
- **repeat** the following steps to create a production pipeline
- *note: be sure to name the application "myapp-production", add it to a production pipeline, and enable automatic deploys to deploy to your `master` branch*<file_sep>'use strict'
require('dotenv').config()
const debug = require('debug')('http:index')
require('./lib/server').start()
<file_sep>import './styles/main.scss'
import React from 'react'
import faker from 'faker'
// const {say, list} = require('cowsay-browser')
// const say = require('cowsay-browser').say
// const list = require('cowsay-browser').list
import cowsay from 'cowsay-browser'
import ReactDom from 'react-dom'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
cows: [],
current: '',
content: cowsay.say({text: 'click the button...'}),
}
// cowsay.list((err, cows) => {
// let current = cows[0]
// this.setState({ cows, current })
// })
this.handleClick = this.handleClick.bind(this)
}
componentWillMount() {
cowsay.list((err, cows) => {
let current = cows[0]
this.setState({cows, current})
})
}
handleClick(e) {
let current = e.target.value || this.state.current
let text = faker.random.words(4)
this.setState({current, content: cowsay.say({text, f: current})})
}
render() {
return (
<div className="application">
{console.log('hello')}
<h1>Welcome to cowville!</h1>
<select onChange={this.handleClick}>
{this.state.cows.map((cow, i) => {
return <option value={cow} key={i}>{cow}</option>
})}
</select>
<button onClick={this.handleClick}>click for {this.state.current}</button>
<pre>
{this.state.content}
</pre>
</div>
)
}
}
ReactDom.render(<App />, document.getElementById('root'))
<file_sep>'use strict'
const events = require('./lib/events')
const mod = require('./lib/module')
let eventIWantToRunAnytimeIWant = mod(events)
eventIWantToRunAnytimeIWant('data from somewhere else, Tim.')
<file_sep> 11: ExpressJS
===
## Daily Plan
- Notes:
- Anything top of mind?
- Week ahead, week behind
- quick note about last week's workload
- Code Review?
- Express Framework
- API Data Flow
- Lab Preview
## Learning Objectives
* Students will learn about ExpressJS
* Students will be able to create RESTful HTTP servers through the use of Express
## Resources
* Skim [express api docs](http://expressjs.com/en/4x/api.html)
* Read [express routing](http://expressjs.com/en/guide/routing.html)
## Express
ExpressJS is a lightweight framework for building web servers. ExpressJS extends the NodeJS `http` module with a minimal feature set that enables developers to build quickly build powerful web applications. Express features include routing with url params, error handling, a static server, cookie and link helpers, convenience methods for sending json and jsonp, location and redirect management, request parsing, server side rendering, and a framework for creating middleware to extend express.
<file_sep>'use strict';
const fs = require('fs');
const reader = module.exports = {};
reader.read = function(path, callback) {
fs.readFile(path, (err, fd) => {
if(err) {
console.error(err);
return callback(err);
}
return callback(null, fd);
});
};
reader.write = function(bmpObj, filePath, callback) {
fs.writeFile(filePath, bmpObj.allData, err => {
if(err) return callback(err);
console.log(`File created: ${filePath}`);
return callback(null);
});
};
<file_sep> 42: OAuth Continued
===
## Learning Objectives
* Students will learn Front End Oauth Workflow
## Readings
* [Google OAuth frontend](https://developers.google.com/identity/protocols/OAuth2UserAgent)
<file_sep># 04 Bitmap Project
This is an application that offers a selection of transformations to apply to a bitmap image.
## dazzle! - a command line bitmap transformer
---
The dazzle command line utility allows the user to transform a bitmap image using any of the nine transform methods. A new copy of the image is created with the supplied name.
### dazzle takes three arguments
- <bitmap_file_path> the path to a bitmap image to transform
- <new-file-name> the name for the new bitmap image without an extension
- <transform-method> name of the transform method
```
dazzle bitmap_file_path file new_file_name file transform_method
```
### Installation
This is a node js project that can be installed and run as a command line tool.
1. Clone or fork this repository.
2. In terminal, navigate to the root of the project.
3. Enter
`npm install`
4. Enter
`npm link`
5. You are now ready to use dazzle!
---
### Transform Methods:
- `random` Randomize the color palette of the image
- `reverse` Description of -a flag
- `boostGreen` Sets the green values to 255
- `boostRed` Sets the red values to 255
- `boostBlue` Sets the blue values to 255
- `redChannel` Creates a gray scale image based on the value of the red value
- `blackWhite` Creates a gray scale image based on the average value of the rgb values
- `invert` Inverts the rgb values
- `invert2` Inverts every fourth bit in the color palette
- `invert3` Inverts every third bit in the color palette
- `invert4` Inverts every other bit in the color palette
### Example
```
dazzle ~/users/home/pictures/test.bmp dazed boostGreen
```
#### Dazzle man page
```
man dazzle
```
---
### Reader Module
The reader module requires a file system module and contains two functions. The read and write function takes in an arity of two, the file path and callback. The read method reads the image file past in and passes the information to the bitmap module. The write method takes the transformed object representing the image and writes a new file based on the path provided in the argument. The callback in the read file sends the file data of the original image to the bitmap module.
##### Reader Functions:
* `read` - takes the file data of the image from the file path given and the callback sends the information to the bitmap module.
* `write` - takes the file data of the new image from the bitmap module and creates a new file.
---
### Transform Module
The transform module contains functions to change the color array or pixel array in a bitmap image. All transform module functions have an arity of two, each taking in the object representing a bitmap image (created from the bitmap module) and a callback to send the transformed file data back to the reader module.
##### Transform Functions:
* `random` - takes each bit in the color array and assigns a random number (between 0 and 255) to the RGBa values. The new image file created will be different each time this function is called.
* `invert` - alters the color array to the opposite RGBa value (ex: 255 becomes 0).
* `reverse` - alters the pixel array and flips the image both vertically and horizontally.
* `boostGreen` - alters all green values in the color array to 255.
* `boostRed` - alters all red values in the color array to 255.
* `boostBlue` - alters all blue values in the color array to 255.
* `redChannel` - alters each green and blue value in the color array to equal the red value. This returns a grayscale image based on the red channel.
* `blackWhite` - alters each red green and blue value in the color array to the average of all three and returns a grayscale image.
* `invert2` - alters every 4th bit in the color array to it's opposite value.
* `invert3` - alters every 3rd bit in the color array to it's opposite value.
* `invert4` - alters every other bit in the color array to it's opposite value.
## TESTING
---
### index.test.js
- Test that the app wil not run without arguments.
- Test that the app does not run with less than two arguments.
- Test that the app wil not run with out a valid transform method.
### reader.test.js
#### reader.read
- Test that the reader function can read a file.
- Test that the reader function will send an error message if the file does not exist.
- Test the the reader function will send an error if the file path is missing.
#### reader.write
- Test that the write function can create a file.
- Test that the write function can write to a file.
- Test that the write function can return an error message if the directory does not exist
### bitmap.test.js
- Test that the object will return an error if the buffer is null.
- Test that the constructor can create an object from a buffer
- Test that the constructor will return an error message if the buffer is not from a bit map.
### transform.test.js
#### transform.random
- Test that the object passed to the transform was created by the Bmp object constructor.
- Test that the object has the pixelArray and colorArray properties.
- Test that the pixelArray and colorArray properties have values.
- Test that the colorArray no longer matches the original
#### transform.reverse
- Test that the object passed to the transform was created by the Bmp object constructor.
- Test that the object has the pixelArray and colorArray properties.
- Test that the pixelArray and colorArray properties have values.
- Test the the pixelArray is the reverse of the original
#### transform.boostGreen
- Test that the object passed to the transform was created by the Bmp object constructor.
- Test that the object has the pixelArray and colorArray properties.
- Test that the pixelArray and colorArray properties have values.
- Test that all the green values are 255
#### transform.boostRed
- Test that the object passed to the transform was created by the Bmp object constructor.
- Test that the object has the pixelArray and colorArray properties.
- Test that the pixelArray and colorArray properties have values.
- Test that all the red values are 255
#### transform.boostBlue
- Test that the object passed to the transform was created by the Bmp object constructor.
- Test that the object has the pixelArray and colorArray properties.
- Test that the pixelArray and colorArray properties have values.
- Test that all the blue values are 255
#### transform.redChannel
- Test that the object passed to the transform was created by the Bmp object constructor.
- Test that the object has the pixelArray and colorArray properties.
- Test that the pixelArray and colorArray properties have values.
- Test that all the values are equal to the red value
#### transform.blackWhite
- Test that the object passed to the transform was created by the Bmp object constructor.
- Test that the object has the pixelArray and colorArray properties.
- Test that the pixelArray and colorArray properties have values.
- Test that the values are the average of all the values
#### transform.invert
- Test that the object passed to the transform was created by the Bmp object constructor.
- Test that the object has the pixelArray and colorArray properties.
- Test that the pixelArray and colorArray properties have values.
- Test that the values of each color are the inverse of the original
#### transform.invert2
- Test that the object passed to the transform was created by the Bmp object constructor.
- Test that the object has the pixelArray and colorArray properties.
- Test that the pixelArray and colorArray properties have values.
- Test that every 4th value is the inverse of the original
#### transform.invert3
- Test that the object passed to the transform was created by the Bmp object constructor.
- Test that the object has the pixelArray and colorArray properties.
- Test that the pixelArray and colorArray properties have values.
- Test that every 3th value is the inverse of the original
#### transform.invert4
- Test that the object passed to the transform was created by the Bmp object constructor.
- Test that the object has the pixelArray and colorArray properties.
- Test that the pixelArray and colorArray properties have values.
- Test that every other value is the inverse of the original
<file_sep>'use strict'
const Album = require('./album')
const mongoose = require('mongoose')
const debug = require('debug')('http:model-track')
const Track = mongoose.Schema({
"speechiness": {type: Number},
"key": {type: Number},
"time_signature": {type: Number},
"liveness": {type: Number},
"loudness": {type: Number},
"duration_ms": {type: Number},
"danceability": {type: Number},
"duration": {type: Number},
"valence": {type: Number},
"acousticness": {type: Number},
"spotify_id": {type: String},
"volume_number": {type: Number},
"energy": {type: Number},
"tempo": {type: Number},
"instrumentalness": {type: Number},
"mode": {type: Number},
"number": {type: Number},
"artist": {type: String, required: true},
"title": {type: String, required: true},
"album": {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'album'},
}, { timestamps: true })
Track.pre('save', function(next) {
Album.findById(this.album)
.then(album => {
// album.tracks = [...new Set(album.tracks).add(this._id)]
let trackIdSet = new Set(album.tracks)
trackIdSet.add(this._id)
album.tracks = [...trackIdSet]
})
.then(next)
.catch(() => next(new Error('Validation Error. Failed to create track because Album does not exist')))
})
Track.post('remove', function(doc, next) {
Album.findById(doc.album)
.then(album => {
album.tracks = album.tracks.filter(track => track._id !== doc._id)
return album.save()
})
.then(next)
.catch(next)
})
module.exports = mongoose.model('track', Track)<file_sep>import {combineReducers} from 'redux'
import albums from './album'
import tracks from './track'
export default combineReducers({albums, tracks})
<file_sep>import React from 'react'
import Adapter from 'enzyme-adapter-react-16'
import {configure, shallow, mount} from 'enzyme'
import CategoryForm from '../component/category/category-form/category-form'
require('jest')
configure({adapter: new Adapter()})
describe('<CategoryForm />', function() {
describe('Shallow Mounting', function() {
beforeAll(() => {
let wrapper = shallow(<CategoryForm />)
this.wrapper = wrapper
})
afterAll(() => this.wrapper.unmount())
it('should render a category form component', () => {
console.log(this.wrapper.html())
expect(this.wrapper.length).toBe(1)
expect(this.wrapper.find('.category-form').length).toBe(1)
})
it('should have a default state object with a title property assigned an empty string', () => {
expect(this.wrapper.state().title).toEqual('')
})
it('should change the state object when form input is provided', () => {
let event = {target: { name: 'title', value: 'hello' }}
this.wrapper.find('.category-form input').simulate('change', event)
expect(this.wrapper.state().title).toEqual('hello')
// wrapper.instance().handleChange(event)
})
})
describe('Full Mounting', function() {
beforeAll(() => {
this.wrapper = mount(<CategoryForm />)
this.wrapper.setProps({onComplete: jest.fn()})
})
afterAll(() => this.wrapper.unmount())
it('should reset the state.title value to empty string on form submit', () => {
this.wrapper.setState({title: 'goodbye world'})
expect(this.wrapper.state().title).toEqual('goodbye world')
this.wrapper.simulate('submit', {preventDefault: () => {}})
expect(this.wrapper.state().title).toEqual('')
})
it('should have called onComplete in the previous assertion', () => {
expect(this.wrapper.props().onComplete).toHaveBeenCalled()
})
})
})
<file_sep>'use strict'
const fs = require('fs')
const reader = module.exports = {}
reader.read = function(paths, cb) {
// let one = paths[0]
// let two = paths[1]
// let three = paths[2]
// shorthand destructuring
let [one, two, three] = paths
let results = []
fs.readFile(one, (err, data) => {
if(err) {
console.error(err)
return cb(err)
}
results.push(data.toString())
fs.readFile(two, (err, data) => {
if(err) {
console.error(err)
return cb(err)
}
results.push(data.toString())
fs.readFile(three, (err, data) => {
if(err) {
console.error(err)
return cb(err)
}
results.push(data.toString())
return cb(null, results)
})
})
})
}
// Does not maintain the correct order of files read and file results
// reader.read = function(paths, cb) {
// // let one = paths[0]
// // let two = paths[1]
// // let three = paths[2]
// // shorthand destructuring
// let [one, two, three] = paths
// let results = []
// fs.readFile(one, (err, data) => {
// if(err) {
// console.error(err)
// return cb(err)
// }
// results.push(data.toString('utf-8', 0, 32))
// })
// fs.readFile(two, (err, data) => {
// if(err) {
// console.error(err)
// return cb(err)
// }
// results.push(data.toString('utf-8', 0, 32))
// })
// fs.readFile(three, (err, data) => {
// if(err) {
// console.error(err)
// return cb(err)
// }
// results.push(data.toString('utf-8', 0, 32))
// return cb(null, results)
// })
// }<file_sep>import ExpenseCreateForm from '../expense/expense-create-form/expense-create-form'
import ExpenseList from '../expense/expense-list/expense-list'
import ExpenseItem from '../expense/expense-item/expense-item'
export const ExpenseCreateForm
export const ExpenseList
export const ExpenseItem
<file_sep>'use strict'
// Write a function that takes N as it's only argument
// and returns the sum total of 0 to N
function sumIterative(n) {
let agg = 0
let x = n
for(n; n > 0; n--) {
agg += n
}
return agg
}
function recurse() {
if(count === 10) return
count++
recurse()
}
function sumRecursive(n) {
if(!n) return 1
return n + sumRecursive(n - 1)
}
let sumOneLineRecursive = n => n === 0 ? 0 : n + sumRecursive(n - 1)<file_sep>'use strict'
const math = module.exports = {}
math.floor = function(num) {
if(typeof num !== 'number') return new Error('barf')
return Math.floor(num)
}
// math.ceiling = function(num) {
// return Math.ceil(num)
// }
// math.absolute = function(num) {
// return Math.abs(num)
// }<file_sep>'use strict';
const mongoose = require('mongoose');
const Rider = require('./rider.js');
const Bike = mongoose.Schema({
'year': {type: Number},
'color': {type: String},
'make': {type: String, required: true},
'category': {type: String, required: true},
'rider': {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'riders'},
}, {timestamps: true});
Bike.pre('save', function(next) {
Rider.findById(this.rider)
.then(rider => {
let bikeIds = new Set(rider.bikes);
bikeIds.add(this._id);
rider.bikes = [...bikeIds];
Rider.findByIdAndUpdate(this.rider, {rider: rider.bikes});
})
.then(next)
.catch(() => next(new Error('Validation Error. Failed to save Bike.')));
});
Bike.post('remove', function(doc, next) {
Rider.findById(doc.rider)
.then(rider => {
rider.bikes = rider.bikes.filter(a => a.toString() !== doc._id.toString());
Rider.findByIdAndUpdate(this.rider, {rider: rider.bikes});
})
.then(next)
.catch(next);
});
module.exports = mongoose.model('bikes', Bike);<file_sep>'use strict'
require('jest')
describe('testing dummy', function() {
it('should return true', () => expect(true).toBeTruthy())
})<file_sep>'use strict';
const Rider = require('../model/rider.js');
const bodyParser = require('body-parser').json();
const errorHandler = require('../lib/error-handler.js');
module.exports = function(router) {
router.route('/rider/:_id?')
.get((req, res) => {
if(req.params._id) {
return Rider.findById(req.params._id)
.then(rider => res.status(200).json(rider))
.catch(err => errorHandler(err, res));
}
return Rider.find()
.then(rider => rider.map(a => ({_id: a._id, name: a.name})))
.then(rider => res.status(200).json(rider))
.catch(err => errorHandler(err, res));
})
.post(bodyParser, (req, res) => {
new Rider(req.body).save()
.then(rider => res.status(201).json(rider))
.catch(err => errorHandler(err, res));
})
.put(bodyParser, (req, res) => {
return Rider.findOneAndUpdate(req.params._id, req.body, {upsert: true, runValidators: true})
.then(() => res.sendStatus(204))
.catch(err => errorHandler(err, res));
})
.delete((req, res) => {
return Rider.findByIdAndRemove(req.params._id)
.then(() => res.sendStatus(204))
.catch(err => errorHandler(err, res));
});
}; | 2caa573108c66c5108bd2545410daf61cc3db215 | [
"JavaScript",
"Markdown"
] | 112 | JavaScript | montgomeryrd/seattle-javascript-401d21 | 03ed240bcd15a27f57c0e7c9102f663321c1e092 | 9140e8aa175f8c99dcfae16181d0de1649b390d8 | |
refs/heads/master | <file_sep># GoogleHomeHackathon-


[Watch Demo](https://vimeo.com/207585754)
# openBCI + GoogleHome
## Components of the application
1. OpenBCI Ganglion + SensorData
2. OSC in order to retrieve Data from open BCI
3. API.ai
4. GoogleCloudPlatform
## How the application works
We are using the streaming data from OpenBCI which is being transmitted from the networking tab along with the OSC. We then interpret the values and assign it to a Boolean of either True or False for stress. It is then stored in a file in which we read using our Node Server and pull the most recent value.
The system works through using API.ai’s entities along with intents in order to create the conversations of the Google Home(referred to as Home). When you have the system running, you initiate the conversation with the Home by asking to speak with OpenBCI. This allows for the system to differentiate our conversations from the other applications.
When you ask Google to help you relax, it will go and perform a /GET request to the server and read the True or False value. If the Value is true it will then play a Relax/Chill mood playlist from Spotify. This is done by combining the Google Home API with API.ai and accessing the Spotify playlist through their API.
If you were to ask to relax and the /GET returned a false response it would respond by saying that you are already relaxed. It would then end the conversation with Home’s OpenBCI.
This is all hosted on the Google Cloud Platform allowing for it to run when combined with the OpenBCI platform.
<file_sep>import argparse
import time
import atexit
import os
import signal
import sys
if sys.version_info.major == 3:
from pythonosc import dispatcher
from pythonosc import osc_server
elif sys.version_info.major == 2:
import OSC
last_time_checked = time.time()
over_threshold = False
sample_list = []
foo = 1
# Print received message to console
def print_message(*args):
global last_time_checked
data = args[2]
channel = data[0]
actual_data = data[1:]
if channel == 3:
# print actual_data
average = sum(actual_data) / len(actual_data)
#print average
if average > 0.5:
over_threshold = True
#make API CALL to Stressed
print "stressed=", average
else:
over_threshold = False
print "relaxed=", average
#make API CALL to Relaxed
#print args
# global sample_list
# sample_list.append(args[2])
# if len(sample_list) > 50:
# sample_list = sample_list[1:]
# average = sum(sample_list) / len(sample_list)
# print average
# # if time.time() - last_time_checked > 15000:
# last_time_checked = time.time()
# if average > 0.4:
# print "over the threshold!"
# if over_threshold is False:
# # make the API call here
# # pass
# over_threshold = True
# else:
# print "below threshold"
# if over_threshold:
# make the API call
# pass
#over_threshold = False
# try:
# current = time.time()
# if sys.version_info.major == 2:
# #print("(%f) RECEIVED MESSAGE: %s %s" % (current, args[0], ",".join(str(x) for x in args[2:])))
# elif sys.version_info.major == 3:
#print("(%f) RECEIVED MESSAGE: %s %s" % (current, args[0], ",".join(str(x) for x in args[1:])))
#except ValueError: pass
# Clean exit from print mode
def exit_print(signal, frame):
print("Closing listener")
sys.exit(0)
# Record received message in text file
def record_to_file(*args):
f = open("textfile.txt", "w")
textfile.write(str(time.time()) + ",")
textfile.write(",".join(str(x) for x in args))
textfile.write("\n")
# Save recording, clean exit from record mode
def close_file(*args):
print("\nFILE SAVED")
textfile.close()
sys.exit(0)
if __name__ == "__main__":
# Collect command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--ip",
default="localhost", help="The ip to listen on")
parser.add_argument("--port",
type=int, default=12345, help="The port to listen on")
parser.add_argument("--address",default="/openbci", help="address to listen to")
parser.add_argument("--option",default="print",help="Debugger option")
args = parser.parse_args()
if sys.version_info.major == 3:
# Set up necessary parameters from command line
dispatcher = dispatcher.Dispatcher()
if args.option=="print":
dispatcher.map("/openbci", print_message)
signal.signal(signal.SIGINT, exit_print)
elif args.option=="record":
i = 0
while os.path.exists("osc_test%s.txt" % i):
i += 1
filename = "osc_test%i.txt" % i
textfile = open(filename, "w")
print("Recording to %s" % filename)
dispatcher.map("/openbci", record_to_file)
signal.signal(signal.SIGINT, close_file)
# Display server attributes
print('--------------------')
print("-- OSC LISTENER -- ")
print('--------------------')
print("IP:", args.ip)
print("PORT:", args.port)
print("ADDRESS:", args.address)
print('--------------------')
print("%s option selected" % args.option)
# connect server
server = osc_server.ThreadingOSCUDPServer(
(args.ip, args.port), dispatcher)
server.serve_forever()
elif sys.version_info.major == 2:
s = OSC.OSCServer((args.ip, args.port)) # listen on localhost, port 57120
if args.option=="print":
s.addMsgHandler(args.address, print_message)
elif args.option=="record":
i = 0
while os.path.exists("osc_test%s.txt" % i):
i += 1
filename = "osc_test%i.txt" % i
textfile = open(filename, "w")
textfile.write("time,address,messages\n")
textfile.write("-------------------------\n")
print("Recording to %s" % filename)
signal.signal(signal.SIGINT, close_file)
# Display server attributes
print('--------------------')
print("-- OSC LISTENER -- ")
print('--------------------')
print("IP:", args.ip)
print("PORT:", args.port)
print("ADDRESS:", args.address)
print('--------------------')
print("%s option selected" % args.option)
print("Listening...")
s.serve_forever()
| cc46449db16eed4b8a514ddc2b1df40aaf968b47 | [
"Markdown",
"Python"
] | 2 | Markdown | noufali/GoogleHomeHackathon- | 938320ee299b57c3b92cf47f07bc54cab182ecb1 | 7f74ce7ca4d319ef803b95633cf31a9208ffd3db | |
refs/heads/master | <file_sep>function mostrarMensagem(){
var anoDeNascimento = prompt("Olá, Digite o ano de seu nascimento: ");
var anoAtual = new Date().getFullYear();
var idade = anoAtual - anoDeNascimento;
alert(`Você tem ${idade} anos`);
}
mostrarMensagem();<file_sep># Vitex-o-mais-brabo
Vitex o Mais brabo
| 729d0917844c98f071571ebccdf1a2e2b8ba1256 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | VictorPieretti/Vitex-o-mais-brabo | ca844b6c68cd963c7560aafb1db36a9648f105d3 | 578607ffe60decd5aa8754fd56a30e292a933860 | |
refs/heads/master | <file_sep>package org.zerock.service;
import java.util.List;
import org.zerock.domain.BoardVO;
public interface BoardService {
public void regist(BoardVO board) throws Exception;
public BoardVO read(Integer bno) throws Exception;
public void mdify(BoardVO board) throws Exception;
public void remove(Integer bno) throws Exception;
public List<BoardVO> listAll() throws Exception;
}
| ecfc0d8ccda2e8d3863ffa69d2ae038d3eb9ed10 | [
"Java"
] | 1 | Java | Fran4ssisi/Spring-Legacy | 9e6655a00eef86b65b80dfacd5e88cd407d39c96 | e532e3bd928904b29161e68e0280dcd635d471c6 | |
refs/heads/master | <repo_name>Shash29/Checkers-using-Python<file_sep>/README.md
# Checkers-using-Python
An implementation of the checkers board game using some simple concepts of Python. The GUI of the game has been implemented using the Turtle library.
Basic rules of Checkers:- https://www.ducksters.com/games/checkers_rules.php
This implementation is for Player vs Player. Player vs Computer coming soon! ;-)
About GUI:- Background is initially blue,but at any point of the game,the Background colour specifies which player has to make his move in the current turn.
The game begins with Red pieces' turn. The game ends when one of the players has no pieces left.
<file_sep>/Checkers pvp.py
import turtle
from math import *
from random import randint
from time import sleep
Arr=[['_','_','_','_','_','_','_','_'], #2D array for background processes of Game board
['_','_','_','_','_','_','_','_'],
['_','_','_','_','_','_','_','_'],
['_','_','_','_','_','_','_','_'],
['_','_','_','_','_','_','_','_'],
['_','_','_','_','_','_','_','_'],
['_','_','_','_','_','_','_','_'],
['_','_','_','_','_','_','_','_']]
Reds=['_','_','_','_','_','_','_','_','_','_','_','_'];
Grays=['_','_','_','_','_','_','_','_','_','_','_','_'];
RedT=['_','_','_','_','_','_','_','_','_','_','_','_']; #Arrays for storing turtles corresponding to coins
GrayT=['_','_','_','_','_','_','_','_','_','_','_','_'];
ColArrays=[Reds,Grays]
TurtArrays=[RedT,GrayT]
Map = [40+n*80 for n in range(-4,4)] #for mapping array indices to co-ordinates
Bcolors = ["black","white"]
Colors = ["red","gray"]
turtle.setup(1500,700) #setting up game window
window = turtle.Screen()
window.title('Checkers')
window.bgcolor("blue")
DrawBot = turtle.getturtle() #setting up a turtle for drawing
DrawBot.speed(0)
DrawBot.begin_poly() #creating a square shape for turtle
DrawBot.penup()
DrawBot.setposition(40,40)
DrawBot.setheading(180)
DrawBot.pendown()
i=0
while(i<4):
DrawBot.forward(80)
DrawBot.left(90)
i+=1
DrawBot.penup()
DrawBot.setposition(0,0)
DrawBot.end_poly()
turtle.register_shape('Block',DrawBot.get_poly())
DrawBot.begin_poly() #creating a circle shape for coins
DrawBot.pensize(5)
DrawBot.penup()
DrawBot.setheading(90)
DrawBot.forward(30)
DrawBot.left(90)
DrawBot.pendown()
DrawBot.circle(30)
DrawBot.penup()
DrawBot.setposition(0,0)
DrawBot.setheading(90)
DrawBot.end_poly()
turtle.register_shape('Coin',DrawBot.get_poly())
DrawBot.begin_poly() #creating a King circle shape for coins
DrawBot.fillcolor("yellow")
DrawBot.pensize(5)
DrawBot.penup()
DrawBot.setheading(90)
DrawBot.forward(20)
DrawBot.left(90)
DrawBot.pendown()
DrawBot.begin_fill()
DrawBot.circle(20)
DrawBot.end_fill()
DrawBot.penup()
DrawBot.setheading(90)
DrawBot.forward(10)
DrawBot.left(90)
DrawBot.pendown()
DrawBot.circle(30)
DrawBot.penup()
DrawBot.setposition(0,0)
DrawBot.setheading(90)
DrawBot.end_poly()
turtle.register_shape('King_Coin',DrawBot.get_poly())
class Coin(object):
def _init_(self,i,j,color,Type,ai):
self.i = i
self.j = j
self.color = color
self.Type = Type
self.ai = ai
def setup_coin(self,i,j,color,Type,ai):
self.i = i
self.j = j
self.color = color
self.Type = Type
self.ai = ai
def setTurtPos(self,i,j):
if(self.color=="red"):
RedT[self.ai].setposition(Map[j],Map[7-i])
else:
GrayT[self.ai].setposition(Map[j],Map[7-i])
def setPos(self,i,j):
self.i = i
self.j = j
Arr[i][j] = self
self.setTurtPos(i,j)
def upgrade(self):
self.Type = "king"
if(self.color=="red"):
RedT[self.ai].shape("King_Coin")
else:
GrayT[self.ai].shape("King_Coin")
DrawBot.penup() #Drawing the game board using stamps
DrawBot.shape('Block')
c=0;i=0;
while(i<8):
j=0
while(j<8):
DrawBot.setposition(Map[i],Map[j])
DrawBot.pendown()
DrawBot.pencolor(Bcolors[c])
DrawBot.fillcolor(Bcolors[c])
DrawBot.stamp()
DrawBot.penup()
j+=1
c=1-c
c=1-c
i+=1
i=1;j=0;t=0; #Creating and Arranging Red Coins
while(j<8):
Reds[t] = Coin()
Reds[t].setup_coin(i,j,"red","norm",t)
RedT[t] = turtle.Turtle()
RedT[t].shape('Coin')
RedT[t].speed(10)
RedT[t].fillcolor("red")
RedT[t].penup()
Arr[i][j] = Reds[t]
Arr[i][j].setTurtPos(i,j)
t+=1
i+=2
if(i>2):
j+=1
i%=3
i=0;j=0;t=0; #Creating and Arranging Gray Coins
while(j<8):
Grays[t] = Coin()
Grays[t].setup_coin(i+5,j,"gray","norm",t)
GrayT[t] = turtle.Turtle()
GrayT[t].shape('Coin')
GrayT[t].speed(10)
GrayT[t].fillcolor("gray")
GrayT[t].penup()
Arr[i+5][j] = Grays[t]
Arr[i+5][j].setTurtPos(i+5,j)
t+=1
i+=2
if(i>2):
j+=1
i%=3
Pointer=turtle.Turtle() #Creating a Pointer for the Game Board
Pointer.hideturtle()
Pointer.speed(0)
Pointer.setheading(90)
Pointer.penup()
Pointer.shape("Block")
Pointer.fillcolor("yellow")
Pointer.pencolor("yellow")
All_step = [1,-1]
All_jump = [2,-2]
P=0
G=0
pi=(-1)
pj=(-1)
SLock = 0
def ClickTrack(x,y): #returns coordinates of the centre of any clicked square
if(x<320 and x>(-320)):
X=int(fabs(x))
Y=int(fabs(y))
a=floor(X/80)
A=ceil(X/80)
xi=(x/X)*((a*80+A*80)/2)
elif(x>320):
xi=280
else:
xi=(-280)
if(y<320 and y>(-320)):
b=floor(Y/80)
B=ceil(Y/80)
yj=(y/Y)*((b*80+B*80)/2)
elif(y>320):
yj=280
else:
yj=(-280)
return [xi,yj]
def Point(x,y): #Highlights the recently clicked square
Coords = ClickTrack(x,y)
Pointer.clearstamps()
Pointer.setposition(Coords[0],Coords[1])
Pointer.stamp()
global P
global pi
global pj
global G
global SLock
window.bgcolor(Colors[P])
if(G==0):
j=Map.index(Coords[0])
i=7-Map.index(Coords[1])
if(Arr[i][j]!='_'): #if a coin was recently clicked
if(SLock == 0):
Arr[i][j].setTurtPos(i,j)
if(Arr[i][j].color == Colors[P]):
pi = i;pj = j;
else:
pi = (-1);pj = (-1);
else: #if a free block was recently clicked
if(pi!=(-1)): #if a coin was already selected
di = i - pi
dj = j - pj
if(fabs(di) > 2): #if the recently clicked block cant be reached by selected coin #change this to >2 when enabling jump move
if(SLock == 0):
pi = (-1);pj = (-1);
else:
if(fabs(di)==1 and fabs(dj)==1 and SLock==0):
if(Arr[pi][pj].Type=="norm" and di!=All_step[P]):
pi = (-1);pj = (-1);
else:
t = Arr[pi][pj].ai
c = Arr[pi][pj].color
Arr[pi][pj] = '_'
if(c=="red"):
Reds[t].setPos(i,j)
if(Reds[t].Type=="norm" and i==7):
Reds[t].upgrade()
else:
Grays[t].setPos(i,j)
if(Grays[t].Type=="norm" and i==0):
Grays[t].upgrade()
pi = (-1);pj = (-1);
P = 1-P
window.bgcolor(Colors[P])
elif(fabs(di)==2 and fabs(dj)==2):
dei = int((pi+i)/2); dej = int((pj+j)/2);
print("dei=",dei,"\n")
print("dej=",dej,"\n")
if((Arr[pi][pj].Type=="norm" and di!=All_jump[P]) or Arr[dei][dej]=='_'):
if(SLock == 0):
pi = (-1);pj = (-1);
else:
if(Arr[dei][dej].color==Colors[P]):
if(SLock == 0):
pi = (-1);pj = (-1);
else:
t = Arr[pi][pj].ai
c = Arr[pi][pj].color
Arr[pi][pj] = '_'
if(c=="red"):
Reds[t].setPos(i,j)
if(Reds[t].Type=="norm" and i==7):
Reds[t].upgrade()
else:
Grays[t].setPos(i,j)
if(Grays[t].Type=="norm" and i==0):
Grays[t].upgrade()
td = Arr[dei][dej].ai
tc = Arr[dei][dej].color
Arr[dei][dej] = '_'
if(tc=="red"):
del Reds[td]
RedT[td].hideturtle()
del RedT[td]
R=len(Reds)
if(R>td):
ind = td
while(ind<R):
Reds[ind].ai-=1
Arr[Reds[ind].i][Reds[ind].j] = Reds[ind]
ind+=1
else:
del Grays[td]
GrayT[td].hideturtle()
del GrayT[td]
R=len(Grays)
if(R>td):
ind = td
while(ind<R):
Grays[ind].ai-=1
Arr[Grays[ind].i][Grays[ind].j] = Grays[ind]
ind+=1
print(Colors[1-P],":",R)
if(R==0):
G=1
window.bgcolor("green")
print("Player",P+1,"Wins!!")
else:
Jumps = []
for qi in [1,-1]:
if((ColArrays[P])[t].Type == "norm" and qi != All_step[P]):
Jumps.append(False)
else:
if(i+2*qi>7 or i+2*qi<0):
Jumps.append(False)
else:
for qj in [1,-1]:
if(j+2*qj>7 or j+2*qj<0):
Jumps.append(False)
elif(Arr[i+2*qi][j+2*qj]=='_' and Arr[i+qi][j+qj]!='_'):
if(Arr[i+qi][j+qj].color==Colors[1-P]):
Jumps.append(True)
else:
Jumps.append(False)
else:
Jumps.append(False)
if(True in Jumps):
pi = i;pj = j;
SLock = 1
else:
SLock = 0
pi =(-1);pj =(-1);
P = 1-P
window.bgcolor(Colors[P])
'''pi =(-1);pj =(-1);
P = 1-P
window.bgcolor(Colors[P])'''
else:
if(SLock == 0):
pi = (-1);pj = (-1);
window.onscreenclick(Point,1)
def Unpoint(x,y): #Unhighlights a highlighted square
global P
Pointer.clearstamps()
P = 1-P
window.bgcolor(Colors[P])
window.onscreenclick(Unpoint,3)
| 42e7434b2acb4907edc5f3c9a3327bad9f29b96f | [
"Markdown",
"Python"
] | 2 | Markdown | Shash29/Checkers-using-Python | 7997c7599f7f42825fd25aea40cbeb8d9a62521e | 4fe0b696247f7ad46b28c409d3c3d0caecb0e187 | |
refs/heads/master | <file_sep>const xlsx = require('xlsx'),
fs = require('fs'),
path = require('path');
//takes an array of objects and returns another array of objects with a certain property removed
function property_remover(data, property){
let new_data = data.map(record => {
if(record[property]){
delete(record[property]);
}
return record;
})
return new_data;
}
//takes the path of a certain excel workbook path and returns the data in its first worksheet
function readFileToJson(workbook_path){
let wb = xlsx.readFile(workbook_path),
first_tab = wb.SheetNames[0],
ws = wb.Sheets[first_tab],
data = xlsx.utils.sheet_to_json(ws);
data = property_remover(data, 'مسلسل');
return data;
}
function extension_validator(file){
let file_ext = path.parse(file).ext;
if( ((file_ext === '.xls')||(file_ext === '.xlsx')) && file[0] !== "~"){
return true;
}
return false;
}
function arr_comparator(agg_arr, obj, code) {
for (i = 0; i < agg_arr.length; i++){
agg_obj = agg_arr[i];
if(obj[code] === agg_obj[code]){
return i;
}
}
return false;
}
//takes an array of duplicate objects and returns an array with its duplicate objects reduced to one with a counter holding the number of duplications
function data_consolidator(attendance_data){
let aggregate_att_arr = [],
mod_att_data = attendance_data.map( obj => {
return {...obj, counter:1};
}),
code = ['الكود'];
mod_att_data.forEach(obj => {
let object_exists = arr_comparator(aggregate_att_arr, obj, code);
if(object_exists){
agg_obj = aggregate_att_arr[object_exists];
agg_obj.counter++;
}
else{
aggregate_att_arr.push(obj);
}
})
return aggregate_att_arr;
}
//takes the path of the folder containing our excel files that we want to merge, and returns an array containing their data combined and reduced (using data_consolidator) in json format
function files_merger_generic(sourceDir){
let dir_path = path.join(__dirname, sourceDir),
files = fs.readdirSync(dir_path).filter(extension_validator),
combinedFilesArray = [];
files.forEach(file => {
fileData = readFileToJson(path.join(__dirname, sourceDir, file));
combinedFilesArray = combinedFilesArray.concat(fileData);
})
let reducedFilesArray = data_consolidator(combinedFilesArray);
return reducedFilesArray;
}
//takes the path of the folder containing our excel files that we want to merge, and returns an array containing their data combined in json format(1 array of monthly payments and 1 array of other payments)
function files_merger_cash(sourceDir){
let dir_path = path.join(__dirname, sourceDir),
files = fs.readdirSync(dir_path).filter(extension_validator),
val = 'اشتراك',
combined_monthly = [],
combined_other = [];
files.forEach(file => {
fileData = readFileToJson(path.join(__dirname, sourceDir, file));
monthly_fees = fileData.filter(obj => obj['بيان'] === val);
other_fees = fileData.filter(obj => obj['بيان'] !== val);
combined_monthly = combined_monthly.concat(monthly_fees);
combined_other = combined_other.concat(other_fees);
})
return [combined_monthly, combined_other];
}
//takes the path of the payments folder containing the total and cash excel files each in its own folder, and returns an array of objects containing the students that haven't paid and are not terminated
function net_cash_calculator(source_dir){
let dir_path_cash = path.join(__dirname, source_dir, 'cash'),
dir_path_total = path.join(__dirname, source_dir, 'total'),
cash_file = fs.readdirSync(dir_path_cash).filter(extension_validator)[0],
total_file = fs.readdirSync(dir_path_total).filter(extension_validator)[0],
file_data_1 = readFileToJson(path.join(dir_path_cash, cash_file)),
file_data_2 = readFileToJson(path.join(dir_path_total, total_file)),
unique_data = [...file_data_2],
std_code = 'الكود';
for ( i = 0; i < file_data_2.length; i++){
for (j = 0; j < file_data_1.length; j++){
code_cash = file_data_1[j][std_code];
code_total = file_data_2[i][std_code];
if (code_cash === code_total){
unique_data.splice(unique_data.findIndex( obj => obj[std_code] === code_total), 1);
break;
}
}
}
let active_unique_data = unique_data.filter(std => std['الموقف'] !== 'Termination');
return active_unique_data;
}
//takes the path of the folder containing our excel files that we want to merge, and returns a new file containing all of their data combined
function merged_file_creator(sourceDir, data_array, file_name){
let newWB = xlsx.utils.book_new(),
newWS = xlsx.utils.json_to_sheet(data_array);
xlsx.utils.book_append_sheet(newWB, newWS, "Merged Data");
xlsx.writeFile(newWB, file_name);
}
function directory_creator(folder_name){
let sourceDir = 'excel_files',
dir = path.join(sourceDir, folder_name);
return dir;
}
let att_src_dir = directory_creator('attendance');
let trans_src_dir = directory_creator('transforms');
let cash_src_dir = directory_creator('cash');
let payments_src_dir = directory_creator('payments');
merged_file_creator(att_src_dir, files_merger_generic(att_src_dir), "اجمالي حضور.xlsx");
merged_file_creator(trans_src_dir, files_merger_generic(trans_src_dir), "اجمالي تحويلات.xlsx");
merged_file_creator(cash_src_dir, files_merger_cash(cash_src_dir)[0], "اجمالي يومية اشتراكات.xlsx");
merged_file_creator(cash_src_dir, files_merger_cash(cash_src_dir)[1], "اجمالي يومية اخري.xlsx");
merged_file_creator(payments_src_dir, net_cash_calculator(payments_src_dir), 'غير مدفوع.xlsx');
| d1533c0f1941b0a097e6c8d255cc377e1d52afb3 | [
"JavaScript"
] | 1 | JavaScript | YasserElmor/financial-revision-automation | ebcb93d1b2d8eac94caade604fb287bc23151e68 | 0ca4a4fe9d02a85f6692b9738a241c4b1737a4c0 | |
refs/heads/master | <repo_name>tiamahone/TermProject1<file_sep>/CloudService/CloudSVC.asmx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using Utilities;
namespace CloudService
{
/// <summary>
/// Summary description for CloudSVC
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class CloudSVC : System.Web.Services.WebService
{
[WebMethod]
public int attemptLogin(string[] loginInfo)
{
int response;
string email = loginInfo[0];
string password = loginInfo[1];
DBConnect objDB;
SqlCommand objCommand;
DataSet myDs;
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetCloudUserInfo";
objCommand.Parameters.AddWithValue("@email", email);
myDs = objDB.GetDataSetUsingCmdObj(objCommand);
if (myDs.Tables[0].Rows.Count != 0)
{
if (password != objDB.GetField("Password", 0).ToString())
{
response = 0;
}
else
{
response = 1;
}
}
else
{
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetCloudAdminInfo";
objCommand.Parameters.AddWithValue("@email", email);
myDs = objDB.GetDataSetUsingCmdObj(objCommand);
if (myDs.Tables[0].Rows.Count != 0)
{
if (password != objDB.GetField("Password", 0).ToString())
{
response = 0;
}
else
{
response = 2;
}
}
else
{
response = -1;
}
}
return response;
}
[WebMethod]
public int addUser(string[] userInfo)
{
int response;
//if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
//{
string name = userInfo[0];
string email = userInfo[1];
string password = userInfo[2];
string phone = userInfo[3];
DBConnect objDB;
SqlCommand objCommand;
DataSet myDs;
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetCloudUserInfo";
objCommand.Parameters.AddWithValue("@email", email);
myDs = objDB.GetDataSetUsingCmdObj(objCommand);
if (myDs.Tables[0].Rows.Count != 0)
{
response = -1;
}
else
{
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "AddCloudUser";
objCommand.Parameters.AddWithValue("@name", name);
objCommand.Parameters.AddWithValue("@email", email);
objCommand.Parameters.AddWithValue("@password", <PASSWORD>);
objCommand.Parameters.AddWithValue("@phone", phone);
//myDs = objDB.GetDataSetUsingCmdObj(objCommand);
objDB.DoUpdateUsingCmdObj(objCommand);
response = 0;
}
//}
// else
//{
// response = -1;
//}
return response;
}
[WebMethod]
public int addAdmin(string[] loginInfo, string[] userInfo)
{
int response;
if (attemptLogin(loginInfo) == 2)
{
string name = userInfo[0];
string email = userInfo[1];
string password = userInfo[2];
string phone = userInfo[3];
DBConnect objDB;
SqlCommand objCommand;
DataSet myDs;
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetCloudAdminInfo";
objCommand.Parameters.AddWithValue("@email", email);
myDs = objDB.GetDataSetUsingCmdObj(objCommand);
if (myDs.Tables[0].Rows.Count != 0)
{
response = -1;
}
else
{
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "AddCloudAdmin";
objCommand.Parameters.AddWithValue("@name", name);
objCommand.Parameters.AddWithValue("@email", email);
objCommand.Parameters.AddWithValue("@password", <PASSWORD>);
objCommand.Parameters.AddWithValue("@phone", phone);
//myDs = objDB.GetDataSetUsingCmdObj(objCommand);
objDB.DoUpdateUsingCmdObj(objCommand);
response = 0;
}
}
else
{
response = -1;
}
return response;
}
[WebMethod]
public int addFile(string[] loginInfo, string[] fileInfo, byte[] fileData)
{
int response = 0;
string transactionType = "Upload";
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
string fileEmail = fileInfo[0];
string fileName = fileInfo[1];
string fileType = fileInfo[2];
double fileSize = Convert.ToDouble(fileInfo[3]);
double freeStorage = getUserFreeStorage(loginInfo, fileInfo);
DBConnect objDB;
SqlCommand objCommand;
//Checks to see if file already exists
//DataSet myDs = checkForFile(loginInfo, fileInfo);
double oldFileSize = checkForFile(loginInfo, fileInfo);
//if (myDs.Tables[0].Rows.Count != 0
if (oldFileSize != 0)
{
string[] file = new string[3];
file[0] = fileName;
//file[1] = fileSize.ToString();
file[1] = oldFileSize.ToString();
deleteFile(loginInfo, file);
transactionType = "Update";
response = 1;
}
//Checks to see if enough storage is available
if (fileSize > freeStorage)
{
response = -1;
}
else
{
//Adds file to DB
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "AddCloudFile";
objCommand.Parameters.AddWithValue("@email", fileEmail);
objCommand.Parameters.AddWithValue("@fileName", fileName);
objCommand.Parameters.AddWithValue("@fileType", fileType);
objCommand.Parameters.AddWithValue("@fileSize", fileSize);
objCommand.Parameters.AddWithValue("@fileData", fileData);
objDB.DoUpdateUsingCmdObj(objCommand);
//Updates free storage number in CloudUsersDB
double newFreeStorage = freeStorage - fileSize;
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "UpdateUserFreeStorage";
objCommand.Parameters.AddWithValue("@email", fileEmail);
objCommand.Parameters.AddWithValue("@newStorage", newFreeStorage);
objDB.DoUpdateUsingCmdObj(objCommand);
//Adds transaction record to CloudUserTransactions table
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "AddCloudTransaction";
objCommand.Parameters.AddWithValue("@email", fileEmail);
objCommand.Parameters.AddWithValue("@type", transactionType);
objCommand.Parameters.AddWithValue("@fileName", fileName);
objCommand.Parameters.AddWithValue("@time", DateTime.Now);
objDB.DoUpdateUsingCmdObj(objCommand);
}
}
else
{
response = -1;
}
return response;
}
[WebMethod]
public double checkForFile(string[] loginInfo, string[] userInfo)
{
double size = 0;
DataSet myDS = null;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "checkForFile";
objCommand.Parameters.AddWithValue("@email", userInfo[0]);
objCommand.Parameters.AddWithValue("@fileName", userInfo[1]);
DBConnect objDB = new DBConnect();
myDS = objDB.GetDataSetUsingCmdObj(objCommand);
if (myDS.Tables[0].Rows.Count != 0)
{
size = Convert.ToDouble(objDB.GetField("File Size", 0));
}
}
//return myDS;
return size;
}
[WebMethod]
public DataSet getFilesByUser(string[] loginInfo, string[] userInfo)
{
DataSet myDS = null;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetCloudFilesByUser";
objCommand.Parameters.AddWithValue("@email", userInfo[0]);
DBConnect objDB = new DBConnect();
myDS = objDB.GetDataSetUsingCmdObj(objCommand);
}
return myDS;
}
[WebMethod]
public double getUserFreeStorage(string[] loginInfo, string[] userInfo)
{
double freeStorage = 0;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetCloudUserFreeStorage";
objCommand.Parameters.AddWithValue("@email", userInfo[0]);
DBConnect objDB = new DBConnect();
DataSet myDS = objDB.GetDataSetUsingCmdObj(objCommand);
freeStorage = Convert.ToDouble(objDB.GetField("Free Storage", 0));
}
return freeStorage;
}
[WebMethod]
public double getUserTotalStorage(string[] loginInfo, string[] userInfo)
{
double totalStorage = 0;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetCloudUserTotalStorage";
objCommand.Parameters.AddWithValue("@email", userInfo[0]);
DBConnect objDB = new DBConnect();
DataSet myDS = objDB.GetDataSetUsingCmdObj(objCommand);
totalStorage = Convert.ToDouble(objDB.GetField("Total Storage", 0));
}
return totalStorage;
}
[WebMethod]
public DataSet getCloudUsers(string[] loginInfo)
{
DataSet myDS = null;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetCloudUsers";
DBConnect objDB = new DBConnect();
myDS = objDB.GetDataSetUsingCmdObj(objCommand);
}
return myDS;
}
[WebMethod]
public DataSet getCloudUsersInfo(string[] loginInfo)
{
DataSet myDS = null;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetCloudUsersInfo";
DBConnect objDB = new DBConnect();
myDS = objDB.GetDataSetUsingCmdObj(objCommand);
}
return myDS;
}
[WebMethod]
public DataSet getTransactions(string[] loginInfo, string[] userInfo)
{
DataSet myDS = null;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetCloudTransactions";
objCommand.Parameters.AddWithValue("@email", userInfo[0]);
if (userInfo[1] == "All")
{
objCommand.Parameters.AddWithValue("@timePeriod", "1/01/1900 12:00:01 AM");
}
else if (userInfo[1] == "Past Day")
{
DateTime timePeriod = (Convert.ToDateTime(userInfo[1])).AddDays(-1);
objCommand.Parameters.AddWithValue("@timePeriod", userInfo[1]);
}
else if (userInfo[1] == "Past Week")
{
DateTime timePeriod = (Convert.ToDateTime(userInfo[1])).AddDays(-7);
objCommand.Parameters.AddWithValue("@timePeriod", userInfo[1]);
}
else if (userInfo[1] == "Past Month")
{
DateTime timePeriod = (Convert.ToDateTime(userInfo[1])).AddDays(-30);
objCommand.Parameters.AddWithValue("@timePeriod", userInfo[1]);
}
DBConnect objDB = new DBConnect();
myDS = objDB.GetDataSetUsingCmdObj(objCommand);
}
return myDS;
}
[WebMethod]
public int adminUpdateUser(string[] loginInfo, string[] userInfo)
{
int response = -1;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
double freeStorage = getUserFreeStorage(loginInfo, userInfo);
double oldTotalStorage = getUserTotalStorage(loginInfo, userInfo);
double difference = (Convert.ToDouble(userInfo[3])) - oldTotalStorage;
freeStorage += difference;
SqlCommand objCommand = new SqlCommand();
DBConnect objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "UpdateCloudUser";
objCommand.Parameters.AddWithValue("@email", userInfo[0]);
objCommand.Parameters.AddWithValue("@password", <PASSWORD>[1]);
objCommand.Parameters.AddWithValue("@phone", userInfo[2]);
objCommand.Parameters.AddWithValue("@totalStorage", userInfo[3]);
objCommand.Parameters.AddWithValue("@freeStorage", freeStorage);
objDB.DoUpdateUsingCmdObj(objCommand);
response = 0;
}
return response;
}
[WebMethod]
public int deleteUser(string[] loginInfo, string[] userInfo)
{
int response = -1;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
DBConnect objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "DeleteCloudUser";
objCommand.Parameters.AddWithValue("@email", userInfo[0]);
objDB.DoUpdateUsingCmdObj(objCommand);
response = 0;
}
return response;
}
[WebMethod]
public DataSet getSingleUserInfo(string[] loginInfo, string[] userInfo)
{
DataSet myDS = null;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetSingleCloudUser";
objCommand.Parameters.AddWithValue("@email", userInfo[0]);
DBConnect objDB = new DBConnect();
myDS = objDB.GetDataSetUsingCmdObj(objCommand);
}
return myDS;
}
[WebMethod]
public int userUpdateUser(string[] loginInfo, string[] userInfo)
{
int response = -1;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
DBConnect objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "UpdateCloudUserPersonal";
objCommand.Parameters.AddWithValue("@id", Convert.ToInt32(userInfo[0]));
objCommand.Parameters.AddWithValue("@name", userInfo[1]);
objCommand.Parameters.AddWithValue("@email", userInfo[2]);
objCommand.Parameters.AddWithValue("@password", userInfo[3]);
objCommand.Parameters.AddWithValue("@phone", userInfo[4]);
objDB.DoUpdateUsingCmdObj(objCommand);
response = 0;
}
return response;
}
[WebMethod]
public int deleteFile(string[] loginInfo, string[] userInfo)
{
int response = -1;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
DBConnect objDB = new DBConnect();
//GET FILE
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetFile";
objCommand.Parameters.AddWithValue("@email", loginInfo[0]);
objCommand.Parameters.AddWithValue("@fileName", userInfo[0]);
DataSet myDS = objDB.GetDataSetUsingCmdObj(objCommand);
string email = objDB.GetField("Email", 0).ToString();
string fileName = objDB.GetField("File Name", 0).ToString();
string fileType = objDB.GetField("File Type", 0).ToString();
double fileSizeOld = Convert.ToDouble(objDB.GetField("File Size", 0));
byte[] fileData = (byte[])objDB.GetField("File Data", 0);
DateTime timeStamp = DateTime.Now;
//byte[] image = (byte[])objDB.GetField("File Image", 0);
//Put file in trash
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "AddToTrash";
objCommand.Parameters.AddWithValue("@email", email);
objCommand.Parameters.AddWithValue("@fileName", fileName);
objCommand.Parameters.AddWithValue("@fileType", fileType);
objCommand.Parameters.AddWithValue("@fileSize", fileSizeOld);
objCommand.Parameters.AddWithValue("@fileData", fileData);
objCommand.Parameters.AddWithValue("@timeStamp", timeStamp);
//objCommand.Parameters.AddWithValue("@image", image);
objDB.DoUpdateUsingCmdObj(objCommand);
//Delete File
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "DeleteFile";
objCommand.Parameters.AddWithValue("@email", loginInfo[0]);
objCommand.Parameters.AddWithValue("@fileName", userInfo[0]);
objDB.DoUpdateUsingCmdObj(objCommand);
double oldFreeSpace = Convert.ToDouble(getUserFreeStorage(loginInfo, loginInfo));
double fileSize = Convert.ToDouble(userInfo[1]);
double newFreeSpace = oldFreeSpace + fileSize;
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "UpdateFreeSpace";
objCommand.Parameters.AddWithValue("@email", loginInfo[0]);
objCommand.Parameters.AddWithValue("@freeStorage", newFreeSpace);
objDB.DoUpdateUsingCmdObj(objCommand);
// add transaction
if (userInfo[2] == "delete")
{
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "AddCloudTransaction";
objCommand.Parameters.AddWithValue("@email", email);
objCommand.Parameters.AddWithValue("@type", "Delete");
objCommand.Parameters.AddWithValue("@fileName", fileName);
objCommand.Parameters.AddWithValue("@time", DateTime.Now);
objDB.DoUpdateUsingCmdObj(objCommand);
}
response = 0;
}
return response;
}
[WebMethod]
public DataSet getUserTrash(string[] loginInfo, string[] userInfo)
{
DataSet myDS = null;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetTrashByUser ";
objCommand.Parameters.AddWithValue("@email", userInfo[0]);
DBConnect objDB = new DBConnect();
myDS = objDB.GetDataSetUsingCmdObj(objCommand);
}
return myDS;
}
[WebMethod]
public int changeStoragePlan(string[] loginInfo, string[] userInfo)
{
int response = 0;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
double freeStorage = getUserFreeStorage(loginInfo, userInfo);
double totalStorage = getUserTotalStorage(loginInfo, userInfo);
double newTotalStorage = Convert.ToDouble(userInfo[1]);
double newFreeStorage = freeStorage + (newTotalStorage - totalStorage);
DBConnect objDB = new DBConnect();
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "ChangeStoragePlan";
objCommand.Parameters.AddWithValue("@email", userInfo[0]);
objCommand.Parameters.AddWithValue("@freeStorage", newFreeStorage);
objCommand.Parameters.AddWithValue("@totalStorage", newTotalStorage);
objDB.DoUpdateUsingCmdObj(objCommand);
}
return response;
}
[WebMethod]
public int recoverFile(string[] loginInfo, string[] userInfo)
{
int response = 0;
if (attemptLogin(loginInfo) == 1 || attemptLogin(loginInfo) == 2)
{
DBConnect objDB = new DBConnect();
SqlCommand objCommand = new SqlCommand();
//GET FILE
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetFileFromTrash";
objCommand.Parameters.AddWithValue("@id", userInfo[1]);
DataSet myDS = objDB.GetDataSetUsingCmdObj(objCommand);
string email = objDB.GetField("Email", 0).ToString();
string fileName = objDB.GetField("File Name", 0).ToString();
fileName += "-R";
string fileType = objDB.GetField("File Type", 0).ToString();
double fileSizeOld = Convert.ToDouble(objDB.GetField("File Size", 0));
byte[] fileData = (byte[])objDB.GetField("File Data", 0);
DateTime timeStamp = DateTime.Now;
//Update Free Space
double oldFreeSpace = Convert.ToDouble(getUserFreeStorage(loginInfo, loginInfo));
double newFreeSpace = oldFreeSpace - fileSizeOld;
if (oldFreeSpace < fileSizeOld)
{
return -1;
}
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "UpdateFreeSpace";
objCommand.Parameters.AddWithValue("@email", loginInfo[0]);
objCommand.Parameters.AddWithValue("@freeStorage", newFreeSpace);
objDB.DoUpdateUsingCmdObj(objCommand);
//Put file back
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "AddCloudFile";
objCommand.Parameters.AddWithValue("@email", email);
objCommand.Parameters.AddWithValue("@fileName", fileName);
objCommand.Parameters.AddWithValue("@fileType", fileType);
objCommand.Parameters.AddWithValue("@fileSize", fileSizeOld);
objCommand.Parameters.AddWithValue("@fileData", fileData);
objDB.DoUpdateUsingCmdObj(objCommand);
//Delete File From Trash
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "DeleteFileFromTrash";
objCommand.Parameters.AddWithValue("@id", userInfo[1]);
objDB.DoUpdateUsingCmdObj(objCommand);
//Add transaction
objDB = new DBConnect();
objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "AddCloudTransaction";
objCommand.Parameters.AddWithValue("@email", email);
objCommand.Parameters.AddWithValue("@type", "Recover");
objCommand.Parameters.AddWithValue("@fileName", fileName);
objCommand.Parameters.AddWithValue("@time", DateTime.Now);
objDB.DoUpdateUsingCmdObj(objCommand);
}
return response;
}
[WebMethod]
public DataSet getQuestions()
{
DBConnect objDB = new DBConnect();
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "GetCloudQuestions";
DataSet myDS = objDB.GetDataSetUsingCmdObj(objCommand);
return myDS;
}
[WebMethod]
public void askQuestion(string[] loginInfo, string question)
{
DBConnect objDB = new DBConnect();
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "AskCloudQuestion";
objCommand.Parameters.AddWithValue("@email", loginInfo[0]);
objCommand.Parameters.AddWithValue("@question", question);
objDB.DoUpdateUsingCmdObj(objCommand);
}
}
}
<file_sep>/TermProject/StorageOptions.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Class_Library;
namespace TermProject
{
public partial class StorageOptions : System.Web.UI.Page
{
double storage;
string[] loginInfo = new string[2];
string email = "";
int index;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Login"] != null)
{
lblDisplayText.Text = Session["User"].ToString() + "'s Storage Options";
loginInfo[0] = Session["User"].ToString();
loginInfo[1] = Session["Password"].ToString();
email = Session["User"].ToString();
if(Session["Index"] != null)
{
index = Convert.ToInt32(Session["Index"]);
}
// if (!IsPostBack)
// {
stateLoggedIn();
//}
}
else
{
lblDisplayText.Text = "Error: Must Login in";
}
}
protected void btnBack_Click(object sender, EventArgs e)
{
Response.Redirect("Main.aspx");
}
public void stateLoggedIn()
{
rdoStorageOptions.Visible = true;
lblDisplayText2.Text = "";
if (!IsPostBack)
{
storage = Convert.ToDouble(Functions.getUserTotalSpace(loginInfo, email));
storage = storage / 1000000;
if (storage == 100)
{
rdoStorageOptions.SelectedIndex = 0; ;
rdoStorageOptions.SelectedItem.Text = "100 MB (Free) -- Current Plan";
index = 0;
}
else if (storage == 1000)
{
rdoStorageOptions.SelectedIndex = 1; ;
rdoStorageOptions.SelectedItem.Text = "1 GB ($0.99/Month) -- Current Plan";
index = 1;
}
else if (storage == 2000)
{
rdoStorageOptions.SelectedIndex = 2; ;
rdoStorageOptions.SelectedItem.Text = "2 GB ($1.99/Month) -- Current Plan";
index = 2;
}
else if (storage == 5000)
{
rdoStorageOptions.SelectedIndex = 3; ;
rdoStorageOptions.SelectedItem.Text = "5 GB ($2.99/Month) -- Current Plan";
index = 3;
}
else if (storage == 10000)
{
rdoStorageOptions.SelectedIndex = 4; ;
rdoStorageOptions.SelectedItem.Text = "10 GB ($4.99/Month) -- Current Plan";
index = 4;
}
else if (storage == 50000)
{
rdoStorageOptions.SelectedIndex = 5; ;
rdoStorageOptions.SelectedItem.Text = "50 GB ($9.99/Month) -- Current Plan";
index = 5;
}
Session["Index"] = index;
}
}
public void paymentFormOn()
{
lblAddress.Visible = true; lblCardNumber.Visible = true; lblCardType.Visible = true;
lblCity.Visible = true; lblExpiration.Visible = true; lblName.Visible = true; lblSecurityCode.Visible = true;
lblState.Visible = true; lblZipCode.Visible = true; txtAddress.Visible = true; txtCardNumber.Visible = true;
txtCity.Visible = true; txtName.Visible = true; txtSecurityCode.Visible = true; txtZipCode.Visible = true;
ddlCardType.Visible = true; ddlMonth.Visible = true; ddlState.Visible = true; ddlYear.Visible = true;
btnSubmit.Visible = true;
}
public void paymentFormOff()
{
lblAddress.Visible = false; lblCardNumber.Visible = false; lblCardType.Visible = false;
lblCity.Visible = false; lblExpiration.Visible = false; lblName.Visible = false; lblSecurityCode.Visible = false;
lblState.Visible = false; lblZipCode.Visible = false; txtAddress.Visible = false; txtCardNumber.Visible = false;
txtCity.Visible = false; txtName.Visible = false; txtSecurityCode.Visible = false; txtZipCode.Visible = false;
ddlCardType.Visible = false; ddlMonth.Visible = false; ddlState.Visible = false; ddlYear.Visible = false;
btnSubmit.Visible = false;
}
protected void btnChangePlan_Click(object sender, EventArgs e)
{
if (rdoStorageOptions.SelectedIndex == index)
{
lblDisplayText2.Text = "Must choose plan different from current plan";
}
else if (rdoStorageOptions.SelectedIndex == 0)
{
lblDisplayText2.Text = "Plan Successfully changed";
}
else
{
paymentFormOn();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Validations())
{
lblDisplayText2.Text = "Plan Successfully changed";
paymentFormOff();
Functions.changeStoragePlan(loginInfo, email, rdoStorageOptions.SelectedIndex);
}
}
public bool Validations()
{
if (txtAddress.Text == String.Empty ||
txtCardNumber.Text == String.Empty ||
txtCity.Text == String.Empty||
txtName.Text == String.Empty ||
txtSecurityCode.Text == String.Empty ||
txtZipCode.Text == String.Empty
)
{
lblDisplayText2.Text = "Enter all fields above!";
return false;
}
else
{
return true;
}
}
}
}<file_sep>/TermProject/Trash.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Class_Library;
namespace TermProject
{
public partial class Trash : System.Web.UI.Page
{
string[] loginInfo = new string[2];
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Login"] != null)
{
lblDisplayText.Text = Session["User"].ToString() + "'s Trash Can";
loginInfo[0] = Session["User"].ToString();
loginInfo[1] = Session["Password"].ToString();
gvTrash.DataSource = Functions.getUserTrash(loginInfo, Session["User"].ToString());
gvTrash.DataBind();
}
else
{
lblDisplayText.Text = "Error: Must Login in";
}
}
protected void btnBack_Click(object sender, EventArgs e)
{
Response.Redirect("Main.aspx");
}
protected void gvTrash_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("recover"))
{
int index = Convert.ToInt32(e.CommandArgument);
string id = gvTrash.Rows[index].Cells[1].Text;
string[] userInfo = new string[2];
userInfo[0] = Session["User"].ToString(); userInfo[1] = id;
int response = Functions.recoverFile(loginInfo, userInfo);
gvTrash.DataSource = Functions.getUserTrash(loginInfo, Session["User"].ToString());
gvTrash.DataBind();
if (response == -1)
{
lblDisplayText2.Text = "Not enough free space to recover file.";
}
}
}
}
}<file_sep>/Class Library/CloudStorageObject.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Class_Library
{
public class CloudStorageObject
{
private List<File> cloudItems = new List<File>();
public CloudStorageObject()
{
}
public List<File> LineItems
{
get { return cloudItems; }
set { cloudItems = value; }
}
public void Add(File file)
{
if (file != null)
{
cloudItems.Add(file);
}
}
public void clear()
{
cloudItems.Clear();
}
}
}<file_sep>/Class Library/File.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
namespace Class_Library
{
public class File
{
private string email;
private string fileName;
private string fileType;
private double fileSize;
private byte[] fileData;
public File()
{
}
public File(string email, string fileName, string fileType, double fileSize, byte[] fileData)
{
this.email = email;
this.fileName = fileName;
this.fileType = fileType;
this.fileSize = fileSize;
this.fileData = fileData;
}
public string Email
{
get { return email; }
set { email = value; }
}
public string FileName
{
get { return fileName; }
set { fileName = value; }
}
public string FileType
{
get { return fileType; }
set { fileType = value; }
}
public double FileSize
{
get { return fileSize; }
set { fileSize = value; }
}
public byte[] FileData
{
get { return fileData; }
set { fileData = value; }
}
}
}<file_sep>/Class Library/UserInformation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Class_Library
{
public class UserInformation
{
public string name { get; set; }
public string email { get; set; }
public string password { get; set; }
public string passwordConfirm { get; set; }
}
}<file_sep>/TermProject/Login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Class_Library;
namespace TermProject
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && Request.Cookies["Login_Cookie"] != null)
{
HttpCookie cookie = Request.Cookies["Login_Cookie"];
lblEmail.Text = "Welcome back " + cookie.Values["userName"].ToString() + "!";
txtEmail.Text = cookie.Values["userName"].ToString();
txtEmail.Visible = false; btnRegister.Visible = false; btnOtherUser.Visible = true;
}
else
{
lblEmail.Text = "Email Address:";
txtEmail.Visible = true; btnRegister.Visible = true; btnOtherUser.Visible = false;
}
}
protected void btnRegister_Click(object sender, EventArgs e)
{
Response.Redirect("Registration.aspx");
}
protected void btnSignin_Click(object sender, EventArgs e)
{
string email = txtEmail.Text;
string password = <PASSWORD>.Text;
string response = Functions.attemptLogin(email, password);
if (Validations())
{
if (response == "Success User" || response == "Success Admin")
{
// Adds cookie if remember me is checked
if (chkRemember.Checked)
{
HttpCookie myCookie = new HttpCookie("Login_Cookie");
myCookie.Values["userName"] = txtEmail.Text;
Response.Cookies.Add(myCookie);
}
// Deletes cookie if remember me is not checked
else
{
if (Request.Cookies["Login_Cookie"] != null)
{
HttpCookie myCookie = new HttpCookie("Login_Cookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
}
Session["Login"] = response;
Session["User"] = email;
Session["Password"] = <PASSWORD>;
Response.Redirect("Main.aspx");
}
else
{
lblDisplayText1.Text = response;
}
}
}
protected void btnOtherUser_Click(object sender, EventArgs e)
{
// Deletes cookie if Not Me is clicked
HttpCookie myCookie = new HttpCookie("Login_Cookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
txtEmail.Text = "";
}
public bool Validations()
{
if (txtEmail.Text == String.Empty ||
txtPassword.Text == String.Empty)
{
lblDisplayText2.Text = "Enter all fields above!";
return false;
}
else
{
return true;
}
}
}
}<file_sep>/TermProject/Registration.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Class_Library;
namespace TermProject
{
public partial class Registraion : System.Web.UI.Page
{
string[] loginInfo = new string[2];
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Login"] != null)
{
loginInfo[0] = Session["User"].ToString();
loginInfo[1] = Session["Password"].ToString();
if (Session["Login"].ToString() == "Success Admin")
{
btnRegister.Text = "Register Admin";
lblRemember.Visible = false;
chkRemember.Checked = false;
chkRemember.Visible = false;
}
}
}
protected void btnBack_Click(object sender, EventArgs e)
{
Session["Login"] = null;
Response.Redirect("Login.aspx");
}
protected void btnRegister_Click1(object sender, EventArgs e)
{
string result = "";
if (Validation())
{
if (txtPassword.Text != txtConfirm.Text)
{
lblDisplayText.Text = "Passwords must match";
}
else
{
if (Session["Login"] != null)
{
if (Session["Login"].ToString() == "Success Admin")
{
result = Functions.addAdmin(loginInfo, txtName.Text, txtEmail.Text,
txtPassword.Text, txtPhone.Text);
}
}
else
{
result = Functions.addUser(txtName.Text, txtEmail.Text,
txtPassword.Text, txtPhone.Text);
}
lblDisplayText.Text = result;
// Adds cookie if remember me is checked
if (chkRemember.Checked)
{
HttpCookie myCookie = new HttpCookie("Login_Cookie");
myCookie.Values["userName"] = txtEmail.Text;
Response.Cookies.Add(myCookie);
}
// Deletes cookie if remember me is not checked
else
{
if (Request.Cookies["Login_Cookie"] != null)
{
HttpCookie myCookie = new HttpCookie("Login_Cookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
}
}
}
}
public Boolean Validation()
{
if (txtName.Text == String.Empty ||
txtEmail.Text == String.Empty ||
txtPassword.Text == String.Empty ||
txtConfirm.Text == String.Empty ||
txtPhone.Text == String.Empty)
{
lblDisplayText.Text = "Enter all fields above!";
return false;
}
else
{
return true;
}
}
}
}<file_sep>/TermProject/Main.aspx.cs
using Class_Library;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TermProject
{
public partial class Main : System.Web.UI.Page
{
string[] loginInfo = new string[2];
CloudStorageObject cloudObj = new CloudStorageObject();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Login"] != null)
{
if (Session["cloudObj"] != null)
{
cloudObj = (CloudStorageObject)Session["cloudObj"];
}
lblDisplayText.Text = "Welcome " + Session["User"].ToString() + "!";
if (Session["Login"].ToString() == "Success Admin")
{
stateAdmin();
}
else if (Session["Login"].ToString() == "Success User")
{
stateUser();
}
loginInfo[0] = Session["User"].ToString();
loginInfo[1] = Session["Password"].ToString();
}
else
{
lblDisplayText.Text = "Error: Must Login in";
}
}
protected void btnBack_Click(object sender, EventArgs e)
{
Response.Redirect("Login.aspx");
}
protected void btnAddAdmin_Click(object sender, EventArgs e)
{
Response.Redirect("Registration.aspx");
}
public void stateUser()
{
btnUserEditUser.Visible = true;
btnMyFiles.Visible = true;
btnDeleteFiles.Visible = true;
btnStorageOptions.Visible = true;
btnViewTrash.Visible = true;
btnAskQuestion.Visible = true;
}
public void stateAdmin()
{
btnAddAdmin.Visible = true;
btnViewTransactions.Visible = true;
btnAdminEditUser.Visible = true;
btnDeleteUser.Visible = true;
btnAdminViewUserFiles.Visible = true;
btnAnswerQuestion.Visible = true;
}
protected void btnFile_Click(object sender, EventArgs e)
{
userFormsOff();
int fileSize;
string fileType, fileName;
if (fileUp.HasFile)
{
fileSize = fileUp.PostedFile.ContentLength;
byte[] fileData = new byte[fileSize];
fileUp.PostedFile.InputStream.Read(fileData, 0, fileSize);
fileName = fileUp.PostedFile.FileName;
fileType = fileUp.PostedFile.ContentType;
File file = new File();
file.Email = Session["User"].ToString();
file.FileName = fileName;
file.FileType = fileType;
file.FileSize = fileSize;
file.FileData = fileData;
cloudObj.Add(file);
string response = Functions.fileUpload(loginInfo, Session["User"].ToString(), fileName, fileType,
fileSize, fileData);
lblDisplayText.Text = response;
stateUser();
gvUserFiles.DataSource = Functions.getFilesByUser(loginInfo, Session["User"].ToString());
gvUserFiles.DataBind(); gvUserFiles.Visible = true; lblFile.Visible = true; fileUp.Visible = true;
lblFreeUserSpace.Visible = true; btnFile.Visible = true;
lblFreeUserSpace.Text = "Free Space Remaining: " +
Functions.getUserFreeSpace(loginInfo, Session["User"].ToString()) +
" Bytes";
}
}
protected void gvTransactions_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnViewTransactions_Click(object sender, EventArgs e)
{
adminFormsOff();
dropUser.DataSource = Functions.getCloudUsers(loginInfo);
dropUser.DataTextField = "Email";
dropUser.DataBind();
transactionFormOn();
}
protected void btnGetTransactions_Click(object sender, EventArgs e)
{
gvTransactions.DataSource = Functions.getTransactions(loginInfo, dropUser.SelectedItem.ToString(),
dropTimePeriod.SelectedItem.ToString());
gvTransactions.DataBind();
gvTransactions.Visible = true;
}
public void transactionFormOn()
{
lblSelectUser.Visible = true;
dropUser.Visible = true; lblSelectTimePeriod.Visible = true;
dropTimePeriod.Visible = true;
btnGetTransactions.Visible = true;
}
public void adminFormsOff()
{
lblSelectUser.Visible = false;
dropUser.Visible = false; lblSelectTimePeriod.Visible = false;
dropTimePeriod.Visible = false;
btnGetTransactions.Visible = false;
gvTransactions.Visible = false;
gvAdminModify.Visible = false;
btnDeleteSelection.Visible = false;
gvDelete.Visible = false;
gvAdminUserFilesView.Visible = false; lblSelectUserFA.Visible = false;
btnGetUserFilesView.Visible = false;
gvQuestions.Visible = false;
lblQuestion.Visible = false;
txtQuestions.Visible = false; btnAnswer.Visible = false;
}
public void userFormsOff()
{
gvUserFiles.Visible = false;
lblFile.Visible = false; fileUp.Visible = false;
lblFreeUserSpace.Visible = false; btnFile.Visible = false;
gvUserModify.Visible = false;
btnDeleteFile.Visible = false;
gvDeleteFile.Visible = false;
gvQuestions.Visible = false;
lblQuestion.Visible = false;
txtQuestions.Visible = false; btnAsk.Visible = false;
}
protected void gvAdminModify_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void gvAdminModify_PageIndexChanging(Object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
{
gvAdminModify.PageIndex = e.NewPageIndex;
gvAdminModify.DataSource = Functions.getCloudUsersInfo(loginInfo);
gvAdminModify.DataBind();
}
protected void gvAdminModify_RowEditing(Object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
{
gvAdminModify.EditIndex = e.NewEditIndex;
gvAdminModify.DataSource = Functions.getCloudUsersInfo(loginInfo);
gvAdminModify.DataBind();
}
protected void gvAdminModify_RowCancelingEdit(Object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
{
gvAdminModify.EditIndex = -1;
gvAdminModify.DataSource = Functions.getCloudUsersInfo(loginInfo);
gvAdminModify.DataBind();
}
protected void gvAdminModify_RowUpdating(Object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
int rowIndex = e.RowIndex;
string email = gvAdminModify.Rows[rowIndex].Cells[2].Text;
TextBox passwordBox = (TextBox)gvAdminModify.Rows[rowIndex].Cells[3].Controls[0];
TextBox phoneBox = (TextBox)gvAdminModify.Rows[rowIndex].Cells[4].Controls[0];
TextBox totalBox = (TextBox)gvAdminModify.Rows[rowIndex].Cells[6].Controls[0];
Functions.adminUpdateUser(loginInfo, email, passwordBox.Text, phoneBox.Text, totalBox.Text);
gvAdminModify.EditIndex = -1;
gvAdminModify.DataSource = Functions.getCloudUsersInfo(loginInfo);
gvAdminModify.DataBind();
}
protected void btnAdminEditUser_Click(object sender, EventArgs e)
{
adminFormsOff();
gvAdminModify.Visible = true;
gvAdminModify.DataSource = Functions.getCloudUsersInfo(loginInfo);
gvAdminModify.DataBind();
}
protected void btnDeleteUser_Click(object sender, EventArgs e)
{
adminFormsOff();
gvDelete.Visible = true;
gvDelete.DataSource = Functions.getCloudUsersInfo(loginInfo);
gvDelete.DataBind();
btnDeleteSelection.Visible = true;
}
protected void btnDeleteSelection_Click(object sender, EventArgs e)
{
int checkCount = 0;
for (int row = 0; row < gvDelete.Rows.Count; row++)
{
CheckBox CBox = (CheckBox)gvDelete.Rows[row].FindControl("chkSelect");
if (CBox.Checked)
{
checkCount++;
string email = gvDelete.Rows[row].Cells[3].Text;
Functions.deleteUser(loginInfo, email);
}
}
if (checkCount == 0)
{
//tell user to check something
}
else
{
gvDelete.DataSource = Functions.getCloudUsersInfo(loginInfo);
gvDelete.DataBind();
}
}
protected void btnUserEditUser_Click(object sender, EventArgs e)
{
userFormsOff();
gvUserModify.Visible = true;
gvUserModify.DataSource = Functions.getSingleUserInfo(loginInfo, Session["User"].ToString());
gvUserModify.DataBind();
}
protected void gvUserModify_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void gvUserModify_RowEditing(Object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
{
gvUserModify.EditIndex = e.NewEditIndex;
gvUserModify.DataSource = Functions.getSingleUserInfo(loginInfo, Session["User"].ToString());
gvUserModify.DataBind();
}
protected void gvUserModify_RowCancelingEdit(Object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
{
gvUserModify.EditIndex = -1;
gvUserModify.DataSource = Functions.getSingleUserInfo(loginInfo, Session["User"].ToString());
gvUserModify.DataBind();
}
protected void gvUserModify_RowUpdating(Object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
int rowIndex = e.RowIndex;
int id = Convert.ToInt32(gvUserModify.Rows[rowIndex].Cells[0].Text);
TextBox nameBox = (TextBox)gvUserModify.Rows[rowIndex].Cells[1].Controls[0];
TextBox emailBox = (TextBox)gvUserModify.Rows[rowIndex].Cells[2].Controls[0];
TextBox passwordBox = (TextBox)gvUserModify.Rows[rowIndex].Cells[3].Controls[0];
TextBox phoneBox = (TextBox)gvUserModify.Rows[rowIndex].Cells[4].Controls[0];
Functions.userUpdateUser(loginInfo, id, nameBox.Text, emailBox.Text, passwordBox.Text, phoneBox.Text);
gvUserModify.EditIndex = -1;
gvUserModify.DataSource = Functions.getSingleUserInfo(loginInfo, Session["User"].ToString());
gvUserModify.DataBind();
}
protected void btnMyFiles_Click(object sender, EventArgs e)
{
userFormsOff();
lblFile.Visible = true; fileUp.Visible = true;
lblFreeUserSpace.Visible = true; btnFile.Visible = true;
lblFreeUserSpace.Text = "Free Space Remaining: " +
Functions.getUserFreeSpace(loginInfo, Session["User"].ToString()) +
" Bytes";
gvUserFiles.DataSource = Functions.getFilesByUser(loginInfo, Session["User"].ToString());
gvUserFiles.DataBind(); gvUserFiles.Visible = true;
}
protected void btnDeleteFiles_Click(object sender, EventArgs e)
{
userFormsOff();
gvDeleteFile.Visible = true;
gvDeleteFile.DataSource = Functions.getFilesByUser(loginInfo, Session["User"].ToString());
gvDeleteFile.DataBind();
btnDeleteFile.Visible = true;
}
protected void btnDeleteFile_Click(object sender, EventArgs e)
{
int checkCount = 0;
for (int row = 0; row < gvDeleteFile.Rows.Count; row++)
{
CheckBox CBox = (CheckBox)gvDeleteFile.Rows[row].FindControl("chkSelectFile");
if (CBox.Checked)
{
checkCount++;
string fileName = gvDeleteFile.Rows[row].Cells[1].Text;
string fileSize = gvDeleteFile.Rows[row].Cells[3].Text;
Functions.deleteFile(loginInfo, fileName, fileSize);
}
}
if (checkCount == 0)
{
//tell user to check something
}
else
{
gvDeleteFile.DataSource = Functions.getFilesByUser(loginInfo, Session["User"].ToString());
gvDeleteFile.DataBind();
}
}
protected void btnStorageOptions_Click(object sender, EventArgs e)
{
Response.Redirect("StorageOptions.aspx");
}
protected void btnViewTrash_Click(object sender, EventArgs e)
{
Response.Redirect("Trash.aspx");
}
protected void btnViewUserFiles_Click(object sender, EventArgs e)
{
adminFormsOff();
ddlAdminUserFilesView.DataSource = Functions.getCloudUsers(loginInfo);
ddlAdminUserFilesView.DataTextField = "Email";
ddlAdminUserFilesView.DataBind(); ddlAdminUserFilesView.Visible = true;
gvAdminUserFilesView.Visible = true; lblSelectUserFA.Visible = true;
btnGetUserFilesView.Visible = true;
}
protected void btnGetUserFiles_Click(object sender, EventArgs e)
{
gvAdminUserFilesView.DataSource = Functions.getFilesByUser(loginInfo, ddlAdminUserFilesView.SelectedItem.ToString());
gvAdminUserFilesView.DataBind(); gvAdminUserFilesView.Visible = true;
}
protected void btnaskQuestion_Click(object sender, EventArgs e)
{
userFormsOff();
gvQuestions.Visible = true;
gvQuestions.DataSource = Functions.getQuestions();
gvQuestions.DataBind();
lblQuestion.Visible = true; lblQuestion.Text = "Ask Question: ";
txtQuestions.Visible = true; btnAsk.Visible = true;
}
protected void btnAnswerQuestion_Click(object sender, EventArgs e)
{
adminFormsOff();
gvQuestions.Visible = true;
gvQuestions.DataSource = Functions.getQuestions();
gvQuestions.DataBind();
lblQuestion.Visible = true; lblQuestion.Text = "Answer Question: ";
txtQuestions.Visible = true; btnAnswer.Visible = true;
}
protected void btnAsk_Click(object sender, EventArgs e)
{
Functions.askQuestion(loginInfo, txtQuestions.Text);
gvQuestions.DataSource = Functions.getQuestions();
gvQuestions.DataBind();
}
protected void btnAnswer_Click(object sender, EventArgs e)
{
}
}
}<file_sep>/Class Library/Functions.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utilities;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace Class_Library
{
public partial class Functions : System.Web.UI.Page
{
CloudStorageObject cloudObj = new CloudStorageObject();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["cloudObj"] != null)
{
cloudObj = (CloudStorageObject)Session["cloudObj"];
}
}
public static string attemptLogin(string email, string password)
{
string[] loginInfo = new string[2];
string response = "";
loginInfo[0] = email; loginInfo[1] = password;
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
int result = pxy.attemptLogin(loginInfo);
if (result == -1)
{
response = "Not Found";
}
else if (result == 0)
{
response = "Invalid Password";
}
else if (result == 1)
{
response = "Success User";
}
else if (result == 2)
{
response = "Success Admin";
}
return response;
}
public static string addUser(string name, string email, string password, string phone)
{
string[] userInfo = new string[4];
string response = "";
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
userInfo[0] = name; userInfo[1] = email;
userInfo[2] = password; userInfo[3] = phone;
int result = pxy.addUser(userInfo);
if (result == 0)
{
response = "User successfully registered!";
}
else if (result == -1)
{
response = "Error: User already exists";
}
return response;
}
public static string addAdmin(string[] loginInfo, string name, string email, string password, string phone)
{
string[] userInfo = new string[4];
string response = "";
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
userInfo[0] = name; userInfo[1] = email;
userInfo[2] = password; userInfo[3] = phone;
int result = pxy.addAdmin(loginInfo, userInfo);
if (result == 0)
{
response = "Admin successfully registered!";
}
else if (result == -1)
{
response = "Error: Admin already exists";
}
return response;
}
public static string fileUpload(string[] loginInfo, string email, string fileName, string fileType, int fileSize, byte[] fileData)
{
string response = "";
string[] fileInfo = new string[4];
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
fileInfo[0] = email; fileInfo[1] = fileName;
fileInfo[2] = fileType; fileInfo[3] = fileSize.ToString();
int result = pxy.addFile(loginInfo, fileInfo, fileData);
if (result == 0)
{
response = "File successfully added!";
}
else if (result == 1)
{
response = "File updated, previous version moved to trash";
}
else if (result == -1)
{
response = "Error: Not Enough Free Storage";
}
return response;
}
public static DataSet getFilesByUser(string[] loginInfo, string email)
{
string[] userInfo = new string[1];
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
userInfo[0] = email;
DataSet myDS = pxy.getFilesByUser(loginInfo, userInfo);
return myDS;
}
public static string getUserFreeSpace(string[] loginInfo, string email)
{
string response = "";
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
string[] userInfo = new string[1];
userInfo[0] = email;
response = pxy.getUserFreeStorage(loginInfo, userInfo).ToString();
return response;
}
public static string getUserTotalSpace(string[] loginInfo, string email)
{
string response = "";
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
string[] userInfo = new string[1];
userInfo[0] = email;
response = pxy.getUserTotalStorage(loginInfo, userInfo).ToString();
return response;
}
public static DataSet getTransactions(string[] loginInfo, string user, string timePeriod)
{
string[] userInfo = new string[2];
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
userInfo[0] = user; userInfo[1] = timePeriod;
DataSet myDS = pxy.getTransactions(loginInfo, userInfo);
return myDS;
}
public static DataSet getCloudUsers(string[] loginInfo)
{
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
DataSet myDS = pxy.getCloudUsers(loginInfo);
return myDS;
}
public static DataSet getCloudUsersInfo(string[] loginInfo)
{
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
DataSet myDS = pxy.getCloudUsersInfo(loginInfo);
return myDS;
}
public static int adminUpdateUser(string[] loginInfo, string email, string password, string phone, string total)
{
string[] userInfo = new string[4];
userInfo[0] = email;
userInfo[1] = password;
userInfo[2] = phone;
userInfo[3] = total;
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
int response = pxy.adminUpdateUser(loginInfo, userInfo);
return response;
}
public static int deleteUser(string[] loginInfo, string email)
{
string[] userInfo = new string[1];
userInfo[0] = email;
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
int response = pxy.deleteUser(loginInfo, userInfo);
return response;
}
public static DataSet getSingleUserInfo(string[] loginInfo, string email)
{
string[] userInfo = new string[1];
userInfo[0] = email;
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
DataSet myDS = pxy.getSingleUserInfo(loginInfo, userInfo);
return myDS;
}
public static int userUpdateUser(string[] loginInfo, int id, string name, string email, string password, string phone)
{
string[] userInfo = new string[5];
userInfo[0] = id.ToString();
userInfo[1] = name;
userInfo[2] = email;
userInfo[3] = password;
userInfo[4] = phone;
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
int response = pxy.userUpdateUser(loginInfo, userInfo);
return response;
}
public static int deleteFile(string[] loginInfo, string fileName, string fileSize)
{
string[] userInfo = new string[3];
userInfo[0] = fileName;
userInfo[1] = fileSize;
userInfo[2] = "delete";
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
int response = pxy.deleteFile(loginInfo, userInfo);
return response;
}
public static DataSet getUserTrash(string[] loginInfo, string email)
{
string[] userInfo = new string[1];
userInfo[0] = email;
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
DataSet myDS = pxy.getUserTrash(loginInfo, userInfo);
return myDS;
}
public static int changeStoragePlan(string[] loginInfo, string email, int plan)
{
int response = 0;
double storage = 0;
string[] userInfo = new string[2];
if (plan == 0) {storage = 100000000; }
else if (plan == 1) { storage = 1000000000; }
else if (plan == 2) { storage = 2000000000; }
else if (plan == 3) { storage = 5000000000; }
else if (plan == 4) { storage = 10000000000; }
else if (plan == 5) { storage = 50000000000; }
userInfo[0] = email; userInfo[1] = storage.ToString(); ;
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
response = pxy.changeStoragePlan(loginInfo, userInfo);
return response;
}
public static int recoverFile(string[] loginInfo, string[] userInfo)
{
int response = 0;
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
response = pxy.recoverFile(loginInfo, userInfo);
return response;
}
public static DataSet getQuestions()
{
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
DataSet myDs = pxy.getQuestions();
return myDs;
}
public static void askQuestion(string[] loginInfo, string question)
{
CloudSVCRef.CloudSVC pxy = new CloudSVCRef.CloudSVC();
pxy.askQuestion(loginInfo, question);
}
}
} | ae4a55eb6b3acca96dd86fa81de682f2d0ba32b2 | [
"C#"
] | 10 | C# | tiamahone/TermProject1 | 1f17df1448060563e7a8fd1f09e0c04b108ea442 | 0111b6a03791687210487b9c1ae5bbc14d218253 | |
refs/heads/master | <repo_name>nedirflores/testeBDR<file_sep>/ajax/clientes_fotos.php
<?php
// verifica se foi enviado um arquivo
if(isset($_FILES['fotoCliente']['name']) && $_FILES["fotoCliente"]["error"] == 0)
{
// echo "Você enviou o arquivo: <strong>" . $_FILES['arquivo']['name'] . "</strong><br />";
// echo "Este arquivo é do tipo: <strong>" . $_FILES['arquivo']['type'] . "</strong><br />";
// echo "Temporáriamente foi salvo em: <strong>" . $_FILES['arquivo']['tmp_name'] . "</strong><br />";
// echo "Seu tamanho é: <strong>" . $_FILES['arquivo']['size'] . "</strong> Bytes<br /><br />";
$arquivo_tmp = $_FILES['fotoCliente']['tmp_name'];
$nome = $_FILES['fotoCliente']['name'];
// Pega a extensao
$extensao = strrchr($nome, '.');
// Converte a extensao para mimusculo
$extensao = strtolower($extensao);
// Somente imagens, .jpg;.jpeg;.gif;.png
// Aqui eu enfilero as extesões permitidas e separo por ';'
// Isso server apenas para eu poder pesquisar dentro desta String
if(strstr('.jpg;.jpeg;.gif;.png;.jfif', $extensao))
{
// Cria um nome único para esta imagem
// Evita que duplique as imagens no servidor.
$novoNome = rand(111,999999999) . $extensao;
// Concatena a pasta com o nome
$destino = '../fotos/' . $novoNome;
// tenta mover o arquivo para o destino
if( @move_uploaded_file( $arquivo_tmp, $destino ))
{
echo json_encode([ 'status' => true, 'nameFile' => $novoNome ]);
}
else
echo json_encode([ 'status' => false, 'nameFile' => "" ]);
}
else{
echo json_encode([ 'status' => false, 'nameFile' => "" ]);
}
}
else
{
echo json_encode([ 'status' => false, 'nameFile' => "" ]);
}
<file_sep>/index.php
<?php
include_once('./bd/conexao.php');
$arrStatus = [
0 => '<span style="width:60px" class="btn btn-xs btn-danger "> Inativo </span>',
1 => '<span style="width:60px" class="btn btn-xs btn-info "> Ativo </span>'
];
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="bootstrap/css/bootstrap-theme.css" />
<link rel="stylesheet" href="bootstrap/css/bootstrap.css" />
<link href="bootstrap/css/select2.min.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="js/jquery.mask.js"></script>
<script type="text/javascript" src="js/funcoes.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.js" ></script>
<script type="text/javascript" src="bootstrap/js/npm.js"></script>
<script src="bootstrap/js/select2.min.js"></script>
<link rel="shortcut icon" href="imgs/favicon.png" />
<title>Teste BDR</title>
</head>
<body>
<div class="container-fluid">
<div class="col-md-12">
<div class="row">
<center>
<h1>Clientes</h1>
<table style="width: 100%" class="">
<header>
<tr>
<th style="float: right">
<button class="btn btn-info btn-sm" data-toggle="modal" data-target="#modalEditar" onclick="clienteIncluir()"> Novo Cliente </button>
</th>
</tr>
</header>
</table> <br>
<div id='page-data'>
<br><br>
</center>
</div>
</div>
</div>
</body>
</html>
<div class="modal fade" id="modalEditar" role="dialog" aria-labelledby="editarModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="editarModalLabel">Editar Cliente</h3>
</div>
<div class="modal-body">
<form method="post" enctype="multipart/form-data">
<table class="">
<input type="hidden" id="idCliente" name="idCliente"> </td>
<input type="hidden" id="acao" name="acao"> </td>
<tr>
<td style="width: 80px">Nome</td>
<td><input type="text" class="form-control" id="nmCliente" name="nmCliente" style="width: 100%"> </td>
</tr>
<tr> <td colspan="2"> </td> </tr>
<tr>
<td style="width: 80px">Email</td>
<td><input type="text" class="form-control" id="emailCliente" name="emailCliente" onblur="checarEmail();" style="width: 100%"> </td>
</tr>
<tr> <td colspan="2"> </td> </tr>
<tr>
<td style="width: 80px">Telefone</td>
<td><input type="text" class="form-control" id="foneCliente" name="foneCliente" maxlength="14" pattern="\([0-9]{2}\)[\s][0-9]{4}-[0-9]{4,5}" style="width: 50%"> </td>
</tr>
<tr> <td colspan="2"> </td> </tr>
<tr>
<td style="width: 80px">Foto</td>
<td><img name="clienteImagem" id="clienteImagem" class="img-circle" src="" width="150px" height="150px"></td>
</tr>
<tr> <td colspan="2"> </td> </tr>
<tr>
<td style="width: 80px">Arquivo</td>
<td> <input type="file" class="form-control" id="fotoCliente" name="fotoCliente" style="width: 100%"> </td>
</tr>
</table>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="clienteSalvar();">Salvar</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="modalExcluir" role="dialog" aria-labelledby="excluirModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="excluirModalLabel">Excluir Cliente</h3>
</div>
<div class="modal-body">
<form class="table-form">
<table class="">
<tr>
<td style="width: 80px">ID</td>
<td><input type="text" class="form-control" id="idClientex" name="idClientex" style="width: 150px" readonly="true"> </td>
</tr>
<tr> <td colspan="2"> </td> </tr>
<tr>
<td style="width: 80px">Nome</td>
<td><input type="text" class="form-control" id="nmClientex" name="nmClientex" style="width: 250px" readonly="true"> </td>
</tr>
<tr> <td colspan="2"> </td> </tr>
<tr>
<td style="width: 80px">Email</td>
<td><input type="text" class="form-control" id="emailClientex" name="emailClientex" style="width: 250px" readonly="true"> </td>
</tr>
<tr> <td colspan="2"> </td> </tr>
</table>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
<button type="button" class="btn btn-primary" onclick="clienteExcluirConfirma();" data-dismiss="modal">Excluir</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$("#foneCliente").mask("(00) 00000-0009");
function checarEmail(){
if( document.forms[0].emailCliente.value==""
|| document.forms[0].emailCliente.value.indexOf('@')==-1
|| document.forms[0].emailCliente.value.indexOf('.')==-1 )
{
mostraDialogo( "E-MAIL", "Por favor, informe um E-MAIL válido!" , "warning", );
$("#page-data").focus();
}
}
function listar() {
$.ajax({
url: "./ajax/clientes_lista.php",
type: "POST",
dataType: "html",
success: function (res) {
$("#page-data").html(res);
}
});
}
function clienteEditar( idRef ) {
$.ajax({
url: "./ajax/clientes_crud.php",
type: "POST",
dataType: "json",
data: { acao: 1, id: idRef },
success: function (res) {
$("#acao").val("2");
$("#idCliente").val(res.Id);
$("#nmCliente").val(res.nome);
$("#emailCliente").val(res.email);
$("#foneCliente").val(res.telefone);
$('#clienteImagem').attr('src', 'fotos/' + res.foto);
$('#fotoCliente').val('');
}
});
}
var nmArqFoto;
var formEditar;
function readURL(input) {
if(input.files.length > 4) { }
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#clienteImagem').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$('#fotoCliente').change(function (event) {
readURL(this);
formEditar = new FormData();
formEditar.append('fotoCliente', event.target.files[0]); // para apenas 1 arquivo
//var name = event.target.files[0].content.name; // para capturar o nome do arquivo com sua extenção
});
function clienteSalvar( ) {
nmArqFoto = "";
if ( $('#fotoCliente').val() != null && $('#fotoCliente').val() !== '' ){
if ( $("#acao").val() === '2' ){
$.ajax({
url: "./ajax/clientes_crud.php",
type: "POST",
dataType: "json",
data: { acao: 5, id: $("#idCliente").val() },
success: function (res) {
if ( res.status == true ){
//mostraDialogo( "Foto", "Excluida com sucesso!" , "info", );
} else {
//mostraDialogo( "Foto", res.erro , "danger", );
}
}
});
}
$.ajax({
url: "./ajax/clientes_fotos.php",
type: "POST",
dataType: "json",
processData: false,
contentType: false,
data: formEditar,
success: function (res) {
nmArqFoto = res.nameFile;
$.ajax({
url: "./ajax/clientes_crud.php",
type: "POST",
dataType: "json",
data: {
acao: $("#acao").val(),
id: $("#idCliente").val(),
nome: $("#nmCliente").val(),
email: $("#emailCliente").val(),
telefone: $("#foneCliente").val(),
foto: nmArqFoto,
},
success: function (res) {
if ( res.status == true ){
mostraDialogo( "Cliente", "Salvo com sucesso!" , "info", );
listar();
} else {
mostraDialogo( "Cliente", res.erro , "danger", );
}
}
});
}
});
} else {
$.ajax({
url: "./ajax/clientes_crud.php",
type: "POST",
dataType: "json",
data: {
acao: $("#acao").val(),
id: $("#idCliente").val(),
nome: $("#nmCliente").val(),
email: $("#emailCliente").val(),
telefone: $("#foneCliente").val(),
foto: nmArqFoto,
},
success: function (res) {
if ( res.status == true ){
mostraDialogo( "Cliente", "Salvo com sucesso!" , "info", );
listar();
} else {
mostraDialogo( "Cliente", res.erro , "danger", );
}
}
});
}
}
function clienteIncluir() {
$("#acao").val("3");
$("#idCliente").val("");
$("#nmCliente").val("");
$("#emailCliente").val("");
$("#foneCliente").val("");
$('#clienteImagem').attr("src", "");
$('#fotoCliente').val("");
}
function clienteExcluir( idRef ) {
$.ajax({
url: "./ajax/clientes_crud.php",
type: "POST",
dataType: "json",
data: { acao: 1, id: idRef },
success: function (res) {
$("#idClientex").val(res.Id);
$("#nmClientex").val(res.nome);
$("#emailClientex").val(res.email);
}
});
}
function clienteExcluirConfirma() {
var idRef = $("#idClientex").val();
$.ajax({
url: "./ajax/clientes_crud.php",
type: "POST",
dataType: "json",
data: { acao: 4, id: idRef },
success: function (res) {
mostraDialogo( "Cliente", "Excluido com sucesso!", "danger", );
listar();
}
});
}
listar();
</script>
<file_sep>/bd/conexao.php
<?php
// constantes com as credenciais de acesso ao banco MySQL
define('DB_HOST', 'localhost');
define('DB_NAME', 'basebdr');
define('DB_USER', 'user');
define('DB_PASS', '<PASSWORD>');
//Criar a conexao
$conn = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
if(!$conn){
die("Falha na conexao: " . mysqli_connect_error());
}else{
//echo "Conexao realizada com sucesso";
}
?>
<file_sep>/ajax/clientes_lista.php
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<?php
session_start();
include_once('../bd/conexao.php');
header( "Content-type: text/html; charset=utf-8" );
/* Iniciando o retorno */
$res = new StdClass();
$res->html = "";
$res->html .= "<table class='table table-bordered table-condensed table-hover table-responsive'>";
$res->html .= " <header>";
$res->html .= " <tr style='background-color: activecaption'>";
$res->html .= " <th style='text-align: center'>Foto</th>";
//$res->html .= " <th style='text-align: center'>Id</th>";
$res->html .= " <th style='text-align: left '>Nome</th>";
$res->html .= " <th style='text-align: left '>eMail</th>";
$res->html .= " <th style='text-align: left '>Telefone</th>";
$res->html .= " <th style='text-align: center'>Ações</th>";
$res->html .= " </tr>";
$res->html .= " </header>";
$sql = "SELECT * FROM clientes WHERE 1";
$stmt = $conn->prepare($sql);
$stmt->execute();
$clientes = $stmt->fetchAll( $conn::FETCH_ASSOC );
if ( count($clientes) > 0 ){
for ( $x = 0; $x < count($clientes); $x++ ){
$cliente = $clientes[$x];
$res->html .= "<tr>";
$res->html .= " <td style='text-align: center'><img class='img-circle' height='30px' width='30px' src='fotos/".$cliente['foto']."' /></td>";
//$res->html .= " <td style='text-align: center'>" . $cliente["id"] . "</td>";
$res->html .= " <td style='text-align: left'>" . $cliente["nome"] . "</td>";
$res->html .= " <td style='text-align: left'>" . $cliente["email"] . "</td>";
$res->html .= " <td style='text-align: left'>" . $cliente["telefone"] . "</td>";
$res->html .= " <td style='text-align: center'>";
$res->html .= ' <span type="button" data-toggle="modal" data-target="#modalEditar" onclick="clienteEditar(' . $cliente["id"] . ' )"> <img src="imgs/editar.png" width="18" height="18"></img> </span>';
$res->html .= ' <span type="button" data-toggle="modal" data-target="#modalExcluir" onclick="clienteExcluir(' . $cliente["id"] . ' )"> <img src="imgs/lix.png" width="20" height="20"></img></span>';
$res->html .= " </td>";
$res->html .= "</tr>";
}
} else {
$res->html .= "<tr>";
$res->html .= " <td colspan='6' style='text-align: center'>Sem Clientes na Base.</td>";
$res->html .= "</tr>";
}
$res->html .= "</table>";
echo $res->html;
<file_sep>/ajax/clientes_crud.php
<?php
session_start();
include_once('../bd/conexao.php');
extract( $_POST );
if ( $acao === '1' ){
$sql = "SELECT * FROM clientes WHERE id='" . $id . "';";
$stmt = $conn->prepare($sql);
$stmt->execute();
$clientes = $stmt->fetchAll( $conn::FETCH_ASSOC );
$id = "";
$nome = "";
$email = "";
$telefone = "";
$foto = "";
if ( count($clientes) > 0 ){
for ( $x = 0; $x < count($clientes); $x++ ){
$cliente = $clientes[$x];
$id = $cliente["id"];
$nome = $cliente["nome"];
$email = $cliente["email"];
$telefone = $cliente["telefone"];
$foto = $cliente["foto"];
}
}
echo json_encode([
'Id' => $id,
'nome' => $nome,
'email' => $email,
'telefone' => $telefone,
'foto' => $foto
]);
} else if ( $acao === '2' ){
if ( $foto !== "" ){
$sql = "UPDATE clientes SET nome='" . $nome . "',email='" . $email . "',telefone='" . $telefone . "',foto='" . $foto . "' WHERE id='" . $id . "';";
} else {
$sql = "UPDATE clientes SET nome='" . $nome . "',email='" . $email . "',telefone='" . $telefone . "' WHERE id='" . $id . "';";
}
$stmt = $conn->prepare($sql);
$stmt->execute();
echo json_encode([ 'status' => true ]);
} else if ( $acao === '3' ){
$sql = "INSERT INTO `clientes`(`id`, `nome`, `email`, `telefone`, `foto` ) VALUES ( NULL,'" . $nome . "','" . $email . "','" . $telefone . "','" . $foto . "');";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo json_encode([ 'status' => true ]);
} else if ( $acao === '4' ){
$sql = "DELETE FROM `clientes` WHERE id='" . $id . "';";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo json_encode([ 'status' => true ]);
} else if ( $acao === '5' ){
$sql = "SELECT foto FROM clientes WHERE id='" . $id . "';";
$stmt = $conn->prepare($sql);
$stmt->execute();
$clientes = $stmt->fetchAll( $conn::FETCH_ASSOC );
$foto = "";
if ( count($clientes) > 0 ){
for ( $x = 0; $x < count($clientes); $x++ ){
$cliente = $clientes[$x];
$foto = "../fotos/" . $cliente["foto"];
}
}
if ( !unlink( $foto ) )
{
echo json_encode([ 'status' => false ]);
}
else
{
echo json_encode([ 'status' => true ]);
}
}
| 914dfe1d5305a05ebb4546b23aad36253be41c77 | [
"PHP"
] | 5 | PHP | nedirflores/testeBDR | 2107a3150ef8524053c351f43b60b86bcfc5240f | 93160db4a560e371f3708b7527eeab55cd340522 | |
refs/heads/master | <repo_name>thinkful-ei-cheetah/scott-jquery-drills<file_sep>/index.js
'use strict';
/* global $ */
function handleThumbnailClicksMouse() {
$('.thumbnail').click(event => {
const targetImg = $(event.target);
const imgSrc = $(targetImg).attr('src');
const imgAlt = $(targetImg).attr('alt');
$('.large-img').attr('src',imgSrc);
$('.large-img').attr('alt', imgAlt);
});
}
function handleThumbnailClicksEnter() {
$('.thumbnail').keyup(event => {
if (event.which === 13) {
const targetImg = $(event.target).find('img');
const imgSrc = targetImg.attr('src');
const imgAlt = targetImg.attr('alt');
$('.large-img').attr('src',imgSrc);
$('.large-img').attr('alt', imgAlt);
}
});
}
$(handleThumbnailClicksMouse);
$(handleThumbnailClicksEnter); | 3a19d90927f0b3e7164524a747400c1572e0223b | [
"JavaScript"
] | 1 | JavaScript | thinkful-ei-cheetah/scott-jquery-drills | 4f77016abbce47f8176388c163d8bb35a4f7d53c | 090f6038a64ca87e0c9f08edfd65d7905d5bceb1 | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Parcial1_Aplicada2.Models
{
public class Articulos
{
[Key]
[Required(ErrorMessage = "No debe de estar Vacío el campo 'ArticuloId'")]
public int ArticuloId { get; set; }
[Required(ErrorMessage = "No debe de estar Vacío el campo 'Descripción'")]
public string Descripcion { get; set; }
[Required(ErrorMessage = "No debe de estar Vacío el campo 'Existencia'")]
public int Existencia { get; set; }
[Required(ErrorMessage = "No debe de estar Vacío el campo 'Costo'")]
public decimal Costo { get; set; }
[Required(ErrorMessage = "No debe de estar Vacío el campo 'Valor de Inventario'")]
public decimal ValorInventario { get; set; }
public Articulos()
{
ArticuloId = 0;
Descripcion = string.Empty;
Existencia = 0;
Costo = 0;
ValorInventario = 0;
}
public Articulos(int articuloId, string descripcion, int existencia, decimal costo, decimal valorInventario)
{
ArticuloId = articuloId;
Descripcion = descripcion;
Existencia = existencia;
Costo = costo;
ValorInventario = valorInventario;
}
}
}
| 2452c15893c6d299ba0e2f5be564ee4856a3f53c | [
"C#"
] | 1 | C# | LuisDavidSanchezOvalles/Parcial_1_Aplicada_2 | bb90b0bf3afcd6004f1e92b603f53a4d75c756c8 | b4d5ea499539fd6e55ecf7fd2eed49f6c43ce6f5 | |
refs/heads/master | <repo_name>marvinh/MyVstHost<file_sep>/MyVstHost/AudioIO.h
//
// AudioIO.h
// MyVstHost
//
// Created by <NAME> on 8/8/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#ifndef AudioIO_h
#define AudioIO_h
#include "pluginterfaces/vst2.x/aeffectx.h"
#include "RtAudio.h"
class AudioIO
{
public:
AudioIO();
static int AudioCallback( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
double streamTime, RtAudioStreamStatus status, void *data );
void InitializeAudio();
RtAudio *dac;
static VstEvents *events;
static AEffect *effect;
static std::mutex *mtx;
};
#endif /* AudioIO_h */
<file_sep>/MyVstHost/MidiState.h
//
// MidiState.h
// MyVstHost
//
// Created by <NAME> on 8/8/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#ifndef MidiState_h
#define MidiState_h
#include "pluginterfaces/vst2.x/aeffectx.h"
class MidiState
{
public:
MidiState()
{
baseNote = 60;
velocity = 100;
for(int i = 0; i < 128 ; i++)
{
noteOnArray[i] = false;
}
}
~MidiState()
{
}
void NoteOn(char offsetFromOctave)
{
if(noteOnArray[offsetFromOctave+baseNote] == false)
{
mtx->lock();
events->events[events->numEvents] = new VstEvent();
VstMidiEvent *event = (VstMidiEvent*)events->events[events->numEvents];
events->numEvents++;
event->deltaFrames = ((int)(dac->getStreamTime()*44100))%512;
event->midiData[0] = 0x90 | 0;
event->midiData[1] = baseNote+offsetFromOctave;
event->midiData[2] = velocity;
event->type = kVstMidiType;
event->byteSize = sizeof(VstMidiEvent);
event->flags = 1;
noteOnArray[offsetFromOctave+baseNote] = true;
mtx->unlock();
}
}
void NoteOff(char offsetFromOctave)
{
mtx->lock();
events->events[events->numEvents] = new VstEvent();
VstMidiEvent *event = (VstMidiEvent*)events->events[events->numEvents];
events->numEvents++;
event->deltaFrames = ((int)(dac->getStreamTime()*44100))%512;
event->midiData[0] = 0x80 | 0;
event->midiData[1] = baseNote+offsetFromOctave;
event->midiData[2] = velocity;
event->type = kVstMidiType;
event->byteSize = sizeof(VstMidiEvent);
event->flags = 1;
noteOnArray[offsetFromOctave+baseNote] = false;
mtx->unlock();
}
void AllNotesOff()
{
mtx->lock();
effect->dispatcher(effect, effProcessEvents, 0, 0, events, 0);
for(int i = 0; i < events->numEvents; i++)
{
if(events->events[i])
{
delete events->events[i];
}
}
events->numEvents = 0;
for(int i = 0; i < 128; i++)
{
events->events[events->numEvents] = new VstEvent();
VstMidiEvent *event = (VstMidiEvent*)events->events[events->numEvents];
event->deltaFrames = ((int)(dac->getStreamTime()*44100))%512;
event->midiData[0] = 0x80 | 0;
event->midiData[1] = i;
event->midiData[2] = velocity;
event->type = kVstMidiType;
event->byteSize = sizeof(VstMidiEvent);
event->flags = 1;
events->numEvents++;
noteOnArray[i] = false;
}
effect->dispatcher(effect, effProcessEvents, 0, 0, events, 0);
for(int i = 0; i < events->numEvents; i++)
{
if(events->events[i])
{
delete events->events[i];
}
}
events->numEvents = 0;
mtx->unlock();
}
void VelocityUp()
{
if(velocity < 120)
{
velocity += 20;
}
else
{
velocity = 127;
}
}
void VelocityDown()
{
if(velocity == 127)
{
velocity = 120;
}
else if(velocity > 20)
{
velocity -=20;
}
else
{
velocity = 1;
}
}
void OctaveUp()
{
AllNotesOff();
if(baseNote < 100)
{
baseNote += 12;
}
}
void OctaveDown()
{
AllNotesOff();
if(baseNote > 0)
{
baseNote -= 12;
}
}
AEffect *effect;
RtAudio *dac;
VstEvents *events;
std::mutex *mtx;
bool noteOnArray[128];
private:
char baseNote;
char velocity;
};
#endif /* MidiState_h */
<file_sep>/MyVstHost/PluginFunctions.h
//
// PluginFunctions.h
// MyVstHost
//
// Created by <NAME> on 8/8/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#ifndef PluginFunctions_h
#define PluginFunctions_h
#include <stdio.h>
#include <Cocoa/Cocoa.h>
#include "pluginterfaces/vst2.x/aeffectx.h"
//-------------------------------------------------------------------------------------------------------
static const VstInt32 kBlockSize = 512;
static const float kSampleRate = 44100.f;
static const VstInt32 kNumProcessCycles = 5;
//-------------------------------------------------------------------------------------------------------
typedef AEffect* (*PluginEntryProc) (audioMasterCallback audioMaster);
static VstIntPtr VSTCALLBACK HostCallback (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
//-------------------------------------------------------------------------------------------------------
// PluginLoader
//-------------------------------------------------------------------------------------------------------
struct PluginLoader
{
//-------------------------------------------------------------------------------------------------------
void* module;
PluginLoader ()
: module (0)
{}
~PluginLoader ()
{
if (module)
{
#if _WIN32
FreeLibrary ((HMODULE)module);
#elif TARGET_API_MAC_CARBON
CFBundleUnloadExecutable ((CFBundleRef)module);
CFRelease ((CFBundleRef)module);
#endif
}
}
bool loadLibrary (const char* fileName)
{
#if _WIN32
module = LoadLibrary (fileName);
#elif TARGET_API_MAC_CARBON
CFStringRef fileNameString = CFStringCreateWithCString (NULL, fileName, kCFStringEncodingUTF8);
if (fileNameString == 0)
return false;
CFURLRef url = CFURLCreateWithFileSystemPath (NULL, fileNameString, kCFURLPOSIXPathStyle, false);
CFRelease (fileNameString);
if (url == 0)
return false;
module = CFBundleCreate (kCFAllocatorDefault, url);
CFRelease (url);
if (module && CFBundleLoadExecutable ((CFBundleRef)module) == false)
return false;
#endif
return module != 0;
}
PluginEntryProc getMainEntry ()
{
PluginEntryProc mainProc = 0;
#if _WIN32
mainProc = (PluginEntryProc)GetProcAddress ((HMODULE)module, "CFBundleMain");
if (!mainProc)
mainProc = (PluginEntryProc)GetProcAddress ((HMODULE)module, "main");
#elif TARGET_API_MAC_CARBON
mainProc = (PluginEntryProc)CFBundleGetFunctionPointerForName ((CFBundleRef)module, CFSTR("VSTPluginMain"));
if (!mainProc)
mainProc = (PluginEntryProc)CFBundleGetFunctionPointerForName ((CFBundleRef)module, CFSTR("main_macho"));
#endif
return mainProc;
}
//-------------------------------------------------------------------------------------------------------
};
//-------------------------------------------------------------------------------------------------------
static bool checkPlatform ()
{
#if VST_64BIT_PLATFORM
printf ("*** This is a 64 Bit Build! ***\n");
#else
printf ("*** This is a 32 Bit Build! ***\n");
#endif
int sizeOfVstIntPtr = sizeof (VstIntPtr);
int sizeOfVstInt32 = sizeof (VstInt32);
int sizeOfPointer = sizeof (void*);
int sizeOfAEffect = sizeof (AEffect);
printf ("VstIntPtr = %d Bytes, VstInt32 = %d Bytes, Pointer = %d Bytes, AEffect = %d Bytes\n\n",
sizeOfVstIntPtr, sizeOfVstInt32, sizeOfPointer, sizeOfAEffect);
return sizeOfVstIntPtr == sizeOfPointer;
}
//-------------------------------------------------------------------------------------------------------
static void checkEffectProperties (AEffect* effect);
static void checkEffectProcessing (AEffect* effect);
//-------------------------------------------------------------------------------------------------------
void checkEffectProperties (AEffect* effect)
{
printf ("HOST> Gathering properties...\n");
char effectName[256] = {0};
char vendorString[256] = {0};
char productString[256] = {0};
effect->dispatcher (effect, effGetEffectName, 0, 0, effectName, 0);
effect->dispatcher (effect, effGetVendorString, 0, 0, vendorString, 0);
effect->dispatcher (effect, effGetProductString, 0, 0, productString, 0);
printf ("Name = %s\nVendor = %s\nProduct = %s\n\n", effectName, vendorString, productString);
printf ("numPrograms = %d\nnumParams = %d\nnumInputs = %d\nnumOutputs = %d\n\n",
effect->numPrograms, effect->numParams, effect->numInputs, effect->numOutputs);
// Iterate programs...
for (VstInt32 progIndex = 0; progIndex < effect->numPrograms; progIndex++)
{
char progName[256] = {0};
if (!effect->dispatcher (effect, effGetProgramNameIndexed, progIndex, 0, progName, 0))
{
effect->dispatcher (effect, effSetProgram, 0, progIndex, 0, 0); // Note: old program not restored here!
effect->dispatcher (effect, effGetProgramName, 0, 0, progName, 0);
}
printf ("Program %03d: %s\n", progIndex, progName);
}
printf ("\n");
// Iterate parameters...
for (VstInt32 paramIndex = 0; paramIndex < effect->numParams; paramIndex++)
{
char paramName[256] = {0};
char paramLabel[256] = {0};
char paramDisplay[256] = {0};
effect->dispatcher (effect, effGetParamName, paramIndex, 0, paramName, 0);
effect->dispatcher (effect, effGetParamLabel, paramIndex, 0, paramLabel, 0);
effect->dispatcher (effect, effGetParamDisplay, paramIndex, 0, paramDisplay, 0);
float value = effect->getParameter (effect, paramIndex);
printf ("Param %03d: %s [%s %s] (normalized = %f)\n", paramIndex, paramName, paramDisplay, paramLabel, value);
}
printf ("\n");
// Can-do nonsense...
static const char* canDos[] =
{
"receiveVstEvents",
"receiveVstMidiEvent",
"midiProgramNames"
};
for (VstInt32 canDoIndex = 0; canDoIndex < sizeof (canDos) / sizeof (canDos[0]); canDoIndex++)
{
printf ("Can do %s... ", canDos[canDoIndex]);
VstInt32 result = (VstInt32)effect->dispatcher (effect, effCanDo, 0, 0, (void*)canDos[canDoIndex], 0);
switch (result)
{
case 0 : printf ("don't know"); break;
case 1 : printf ("yes"); break;
case -1 : printf ("definitely not!"); break;
default : printf ("?????");
}
printf ("\n");
}
printf ("\n");
}
//-------------------------------------------------------------------------------------------------------
void checkEffectProcessing (AEffect* effect)
{
float** inputs = 0;
float** outputs = 0;
VstInt32 numInputs = effect->numInputs;
VstInt32 numOutputs = effect->numOutputs;
if (numInputs > 0)
{
inputs = new float*[numInputs];
for (VstInt32 i = 0; i < numInputs; i++)
{
inputs[i] = new float[kBlockSize];
memset (inputs[i], 0, kBlockSize * sizeof (float));
}
}
if (numOutputs > 0)
{
outputs = new float*[numOutputs];
for (VstInt32 i = 0; i < numOutputs; i++)
{
outputs[i] = new float[kBlockSize];
memset (outputs[i], 0, kBlockSize * sizeof (float));
}
}
printf ("HOST> Resume effect...\n");
effect->dispatcher (effect, effMainsChanged, 0, 1, 0, 0);
for (VstInt32 processCount = 0; processCount < kNumProcessCycles; processCount++)
{
printf ("HOST> Process Replacing...\n");
effect->processDoubleReplacing (effect, (double**)inputs,(double**) outputs, kBlockSize);
}
printf ("HOST> Suspend effect...\n");
effect->dispatcher (effect, effMainsChanged, 0, 0, 0, 0);
if (numInputs > 0)
{
for (VstInt32 i = 0; i < numInputs; i++)
delete [] inputs[i];
delete [] inputs;
}
if (numOutputs > 0)
{
for (VstInt32 i = 0; i < numOutputs; i++)
delete [] outputs[i];
delete [] outputs;
}
}
//-------------------------------------------------------------------------------------------------------
VstIntPtr VSTCALLBACK HostCallback (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
{
VstIntPtr result = 0;
// Filter idle calls...
bool filtered = true;
if (opcode == audioMasterIdle)
{
static bool wasIdle = false;
if (wasIdle)
filtered = true;
else
{
printf ("(Future idle calls will not be displayed!)\n");
wasIdle = true;
}
}
if (!filtered)
printf ("PLUG> HostCallback (opcode %d)\n index = %d, value = %p, ptr = %p, opt = %f\n", opcode, index, FromVstPtr<void> (value), ptr, opt);
switch (opcode)
{
case audioMasterVersion :
result = kVstVersion;
break;
}
return result;
}
#endif /* PluginFunctions_h */
<file_sep>/MyVstHost/AudioIO.cpp
//
// AudioIO.cpp
// MyVstHost
//
// Created by <NAME> on 8/14/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#include <stdio.h>
#include "AudioIO.h"
AEffect *AudioIO::effect;
VstEvents *AudioIO::events;
std::mutex *AudioIO::mtx;
AudioIO::AudioIO()
{
}
int AudioIO::AudioCallback( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
double streamTime, RtAudioStreamStatus status, void *data )
{
if ( status )
std::cout << "Stream underflow detected!" << std::endl;
float* inputBufferF = (float*)inputBuffer;
float* outputBufferF = (float*)outputBuffer;
mtx->lock();
if(events->numEvents>0)
{
effect->dispatcher(effect, effProcessEvents, 0, 0, events, 0);
}
for(int i = 0; i < nBufferFrames ; i++)
{
if(i==0)
{
float *inputs[2] = {inputBufferF, inputBufferF+nBufferFrames};
float *outputs[2] = {outputBufferF,outputBufferF+nBufferFrames};
effect->processReplacing(effect,inputs,outputs,nBufferFrames);
}
}
for(int i = 0; i < events->numEvents; i++)
{
if(events->events[i])
{
delete events->events[i];
}
}
events->numEvents = 0;
mtx->unlock();
return 0;
}
void AudioIO::InitializeAudio()
{
RtAudio::StreamParameters oParams;
oParams.deviceId = dac->getDefaultOutputDevice();
oParams.nChannels = 2;
RtAudio::StreamParameters iParams;
iParams.deviceId = dac->getDefaultInputDevice();
iParams.nChannels = 2;
unsigned int sampleRate = 44100;
unsigned int bufferFrames = 512; // 512 sample frames
RtAudio::StreamOptions options;
options.flags = RTAUDIO_NONINTERLEAVED | RTAUDIO_SCHEDULE_REALTIME;
options.priority = 0;
try {
dac->openStream( &oParams, &iParams, RTAUDIO_FLOAT32,
sampleRate, &bufferFrames,&AudioCallback, NULL, &options );
dac->startStream();
}
catch ( RtAudioError& e ) {
std::cout << '\n' << e.getMessage() << '\n' << std::endl;
exit( 0 );
}
} | 62a1de9def2e3618cce61cc73910f76a948117d3 | [
"C",
"C++"
] | 4 | C++ | marvinh/MyVstHost | 6b4b68b9067c6d5b6d282da7a8a12de8fd437f16 | 87e59f7ad537320755fa294575add85d99768e72 | |
refs/heads/master | <file_sep>#!/usr/bin/env python
import subprocess
import sys
# Command line parameters
dummy, mexp, calc_jump, characteristic_file, target_file = sys.argv
# Each generator can generate at lest SEP random numbers without overlaps
SEP = 10L**60
# Generate polynomials for both 1*SEP and FACTOR*SEP jumps
FACTOR = 100
def gen_jump(step):
result = subprocess.check_output([calc_jump, str(step), characteristic_file])
head, poly, empty = result.split("\n")
assert head == 'jump polynomial:'
assert empty == ''
return poly
jump_one = gen_jump(SEP)
jump_many = gen_jump(FACTOR * SEP)
with open(target_file, 'w') as f:
f.write('MEXP = %s\n' % mexp)
f.write('JUMP_FACTOR = %d\n' % FACTOR)
f.write('JUMP_ONE = %s\n' % repr(jump_one))
f.write('JUMP_MANY = %s\n' % repr(jump_many))
<file_sep>#!/usr/bin/env python
import struct
import sys
DIR = "src"
#--- Utility functions ---
def dd(*l):
result = dict()
for x in l:
result.update(x.d)
return result
def indent(w, i):
prefix = " " * i;
def w2(msg):
w("".join([prefix + line for line in msg.splitlines(True)]))
return w2
def gen_list(w, l, pat1, pat2):
for a in l:
w(pat1 % a.d)
w("\n")
w(pat2 % { "count": len(l) })
w("\n\n")
def any_array(width, l):
r = []
tail = l
while len(tail) > 0:
head, tail = tail[:width], tail[width:]
r.append(", ".join(head))
return ",\n ".join(r)
def char_array(s):
return any_array(12, ["'%s'" % i for i in s] + ["0"])
def uint32_array(l):
return any_array(6, ["0x%08x" % i for i in l])
#--------
def setup_all():
for c in ("none", "curves", "permtest"):
setup_class(Class(c))
Y_TYPE = Y("type", True)
Y_HAPAX = Y("hapax", False)
Y_TOKEN = Y("token", True)
X_WORD = X("word", ["WITH_WORD_COUNT"])
X_TOKEN = X("token", [])
for x in (X_WORD, X_TOKEN):
setup_x(x)
for y in (Y_TYPE, Y_HAPAX, Y_TOKEN):
setup_y(y)
for y in (Y_TYPE, Y_HAPAX):
for x in (X_WORD, X_TOKEN):
setup_yx(y, x)
setup_yx(Y_TOKEN, X_WORD)
YY_TYPE = YY((Y_TYPE,), "type", "vector", ["WITH_MATRIX_BINARY"])
YY_HAPAX = YY((Y_HAPAX,), "hapax", "zom", ["WITH_MATRIX_ZOM"])
YY_TYPE_HAPAX = YY((Y_TYPE, Y_HAPAX), "typehapax", "zom", ["WITH_MATRIX_ZOM"])
YY_TOKEN = YY((Y_TOKEN,), "token", None, [])
XX_TOKEN = XX((X_TOKEN,), "t", False)
XX_WORD = XX((X_WORD,), "w", False)
XX_WORD_TOKEN = XX((X_WORD, X_TOKEN), "wt", True)
V_DENSE = V("dense")
V_SPARSE = V("sparse")
V_NORMAL = V(None)
for yy in (YY_TYPE, YY_HAPAX, YY_TYPE_HAPAX):
for xx in (XX_TOKEN, XX_WORD, XX_WORD_TOKEN):
setup_variants(yy, xx, [V_DENSE, V_SPARSE])
setup_variants(YY_TOKEN, XX_WORD, [V_NORMAL])
def record(w, y, x):
# Store new per-slot bounds based on per-gap bounds.
# Example:
# - threshold is 0, 10, 20, etc.
# - "xslot" is 2
# Then:
# - "b_prev_gap" is the bounds for the gap 10..20
# - "b_this_gap is the bounds for the gap 20..30
# - we update the bounds for the slot 20.
w('''\
{
''')
if y.nondecreasing:
w('''\
assert(b_prev_gap_%(y)s_%(x)s.lower <= b_this_gap_%(y)s_%(x)s.lower);
assert(b_prev_gap_%(y)s_%(x)s.upper <= b_this_gap_%(y)s_%(x)s.upper);
const unsigned lower = b_prev_gap_%(y)s_%(x)s.lower;
const unsigned upper = b_this_gap_%(y)s_%(x)s.upper;
''' % dd(y, x))
else:
w('''\
const unsigned lower = MIN(b_prev_gap_%(y)s_%(x)s.lower, b_this_gap_%(y)s_%(x)s.lower);
const unsigned upper = MAX(b_prev_gap_%(y)s_%(x)s.upper, b_this_gap_%(y)s_%(x)s.upper);
''' % dd(y, x))
w('''\
const unsigned yslot_lower = get_yslot(pgrid, Y%(Y)s, lower);
const unsigned yslot_upper = get_yslot_up(pgrid, Y%(Y)s, upper);
const unsigned index_lower = slot(pgrid, Y%(Y)s, X%(X)s, yslot_lower, xslot_%(x)s);
const unsigned index_upper = slot(pgrid, Y%(Y)s, X%(X)s, yslot_upper, xslot_%(x)s);
pyxstat->yx[YX_%(Y)s_%(X)s][index_lower].lower++;
pyxstat->yx[YX_%(Y)s_%(X)s][index_upper].upper++;
}
''' % dd(y, x))
def gen_summarise_collection_var(f, var):
w = f.cw
xx = var.alg.xx
yy = var.alg.yy
w('''\
static void
summarise_collection_%(yy)s_%(xx)s%(maybev)s(
const input_t * restrict pinput,
collection_t * restrict pcoll,
const unsigned c)
{
''' % var.d)
if yy.temp is not None:
w('''\
%(temp)s_t temp[pinput->types.nvector];
%(temp)s_clear(temp, pinput->types.nvector);
''' % var.d)
for x in xx.x:
w('''\
unsigned xaccum_%(x)s = 0;
''' % x.d)
for y in yy.y:
w('''\
unsigned yaccum_%(y)s = 0;
''' % y.d)
w('''\
for (unsigned id = 0; id < pinput->types.nrow; id++) {
if (matrix_element_b(&pinput->collections, id, c)) {
calculate_bounds_%(yy)s%(maybev)s(
pinput, id%(maybetemp)s, %(yaccumlist)s
);
''' % var.d)
for x in xx.x:
w('''\
xaccum_%(x)s += %(getsamples)s;
''' % { "x": x.key, "getsamples": xx.get_samples(x)})
w('''\
}
}
''')
for x in xx.x:
w('''\
pcoll[c].x.x[X%(X)s] = xaccum_%(x)s;
''' % x.d)
for y in yy.y:
w('''\
pcoll[c].y.y[Y%(Y)s] = yaccum_%(y)s;
''' % y.d)
w('''\
}
''')
def gen_calculate_permtest_one(f, var):
w = f.cw
xx = var.alg.xx
yy = var.alg.yy
w('''\
static void
calculate_permtest_%(yy)s_%(xx)s%(maybev)s_one(
const input_t * restrict pinput,
const collection_t * restrict pcoll,
const yxstat_t * restrict pyxstat,
const unsigned * restrict sample_order)
{
''' % var.d)
w('''\
for (unsigned c = 0; c < pinput->collections.ncol; c++) {
''')
for x in xx.x:
w('''\
if (pcoll[c].x.x[X%(X)s] == 0) {
''' % x.d)
for y in yy.y:
w('''\
pyxstat->yx[YX_%(Y)s_%(X)s][c].lower++;
pyxstat->yx[YX_%(Y)s_%(X)s][c].upper++;
''' % dd(y, x))
w('''\
}
''')
w('''\
}
''')
if yy.temp is not None:
w('''\
%(temp)s_t temp[pinput->types.nvector];
%(temp)s_clear(temp, pinput->types.nvector);
''' % var.d)
for x in xx.x:
w('''\
unsigned xaccum_%(x)s = 0;
''' % x.d)
for y in yy.y:
w('''\
unsigned yaccum_%(y)s = 0;
''' % y.d)
w('''\
for (unsigned i = 0; i < pinput->types.nrow; i++) {
const unsigned id = sample_order[i];
const %(yy)s_bounds_t b_sample = calculate_bounds_%(yy)s%(maybev)s(
pinput, id%(maybetemp)s, %(yaccumlist)s
);
''' % var.d)
for x in xx.x:
w('''\
const unsigned xprev_%(x)s = xaccum_%(x)s;
xaccum_%(x)s += %(getsamples)s;
''' % { "x": x.key, "getsamples": xx.get_samples(x)})
w('''\
for (unsigned c = 0; c < pinput->collections.ncol; c++) {
''')
for x in xx.x:
w('''\
if (xprev_%(x)s < pcoll[c].x.x[X%(X)s] && pcoll[c].x.x[X%(X)s] <= xaccum_%(x)s) {
''' % x.d)
for y in yy.y:
w('''\
if (b_sample.y%(y)s.lower <= pcoll[c].y.y[Y%(Y)s]) {
pyxstat->yx[YX_%(Y)s_%(X)s][c].lower++;
}
if (b_sample.y%(y)s.upper >= pcoll[c].y.y[Y%(Y)s]) {
pyxstat->yx[YX_%(Y)s_%(X)s][c].upper++;
}
''' % dd(y, x))
w('''\
}
''')
w('''\
}
}
}
''')
def gen_calculate_curves_one(f, var):
w = f.cw
xx = var.alg.xx
yy = var.alg.yy
w('''\
static void
calculate_curves_%(yy)s_%(xx)s%(maybev)s_one(
const input_t * restrict pinput,
const grid_t * restrict pgrid,
const yxstat_t * restrict pyxstat,
const unsigned * restrict sample_order)
{
''' % var.d)
if yy.temp is not None:
w('''\
%(temp)s_t temp[pinput->types.nvector];
%(temp)s_clear(temp, pinput->types.nvector);
''' % var.d)
for x in xx.x:
w('''\
unsigned xaccum_%(x)s = 0;
unsigned xslot_%(x)s = 0;
''' % x.d)
for y in yy.y:
w('''\
unsigned yaccum_%(y)s = 0;
''' % y.d)
for x in xx.x:
for y in yy.y:
w('''\
bounds_t b_prev_gap_%(y)s_%(x)s = BOUNDS_NULL;
bounds_t b_this_gap_%(y)s_%(x)s = BOUNDS_NULL;
''' % dd(y, x))
w('''\
for (unsigned i = 0; i < pinput->types.nrow; i++) {
const unsigned id = sample_order[i];
const %(yy)s_bounds_t b_sample = calculate_bounds_%(yy)s%(maybev)s(
pinput, id%(maybetemp)s, %(yaccumlist)s
);
''' % var.d)
for x in xx.x:
w('''\
xaccum_%(x)s += %(getsamples)s;
''' % { "x": x.key, "getsamples": xx.get_samples(x)})
for y in yy.y:
if y.nondecreasing:
w('''\
assert(b_this_gap_%(y)s_%(x)s.lower <= b_sample.y%(y)s.lower);
assert(b_sample.y%(y)s.lower <= b_this_gap_%(y)s_%(x)s.upper);
assert(b_this_gap_%(y)s_%(x)s.upper <= b_sample.y%(y)s.upper);
b_this_gap_%(y)s_%(x)s.upper = b_sample.y%(y)s.upper;
''' % dd(y, x))
else:
w('''\
b_this_gap_%(y)s_%(x)s.lower = MIN(b_sample.y%(y)s.lower, b_this_gap_%(y)s_%(x)s.lower);
b_this_gap_%(y)s_%(x)s.upper = MAX(b_sample.y%(y)s.upper, b_this_gap_%(y)s_%(x)s.upper);
''' % dd(y, x))
w('''\
while (xaccum_%(x)s >= get_xthreshold(pgrid, X%(X)s, xslot_%(x)s+1)) {
''' % x.d)
for y in yy.y:
record(indent(w, 2), y, x)
w('''\
b_prev_gap_%(y)s_%(x)s = b_this_gap_%(y)s_%(x)s;
b_this_gap_%(y)s_%(x)s = b_sample.y%(y)s;
''' % dd(y, x))
w('''\
xslot_%(x)s++;
}
if (xaccum_%(x)s == get_xthreshold(pgrid, X%(X)s, xslot_%(x)s)) {
''' % x.d)
for y in yy.y:
w('''\
b_this_gap_%(y)s_%(x)s.lower = yaccum_%(y)s;
b_this_gap_%(y)s_%(x)s.upper = yaccum_%(y)s;
''' % dd(y, x))
w('''\
}
''')
w('''\
}
''')
for x in xx.x:
w('''\
assert(xslot_%(x)s == pgrid->xslots.x[X%(X)s] - 1);
''' % x.d)
for y in yy.y:
record(w, y, x)
w('''\
}
''')
def gen_calculate_x_var(f, var, what, type1, var1):
f.cw('''\
static void
calculate_%(what)s_%(yy)s_%(xx)s%(maybev)s(
const input_t * restrict pinput,
const rng_state_t * restrict rng_state_init,
%(type1)s %(var1)s,
const yxstat_t * restrict pyxstat,
unsigned part)
{
unsigned sample_order[pinput->types.nrow];
unsigned from = get_iteration(pinput->iterations, part);
unsigned to = get_iteration(pinput->iterations, part + 1);
rng_state_t rng_state = rng_state_init[part];
for (unsigned iteration = from; iteration < to; iteration++) {
rand_permutation(&rng_state, pinput->types.nrow, sample_order);
calculate_%(what)s_%(yy)s_%(xx)s%(maybev)s_one(pinput, %(var1)s, pyxstat, sample_order);
}
}
''' % dict(var.d, what=what, type1=type1, var1=var1))
def gen_calculate_permtest_var(f, var):
gen_calculate_x_var(f, var, "permtest", "const collection_t * restrict", "pcoll")
def gen_calculate_curves_var(f, var):
gen_calculate_x_var(f, var, "curves", "const grid_t * restrict", "pgrid")
def gen_array(f):
for v in ("sparse", "dense"):
f.cw('''\
const algv_t ALG_%(V)s[NALG] = {
''' % { "V": v.upper() } )
for alg in ALGORITHMS:
maybev1 = ("_" + v if alg.has_variants else "")
maybev2 = (v if alg.has_variants else "")
f.cw('''\
{
summarise_collection_%(yy)s_%(xx)s%(maybev1)s,
calculate_permtest_%(yy)s_%(xx)s%(maybev1)s,
calculate_curves_%(yy)s_%(xx)s%(maybev1)s,
"%(yy)s-%(xx)s", "%(maybev2)s"
},
''' % dict(alg.d.items(), maybev1=maybev1, maybev2=maybev2))
f.cw('''\
};
''')
f.cw('''\
const alg_t ALG[NALG] = {
''')
for alg in ALGORITHMS:
f.cw('''\
{
%(featurelist)s,
{ { %(outputlist)s } }
},
''' % alg.d)
f.cw('''\
};
''')
def gen_jump_h(f):
import JumpTable
d = {
"JUMP_FACTOR": JumpTable.JUMP_FACTOR,
"MEXP": JumpTable.MEXP,
}
f.hw('''\
#define JUMP_FACTOR %(JUMP_FACTOR)d
extern const char JUMP_ONE[];
extern const char JUMP_MANY[];
''' % d)
def gen_jump_c(f):
import JumpTable
d = {
"MEXP": JumpTable.MEXP,
"JUMP_ONE": char_array(JumpTable.JUMP_ONE),
"JUMP_MANY": char_array(JumpTable.JUMP_MANY),
}
f.cw('''\
#if !defined(SFMT_MEXP)
#error "SFMT_MEXP is not defined"
#endif
#if SFMT_MEXP != %(MEXP)d
#error "this file assumes SFMT_MEXT = %(MEXP)d"
#endif
const char JUMP_ONE[] = {
%(JUMP_ONE)s
};
const char JUMP_MANY[] = {
%(JUMP_MANY)s
};
''' % d)
def get_seed():
FORMAT = '<L'
LEN = struct.calcsize(FORMAT)
assert LEN == 4
seed = []
with open('etc/seed') as f:
while True:
s = f.read(LEN)
if s == '':
break
seed.append(struct.unpack(FORMAT, s))
return {
"SEED_LENGTH": len(seed),
"SEED": uint32_array(seed),
}
def gen_seed_h(f):
d = get_seed()
f.hw('''\
#include <stdint.h>
#define SEED_LENGTH %(SEED_LENGTH)d
extern const uint32_t SEED[SEED_LENGTH];
''' % d)
def gen_seed_c(f):
d = get_seed()
f.cw('''\
const uint32_t SEED[SEED_LENGTH] = {
%(SEED)s
};
''' % d)
def gen_yx_h(f):
f.hw('''\
#include <stdbool.h>
#include "io.h"
''')
gen_list(f.hw, CLASS_LIST, "#define CLASS_%(CLASS)s %(index)d", "#define NCLASS %(count)d")
gen_list(f.hw, X_LIST, "#define X%(X)s %(index)d", "#define NX %(count)d")
gen_list(f.hw, Y_LIST, "#define Y%(Y)s %(index)d", "#define NY %(count)d")
gen_list(f.hw, YX_LIST, "#define YX_%(Y)s_%(X)s %(index)d", "#define NYX %(count)d")
d = {
"forx": ", ".join(["a" for x in X_LIST]),
"fory": ", ".join(["a" for y in Y_LIST]),
"foryx": ", ".join(["a" for yx in YX_LIST]),
}
f.hw('''\
typedef struct {
unsigned y;
unsigned x;
const char * label;
const char * cswitch;
const char * pswitch;
} yxmap_t;
extern const yxmap_t YX[NYX];
typedef struct { unsigned x[NX]; } x_t;
typedef struct { unsigned y[NY]; } y_t;
typedef struct { unsigned yx[NYX]; } yx_t;
typedef struct { double x[NX]; } xd_t;
typedef struct { double y[NY]; } yd_t;
typedef struct { bool yx[NYX]; } yxbool_t;
#define FOREACH_X(a) %(forx)s
#define FOREACH_Y(a) %(forx)s
#define FOREACH_YX(a) %(forx)s
#define X_NULL { { FOREACH_X(0) } }
#define Y_NULL { { FOREACH_Y(0) } }
#define YX_NULL { { FOREACH_YX(0) } }
#define XD_NULL { { FOREACH_X(0.0) } }
#define YD_NULL { { FOREACH_Y(0.0) } }
#define YXBOOL_NULL { { FOREACH_YX(false) } }
extern const x_t X_NULL_C;
extern const y_t Y_NULL_C;
extern const yx_t YX_NULL_C;
''' % d)
def gen_yx_c(f):
f.cw('''\
const yxmap_t YX[NYX] = {
''')
for yx in YX_LIST:
f.cw('''\
{ Y%(Y)s, X%(X)s, "%(y)s-%(x)s", "--%(y)s-%(x)s", "--p-%(y)s-%(x)s" },
''' % yx.d)
f.cw('''\
};
const x_t X_NULL_C = X_NULL;
const y_t Y_NULL_C = Y_NULL;
const yx_t YX_NULL_C = YX_NULL;
''')
def gen_alg_h(f):
gen_list(f.hw, ALGORITHMS, "#define ALG_%(YY)s_%(XX)s %(index)d", "#define NALG %(count)d")
def gen_calculate_h(f):
f.hw('''\
#include "collections.h"
#include "curves.h"
#include "input.h"
#include "random.h"
#include "stat.h"
typedef void (*summarise_collection_t)(const input_t * restrict pinput,
collection_t * restrict pcoll,
unsigned c);
typedef void (*calculate_permtest_t)(const input_t * restrict pinput,
const rng_state_t * restrict rng_state_init,
const collection_t * restrict pcoll,
const yxstat_t * restrict pyxstat,
unsigned part);
typedef void (*calculate_curves_t)(const input_t * restrict pinput,
const rng_state_t * restrict rng_state_init,
const grid_t * restrict pgrid,
const yxstat_t * restrict pyxstat,
unsigned part);
typedef struct {
summarise_collection_t summarise_collection;
calculate_permtest_t calculate_permtest;
calculate_curves_t calculate_curves;
const char *msg1;
const char *msg2;
} algv_t;
typedef struct {
unsigned requirements;
yxbool_t outputs;
} alg_t;
''')
f.hw('''\
extern const alg_t ALG[];
extern const algv_t ALG_SPARSE[];
extern const algv_t ALG_DENSE[];
''')
def gen_calculate_c(f):
f.cw('''\
#include "alg.h"
#include "calcutil.h"
#include "plan.h"
#include "malloc.h"
#include <assert.h>
''')
for var in VARIANTS:
gen_summarise_collection_var(f, var)
for var in VARIANTS:
gen_calculate_permtest_one(f, var)
for var in VARIANTS:
gen_calculate_curves_one(f, var)
for var in VARIANTS:
gen_calculate_permtest_var(f, var)
for var in VARIANTS:
gen_calculate_curves_var(f, var)
gen_array(f)
f.close()
class Indexed:
def put_to_list(self, l):
self.set_index(len(l))
l.append(self)
def set_index(self, index):
self.index = index
self.d["index"] = index
class Class(Indexed):
def __init__(self, key):
self.key = key
self.d = {
"class": self.key,
"CLASS": self.key.upper(),
}
class Y(Indexed):
def __init__(self, key, nondecreasing):
self.key = key
self.nondecreasing = nondecreasing
self.d = {
"y": self.key,
"Y": self.key.upper(),
}
class X(Indexed):
def __init__(self, key, features):
self.key = key
self.features = features
self.d = {
"x": self.key,
"X": self.key.upper(),
}
class YX(Indexed):
def __init__(self, y, x):
self.y = y
self.x = x
self.d = dd(y, x)
class YY:
def __init__(self, y, key, temp, features):
self.y = y
self.key = key
self.temp = temp
self.features = features
class XX:
def __init__(self, x, suffix, interleaved):
self.x = x
self.suffix = suffix
self.interleaved = interleaved
self.features = []
for x_ in x:
self.features.extend(x_.features)
if interleaved:
self.features.append("WITH_INTERLEAVING")
def get_samples(self, x):
if self.interleaved:
return "pinput->samples_word_token[id].%s" % x.key
else:
return "pinput->SAMPLES_%s[id]" % x.key.upper()
class V:
def __init__(self, key):
self.key = key
class Algorithm(Indexed):
def __init__(self, yy, xx, has_variants):
self.xx = xx
self.yy = yy
self.has_variants = has_variants
self.features = xx.features + yy.features
self.yx_set = set()
for y in yy.y:
for x in xx.x:
yx = YX_MAP[(y.key, x.key)]
self.yx_set.add(yx)
self.yx_outputs = [ yx in self.yx_set for yx in YX_LIST ]
self.d = {
"yy": yy.key,
"xx": xx.suffix,
"YY": yy.key.upper(),
"XX": xx.suffix.upper(),
"temp": yy.temp,
"maybetemp": (", temp" if yy.temp is not None else ""),
"yaccumlist": ", ".join(["&yaccum_%s" % y.key for y in yy.y]),
"featurelist": " | ".join(self.features),
"outputlist": ", ".join(["true" if a else "false" for a in self.yx_outputs]),
"zeros": ", ".join(["0" for x in xx.x] + ["0" for y in yy.y]),
}
class Variant(Indexed):
def __init__(self, alg, v):
self.alg = alg
self.v = v
self.d = dict(alg.d)
self.d["maybev"] = "" if v.key is None else "_%s" % v.key
class Header:
def __init__(self, prefix):
self.d = { "n": prefix, "N": prefix.upper() }
self.h = open("%s/%s.h" % (DIR, prefix), "w")
self.hw = self.h.write
self.hw('''\
#ifndef TYPES_%(N)s_H
#define TYPES_%(N)s_H
// This file is machine-generated.
''' % self.d)
def close(self):
self.hw('''\
#endif
''')
self.h.close()
class Source:
def __init__(self, prefix):
self.d = { "n": prefix, "N": prefix.upper() }
self.c = open("%s/%s.c" % (DIR, prefix), "w")
self.cw = self.c.write
self.cw('''\
// This file is machine-generated.
#include "%(n)s.h"
''' % self.d)
def close(self):
self.c.close()
CLASS_LIST = []
Y_LIST = []
X_LIST = []
YX_LIST = []
YX_MAP = dict()
ALGORITHMS = []
VARIANTS = []
def setup_variants(yy, xx, vlist):
has_variants = len(vlist) > 1
alg = Algorithm(yy, xx, has_variants)
alg.put_to_list(ALGORITHMS)
for v in vlist:
var = Variant(alg, v)
var.put_to_list(VARIANTS)
def setup_class(c):
c.put_to_list(CLASS_LIST)
def setup_y(y):
y.put_to_list(Y_LIST)
def setup_x(x):
x.put_to_list(X_LIST)
def setup_yx(y, x):
yx = YX(y, x)
yx.put_to_list(YX_LIST)
YX_MAP[(y.key, x.key)] = yx
def gen(what):
l = what.split("/")
assert len(l) == 2, l
assert l[0] == DIR, l
what = l[1]
if what == "alg.h":
f = Header("alg")
gen_alg_h(f)
f.close()
elif what == "calculate.h":
f = Header("calculate")
gen_calculate_h(f)
f.close()
elif what == "calculate.c":
f = Source("calculate")
gen_calculate_c(f)
f.close()
elif what == "jump.h":
import JumpTable
f = Header("jump")
gen_jump_h(f)
f.close()
elif what == "jump.c":
import JumpTable
f = Source("jump")
gen_jump_c(f)
f.close()
elif what == "seed.h":
f = Header("seed")
gen_seed_h(f)
f.close()
elif what == "seed.c":
f = Source("seed")
gen_seed_c(f)
f.close()
elif what == "yx.h":
f = Header("yx")
gen_yx_h(f)
f.close()
elif what == "yx.c":
f = Source("yx")
gen_yx_c(f)
f.close()
else:
raise ValueError(what)
setup_all()
for what in sys.argv[1:]:
gen(what)
<file_sep>#!/usr/bin/env python
import optparse
import os
import os.path
import re
import subprocess
import sys
MEXP = 19937
FLAGS_RE = re.compile('flags\s*:')
def tryrun2(cmd):
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except:
return None
output, error = p.communicate()
if p.returncode:
return None
else:
return (output, error)
def tryrun(cmd):
r = tryrun2(cmd)
if r is None:
return None
output, error = r
if error != '':
return None
else:
return output
def tryrun_get_err(cmd):
r = tryrun2(cmd)
if r is None:
return None
output, error = r
return error
def versionstring(version):
return '.'.join([str(v) for v in version])
def test_cc(cc):
BAD = (None, False)
version = tryrun([cc, '-dumpversion'])
if version is None:
return BAD
version = version.rstrip(' \n\r').split('.')
for v in version:
if not v.isdigit():
return BAD
version = [ int(v) for v in version ]
ok = True
return (version, ok)
PYTHON_TEST = 'src/test.py'
PYTHON_OK = 'OK\n'
def test_python(python):
BAD = (None, False)
version = tryrun_get_err([python, '--version'])
if version is None:
return BAD
version = version.rstrip(' \n\r')
if not version.startswith('Python '):
return BAD
version = version.split(' ')[1].split('.')
for v in version:
if not v.isdigit():
return BAD
version = [ int(v) for v in version ]
r = tryrun2([python, PYTHON_TEST])
if r is None:
ok = False
else:
output, error = r
if output != PYTHON_OK:
ok = False
elif error == '':
ok = True
else:
# Both OK and error messages?
# Might be first-time initialisation related to matplotlib:
# try again...
ok = tryrun([python, PYTHON_TEST]) == PYTHON_OK
return (version, ok)
class Tool:
def __init__(self, short, long, re, hook):
self.short = short
self.long = long
self.re = re
self.hook = hook
self.msg = None
def report(self, full, version, ok):
okstring = "looks good" if ok else "test failed"
if version is None:
toolstring = "?"
else:
toolstring = "%s %s" % (self.short, versionstring(version))
print "- %-30s %-20s %s" % (full, toolstring, okstring)
def find_best(self):
print "Trying to find %s..." % self.long
if self.msg is not None:
print self.msg
print
tool = None
toolversion = None
pathseen = set()
for d in os.environ['PATH'].split(os.pathsep):
if d in pathseen:
continue
pathseen.add(d)
if os.path.isdir(d):
for f in sorted(os.listdir(d)):
if self.re.match(f):
full = os.path.join(d, f)
(version, ok) = self.hook(full)
self.report(full, version, ok)
if ok and (toolversion is None or toolversion < version):
tool = full
toolversion = version
print
if tool is None:
print "Error: could not find %s." % self.long
sys.exit(1)
return (tool, toolversion)
def find_tool(self, hint):
tool = None
toolversion = None
if hint is not None:
print "Testing %s..." % hint
if self.msg is not None:
print self.msg
print
(version, ok) = self.hook(hint)
self.report(hint, version, ok)
print
if ok:
return (hint, version)
if tool is None:
return self.find_best()
GCC_RE = re.compile('gcc(-[0-9]+(\.[0-9]+)*)?(\.exe)?\Z')
PYTHON_RE = re.compile('python(-?2+(\.[0-9]+)+)?(\.exe)?\Z')
GCC = Tool('gcc', 'a C compiler', GCC_RE, test_cc)
PYTHON = Tool('python', 'a Python interpreter', PYTHON_RE, test_python)
PYTHON.msg = "I will try to run the test script %s" % PYTHON_TEST
class Config:
def __init__(self):
self.cc = None
self.ccversion = None
self.python = None
self.cflags_prod = []
self.cflags_debug = []
self.cflags_dep = []
self.cppflags_prod = []
self.cppflags_debug = []
self.cppflags_dep = []
self.ldflags_prod = []
self.ldflags_debug = []
self.popcnt = False
self.sse2 = False
self.openmp = True
def do_all(self):
self.get_args()
print
self.find_platform()
self.find_cc()
self.find_python()
self.find_sqlite()
self.platform_features()
self.compiler_flags()
self.write_flags()
def get_args(self):
parser = optparse.OptionParser(description='Configure the system.')
parser.add_option('--cc', metavar='X', dest='cc',
help='Which C compiler to use')
parser.add_option('--python', metavar='X', dest='python',
help='Which Python interpreter to use (full path required)')
parser.add_option('--enable-openmp', dest='enable_openmp',
action='store_true', default=False,
help='Use OpenMP even if it looks risky')
parser.add_option('--disable-openmp', dest='disable_openmp',
action='store_true', default=False,
help='Do not try to use OpenMP')
(options, args) = parser.parse_args()
self.args = options
def find_platform(self):
self.osx = False
self.linux = False
if sys.platform.startswith('darwin'):
print "This seems to be a Mac OS X system."
self.osx = True
elif sys.platform.startswith('linux'):
print "This seems to be a Linux system."
self.linux = True
elif sys.platform.startswith('cygwin'):
print "This seems to be a Windows / Cygwin system."
else:
print "I do not recognise platform '%s'." % sys.platform
print "I will try to use reasonable default values."
print
def find_cc(self):
(self.cc, self.ccversion) = GCC.find_tool(self.args.cc)
print "I will use %s, which seems to be GCC version %s." % (self.cc, versionstring(self.ccversion))
print "You can override it with the --cc flag."
print
def find_python(self):
(self.python, self.pythonversion) = PYTHON.find_tool(self.args.python)
print "I will use Python interpreter %s, version %s." % (self.python, versionstring(self.pythonversion))
print "You can override it with the --python flag."
print
def find_sqlite(self):
print "Making sure that sqlite3 is installed..."
print
result = tryrun(['sqlite3', '-version'])
if result is None:
print "Error: could not find sqlite3."
sys.exit(1)
def platform_features(self):
print "Inspecting the platform..."
print
if self.linux and os.path.isfile('/proc/cpuinfo'):
print "- reading processor features..."
print
with open('/proc/cpuinfo') as f:
for l in f:
if FLAGS_RE.match(l):
flags = set(l.split(':')[1].split())
if 'sse2' in flags:
self.sse2 = True
if 'popcnt' in flags:
self.popcnt = True
elif self.osx:
print "- reading processor features..."
print
r = tryrun(['sysctl', '-n', 'machdep.cpu.features'])
if r is not None:
flags = set(r.strip().split(' '))
if 'SSE2' in flags:
self.sse2 = True
if 'POPCNT' in flags:
self.popcnt = True
else:
# all Intel Macs should have SSE2
self.sse2 = True
if self.args.disable_openmp:
print "- not using OpenMP as requested"
print
self.openmp = False
elif self.osx and self.ccversion < [4,3,0]:
print "- most likely this compiler does not work reliably with OpenMP"
print " (consider installing gcc from Homebrew)"
print
self.openmp = False
elif self.ccversion < [4,2,0]:
print "- the C compiler is too old to support OpenMP"
print
self.openmp = False
if self.args.enable_openmp and self.openmp == False:
print "- using OpenMP as requested"
print
self.openmp = True
features = []
features.append("OpenMP" if self.openmp else "no OpenMP")
features.append("SSE2" if self.sse2 else "no SSE2")
features.append("POPCNT" if self.popcnt else "no POPCNT")
print "- summary:", ', '.join(features)
print
def compiler_flags(self):
for cppflags in (self.cppflags_prod, self.cppflags_debug, self.cppflags_dep):
cppflags.append("-DSFMT_MEXP=%s" % MEXP)
self.cppflags_prod.append("-DNDEBUG")
if self.ccversion >= [4,2,4]:
self.cflags_prod.append("-march=native")
if self.osx:
# http://stackoverflow.com/questions/9840207/how-to-use-avx-pclmulqdq-on-mac-os-x-lion
self.cflags_prod.append("-Wa,-q")
if self.openmp:
self.cflags_prod.append("-fopenmp")
self.ldflags_prod.append("-fopenmp")
if self.sse2:
self.cppflags_prod.append("-DHAVE_SSE2")
if self.popcnt:
self.cppflags_prod.append("-DUSE_BUILTIN_POPCOUNT")
self.cflags_prod.append("-O3")
if self.ccversion >= [4,7,0]:
for cflags in (self.cflags_prod, self.cflags_debug, self.cflags_dep):
cflags.extend(("-std=c11", "-g", "-pedantic",
"-Werror", "-Wall", "-Wextra",
"-Wformat=2", "-Winit-self", "-Wswitch-enum", "-Wstrict-aliasing",
"-Wundef", "-Wshadow", "-Wpointer-arith", "-Wbad-function-cast",
"-Wcast-qual", "-Wcast-align", "-Wwrite-strings", "-Wstrict-prototypes",
"-Wold-style-definition", "-Wmissing-prototypes", "-Wmissing-declarations",
"-Wredundant-decls", "-Wnested-externs", "-Wdisabled-optimization",
"-Wno-maybe-uninitialized", "-Wno-sign-compare"))
self.cflags_prod.append("-Wno-unused")
if self.ccversion >= [4,8,0]:
self.cflags_prod.append("-Wno-unused-parameter")
self.cflags_debug.append("-Wunused-macros")
else:
for cflags in (self.cflags_prod, self.cflags_debug, self.cflags_dep):
cflags.extend(("-std=c99", "-g", "-Wall", "-Wextra", "-Wno-unused", "-Wno-sign-compare"))
for cppflags in (self.cppflags_prod, self.cppflags_debug, self.cppflags_dep):
cppflags.append("-D_Noreturn='__attribute__((noreturn))'")
if not self.openmp:
self.cflags_prod.append("-Wno-unknown-pragmas")
self.cflags_debug.append("-Wno-unknown-pragmas")
def write_flags(self):
print "Writing configuration..."
print
with open('etc/config.inc', 'w') as f:
def setval(what, val):
l = "%s = %s" % (what, val)
print l
f.write(l)
f.write("\n")
def setlist(what, l):
setval(what, ' '.join(l))
setval('PYTHON', self.python)
setval('CC', self.cc)
setlist('CPPFLAGS', self.cppflags_prod)
setlist('CPPFLAGSD', self.cppflags_debug)
setlist('CPPFLAGSM', self.cppflags_dep)
setlist('CFLAGS', self.cflags_prod)
setlist('CFLAGSD', self.cflags_debug)
setlist('CFLAGSM', self.cflags_dep)
setlist('LDFLAGS', self.ldflags_prod)
setlist('LDFLAGSD', self.ldflags_debug)
setlist('LDLIBSDB', ['-lsqlite3'])
setval('MEXP', str(MEXP))
print
Config().do_all()
<file_sep>#!/usr/bin/env python
import datetime
description = "Type and hapax accumulation curves"
author = "<NAME>"
now = datetime.date.today()
version = now.isoformat()
year = now.year
with open('src/version.c', 'w') as f:
f.write('''\
#include "version.h"
const char * const DESCRIPTION = "%s";
const char * const AUTHOR = "%s";
const char * const VERSION = "%s";
const char * const YEAR = "%d";
''' % (description, author, version, year))
with open('src/TypesVersion.py', 'w') as f:
f.write('''\
DESCRIPTION = "%s"
AUTHOR = "%s"
VERSION = "%s"
YEAR = "%d"
''' % (description, author, version, year))
<file_sep>#include "version.h"
const char * const DESCRIPTION = "Type and hapax accumulation curves";
const char * const AUTHOR = "<NAME>";
const char * const VERSION = "2014-05-15";
const char * const YEAR = "2014";
<file_sep>Type and hapax accumulation curves
==================================
This is a tool for analysing textual diversity, richness, and
productivity in text corpora and other data sets.
For more information, see
http://users.ics.aalto.fi/suomela/types2/
Downloading and compilation
---------------------------
See the section *Installing dependencies* below for information on how
to set the compilation environment. Then open a terminal and run:
git clone git://github.com/suomela/types.git
cd types
./config
make
make check
Examples
--------
See https://github.com/suomela/types-examples for examples.
Installing dependencies
-----------------------
### Ubuntu 15.04
Open a terminal and run:
sudo apt-get install git python-matplotlib python-lxml sqlite3 libsqlite3-dev
### Ubuntu 12.04
Open a terminal and run:
sudo apt-get install git python-matplotlib sqlite3 libsqlite3-dev
### Ubuntu 10.04
Open a terminal and run:
sudo apt-get install git-core python-lxml python-matplotlib sqlite3 libsqlite3-dev
### OS X Yosemite
These instructions should work on OS X 10.10 (Yosemite):
- Open Terminal.
- Install Homebrew: http://brew.sh/
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew doctor
brew update
- Run the following commands to install recent versions of *GCC*,
*Python*, and the Python modules that we need:
brew install python
brew install freetype
pip install --upgrade pip setuptools
pip install numpy
pip install matplotlib
pip install lxml
brew install gcc
Once you have followed the above instructions, `./config` should finish
successfully. In particular, it should find the following tools:
PYTHON = /usr/local/bin/python
CC = /usr/local/bin/gcc-5
### Windows 7
Download the Cygwin installation program (setup.exe): http://cygwin.com/
Run setup.exe. The default settings are usually fine:
- "Install from Internet"
- Root directory: C:\cygwin
- Local Package Directory: for example, C:\cygwinpkg
- "Direct Connection"
- Select a mirror site that is near you
- Do not select any packages yet
- "Create icon on Desktop", "Add icon to Start Menu"
If everything goes fine, you should have a "Cygwin Terminal" icon on
your desktop.
Next, we will install some packages. Run setup.exe again.
It should remember all settings that you have selected so far;
just hit "next" until you get the "Select Packages" dialog.
Then select the latest versions of the following packages:
git
gcc4
make
python
python-numpy
pkg-config
sqlite3
wget
libsqlite3-devel
libxslt-devel
libfreetype-devel
libpng-devel
Next, open Cygwin Terminal.
Run `python --version` to find your Python version. Go to
http://pypi.python.org/pypi/setuptools and download and install
the right version of setuptools ("Python Egg"). For example, if your
Python version is 2.6, then you can use the following commands:
wget http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11-py2.6.egg
sh setuptools-0.6c11-py2.6.egg
Once you have installed setuptools, you can use easy_install to install
the remaining Python modules that we need:
easy_install lxml
easy_install matplotlib
If all goes fine, you are now ready to follow the usual installation
procedure: use `git` to download the software, run `./config`, etc.
Just keep in mind that you must do everything in Cygwin Terminal.
However, once the software finishes, you can of course browse the
results with more user-friendly tools.
---
If you see any error messages that suggest "... try running rebaseall",
follow the instructions here: http://cygwin.wikia.com/wiki/Rebaseall
In brief, you will need do the following and try again:
- Exit Cygwin terminal
- Run C:\cygwin\bin\ash.exe
- In ash.exe, enter the following commands:
/bin/rebaseall
exit
- Re-open Cygwin terminal
In our experiments, we encountered this issue during the installation
of matplotlib on Windows XP, but not on Windows 7.
License
-------
You can distribute everything under the BSD 3-clause license:
http://opensource.org/licenses/BSD-3-Clause
See below for details.
### SFMT and SFMTJump
Copyright (c) 2006,2007 <NAME>, <NAME> and Hiroshima
University.
Copyright (c) 2012 <NAME>, <NAME>, Hiroshima University
and The University of Tokyo.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the names of Hiroshima University, The University of
Tokyo nor the names of its contributors may be used to endorse
or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### Other parts
Copyright (c) 2014, <NAME>.
Enjoy, use at your own risk.
To contact the author, see http://users.ics.aalto.fi/suomela/
You can use any of the following licenses to distribute this software:
- MIT license, http://opensource.org/licenses/MIT
- BSD 2-clause license, http://opensource.org/licenses/BSD-2-Clause
- BSD 3-clause license, http://opensource.org/licenses/BSD-3-Clause
The BSD 3-clause license might be most convenient, as it is the same
license under which SFMT is distributed.
For your convenience, here is the text of the MIT license.
----
Copyright (c) 2014 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
<file_sep># coding=utf-8
from collections import defaultdict, Counter, namedtuple
import math
import optparse
import cPickle
import os
import os.path
import re
import sqlite3
import string
import sys
import numpy as np
import TypesDatabase
import TypesParallel
import TypesPlot
from lxml.builder import E
TOOL = 'types-plot'
PLOT_DIR = 'plot'
HTML_DIR = 'html'
BIN_DIR = 'bin'
DATA_FILE = 'types-plot.pickle'
DEFAULT_GROUP = "default"
N_COMMON = 3
FDR = [0.001, 0.01, 0.1]
def msg(msg):
sys.stderr.write("%s: %s\n" % (TOOL, msg))
def none_to_empty(x):
return '' if x is None else x
def classes(l):
if len(l) == 0:
return {}
else:
return { "class": " ".join(l) }
def firstlast(i, rowlist):
l = []
if i == 0:
l.append('first')
if i == len(rowlist) - 1:
l.append('last')
return classes(l)
def get_args():
parser = optparse.OptionParser(
description='Update all plots.',
version=TypesDatabase.version_string(TOOL),
)
parser.add_option('--db', metavar='FILE', dest='db',
help='which database to read [default: %default]',
default=TypesDatabase.DEFAULT_FILENAME)
TypesParallel.add_options(parser)
parser.add_option('--type-lists', dest='with_typelists', action='store_true',
help='produce type lists',
default=False)
parser.add_option('--sample-lists', dest='with_samplelists', action='store_true',
help='produce sample lists',
default=False)
parser.add_option('--slides', dest='slide_version', action='store_true',
help='presentation slide version',
default=False)
parser.add_option('--plotdir', metavar='DIRECTORY', dest='plotdir',
help='where to store PDF plots [default: %default]',
default=PLOT_DIR)
parser.add_option('--htmldir', metavar='DIRECTORY', dest='htmldir',
help='where to store SVG plots and HTML files [default: %default]',
default=HTML_DIR)
(options, args) = parser.parse_args()
return options
# seq() is a generator that produces
# a, b, ..., z, aa, ab, ..., zz, aaa, aab, ...
C = string.ascii_lowercase
def seqd(depth, prefix):
if depth <= 0:
yield prefix
else:
for c in C:
for s in seqd(depth - 1, prefix + c):
yield s
def seq():
depth = 1
while True:
for s in seqd(depth, ''):
yield s
depth += 1
# Convert arbitrary strings to safe, unique filenames
OKCHAR = re.compile(r'[a-zA-Z0-9]+')
class Filenames:
def __init__(self):
self.map = dict()
self.used = set()
def generate(self, s):
if s in self.map:
return
suffixes = seq()
prefix = []
for ok in OKCHAR.finditer(s):
prefix.append(ok.group().lower())
if len(prefix) == 0:
suffix = [ suffixes.next() ]
else:
suffix = []
while True:
candidate = '-'.join(prefix + suffix)
assert len(candidate) > 0
if candidate not in self.used:
break
suffix = [ suffixes.next() ]
self.used.add(candidate)
self.map[s] = candidate
class SampleData:
pass
Context = namedtuple('Context', [
'corpuscode', 'samplecode', 'datasetcode', 'tokencode',
'before', 'word', 'after', 'link'
])
class AllCurves:
def __init__(self):
self.curves = []
self.statcode_stat = dict()
self.statcode_label = dict()
self.by_corpus = defaultdict(list)
self.by_dataset = defaultdict(list)
self.by_stat = defaultdict(list)
self.by_corpus_dataset = defaultdict(list)
self.by_corpus_stat = defaultdict(list)
self.by_dataset_stat = defaultdict(list)
self.by_dataset_stat_fallback = dict()
self.by_corpus_dataset_stat = dict()
self.result_q = []
def read_curves(self, args, conn):
sys.stderr.write('%s: read:' % TOOL)
if args.slide_version:
layout = TypesPlot.layout_slides
else:
layout = TypesPlot.layout_normal
listings = [None]
if args.with_typelists:
listings += ['t']
if args.with_samplelists:
listings += ['s']
self.with_lists = len(listings) > 1
dirdict = {
"pdf": args.plotdir,
"svg": args.htmldir,
"html": args.htmldir,
"tmp.svg": args.htmldir,
}
self.file_corpus = Filenames()
self.file_stat = Filenames()
self.file_dataset = Filenames()
self.file_group = Filenames()
self.file_collection = Filenames()
### log
timestamp_by_logid = dict()
def get_timestamp(logid):
if logid not in timestamp_by_logid:
ts = [ r[0] for r in conn.execute("SELECT STRFTIME('%s', timestamp) FROM log WHERE id = ?", (logid,)) ]
assert len(ts) == 1
timestamp_by_logid[logid] = int(ts[0])
return timestamp_by_logid[logid]
### stat
sys.stderr.write(' stat')
r = conn.execute('''
SELECT statcode, x, y, xlabel.labeltext, ylabel.labeltext
FROM stat
JOIN label AS ylabel ON stat.y = ylabel.labelcode
JOIN label AS xlabel ON stat.x = xlabel.labelcode
ORDER BY statcode
''')
for statcode, x, y, xlabel, ylabel in r:
self.file_stat.generate(statcode)
self.statcode_stat[statcode] = (x, y)
self.statcode_label[statcode] = (xlabel, ylabel)
### corpus
corpus_descr = dict()
sys.stderr.write(' corpus')
r = conn.execute('''
SELECT corpuscode, description
FROM corpus
ORDER BY corpuscode
''')
for corpuscode, description in r:
self.file_corpus.generate(corpuscode)
corpus_descr[corpuscode] = description
### dataset
dataset_descr = dict()
sys.stderr.write(' dataset')
r = conn.execute('''
SELECT corpuscode, datasetcode, description
FROM dataset
ORDER BY corpuscode, datasetcode
''')
for corpuscode, datasetcode, description in r:
self.file_dataset.generate(datasetcode)
dataset_descr[(corpuscode, datasetcode)] = description
### sample
corpus_size = dict()
sys.stderr.write(' sample')
r = conn.execute('''
SELECT corpuscode, COUNT(*), SUM(wordcount)
FROM sample
GROUP BY corpuscode
''')
for corpuscode, samplecount, wordcount in r:
corpus_size[corpuscode] = (samplecount, wordcount)
### token
dataset_size = dict()
sys.stderr.write(' token')
r = conn.execute('''
SELECT corpuscode, datasetcode, COUNT(DISTINCT tokencode), SUM(tokencount)
FROM token
GROUP BY corpuscode, datasetcode
''')
for corpuscode, datasetcode, typecount, tokencount in r:
dataset_size[(corpuscode, datasetcode)] = (typecount, tokencount)
### result_curve
sys.stderr.write(' result_curve')
r = conn.execute('''
SELECT corpuscode, statcode, datasetcode, id, level, side, logid
FROM result_curve
ORDER BY corpuscode, statcode, datasetcode
''')
for corpuscode, statcode, datasetcode, curveid, level, side, logid in r:
k = (corpuscode, datasetcode, statcode)
totals = {
'type': dataset_size[(corpuscode,datasetcode)][0],
'hapax': None,
'token': dataset_size[(corpuscode,datasetcode)][1],
'word': corpus_size[corpuscode][1],
}
if k not in self.by_corpus_dataset_stat:
xkey, ykey = self.statcode_stat[statcode]
xlabel, ylabel = self.statcode_label[statcode]
xtotal, ytotal = totals[xkey], totals[ykey]
c = TypesPlot.Curve(
layout,
dirdict,
corpuscode, self.file_corpus.map[corpuscode],
corpus_descr[corpuscode],
statcode, self.file_stat.map[statcode],
xlabel, ylabel,
xtotal, ytotal,
datasetcode, self.file_dataset.map[datasetcode],
dataset_descr[(corpuscode, datasetcode)],
listings
)
c.levels = defaultdict(dict)
self.curves.append(c)
self.by_corpus[corpuscode].append(c)
self.by_dataset[datasetcode].append(c)
self.by_stat[statcode].append(c)
self.by_corpus_stat[(corpuscode, statcode)].append(c)
self.by_corpus_dataset[(corpuscode, datasetcode)].append(c)
self.by_dataset_stat[(datasetcode, statcode)].append(c)
self.by_corpus_dataset_stat[k] = c
else:
c = self.by_corpus_dataset_stat[k]
c.add_timestamp(get_timestamp(logid))
c.levels[level][side] = curveid
### result_curve_point
sys.stderr.write(' result_curve_point')
def get_one_path(curveid):
return np.array(list(conn.execute('''
SELECT x, y
FROM result_curve_point
WHERE curveid = ?
ORDER BY x
''', (curveid,))), dtype=np.int32)
for c in self.curves:
for level in sorted(c.levels.keys()):
d = c.levels[level]
if 'upper' in d and 'lower' in d:
upper = get_one_path(d['upper'])
lower = get_one_path(d['lower'])
c.add_poly(level, upper, lower)
### collection
sys.stderr.write(' collection')
r = conn.execute('''
SELECT corpuscode, groupcode, collectioncode, description
FROM collection
ORDER BY corpuscode, groupcode, collectioncode
''')
for corpuscode, groupcode, collectioncode, description in r:
if groupcode is None:
groupcode = DEFAULT_GROUP
self.file_group.generate(groupcode)
self.file_collection.generate(collectioncode)
if corpuscode in self.by_corpus:
for c in self.by_corpus[corpuscode]:
c.add_collection(
groupcode, self.file_group.map[groupcode],
collectioncode, self.file_collection.map[collectioncode],
description
)
### result_p
sys.stderr.write(' result_p')
r = conn.execute('''
SELECT corpuscode, collectioncode, datasetcode, statcode, y, x, above, below, total, logid
FROM result_p
''')
for corpuscode, collectioncode, datasetcode, statcode, y, x, above, below, total, logid in r:
k1 = (corpuscode, datasetcode, statcode)
p = TypesPlot.Point(collectioncode, y, x, above, below, total, -FDR[-1])
self.by_corpus_dataset_stat[k1].add_point(p, get_timestamp(logid))
### result_q
sys.stderr.write(' result_q')
r = conn.execute('''
SELECT corpuscode, collectioncode, datasetcode, statcode, side, p, q
FROM result_q
ORDER BY i
''')
for row in r:
self.result_q.append(row)
if self.with_lists:
self.typelist_cache = {}
self.samplelist_cache = {}
self.sample_cache = {}
self.sampleset_by_collection = defaultdict(set)
self.sampleset_by_corpus = defaultdict(set)
self.collectionset_by_sample = defaultdict(set)
self.collectionset_by_token = defaultdict(set)
self.sampleset_by_token = defaultdict(set)
self.tokenset_by_sample = defaultdict(set)
self.sample_info = {}
self.tokenset_by_dataset = defaultdict(set)
self.token_short = {}
self.tokencount_by_token = Counter()
self.tokencount_by_sample = Counter()
self.tokencount_by_sample_token = defaultdict(Counter)
self.context_by_sample = defaultdict(list)
self.context_by_token = defaultdict(list)
self.file_sample = Filenames()
self.file_token = Filenames()
### sample
sys.stderr.write(' sample')
try:
r = conn.execute('''
SELECT corpuscode, samplecode, wordcount, description, link
FROM sample
''')
except sqlite3.OperationalError:
r = conn.execute('''
SELECT corpuscode, samplecode, wordcount, description, NULL
FROM sample
''')
for corpuscode, samplecode, wordcount, description, link in r:
self.file_sample.generate(samplecode)
self.sampleset_by_corpus[corpuscode].add(samplecode)
self.sample_info[(corpuscode, samplecode)] = (wordcount, description, link)
### sample_collection
sys.stderr.write(' sample_collection')
r = conn.execute('''
SELECT corpuscode, samplecode, collectioncode
FROM sample_collection
''')
for corpuscode, samplecode, collectioncode in r:
self.sampleset_by_collection[(corpuscode, collectioncode)].add(samplecode)
self.collectionset_by_sample[(corpuscode, samplecode)].add(collectioncode)
### token
sys.stderr.write(' token')
r = conn.execute('''
SELECT corpuscode, samplecode, datasetcode, tokencode, tokencount
FROM token
''')
for corpuscode, samplecode, datasetcode, tokencode, tokencount in r:
self.file_token.generate(tokencode)
self.sampleset_by_token[(corpuscode, datasetcode, tokencode)].add(samplecode)
self.tokenset_by_sample[(corpuscode, datasetcode, samplecode)].add(tokencode)
self.tokenset_by_dataset[(corpuscode, datasetcode)].add(tokencode)
self.token_short[(corpuscode, datasetcode, tokencode)] = tokencode
self.tokencount_by_token[(corpuscode, datasetcode, tokencode)] += tokencount
self.tokencount_by_sample[(corpuscode, datasetcode, samplecode)] += tokencount
self.tokencount_by_sample_token[(corpuscode, datasetcode, samplecode)][tokencode] += tokencount
collectioncodes = self.collectionset_by_sample[(corpuscode, samplecode)]
for c in collectioncodes:
self.collectionset_by_token[(corpuscode, datasetcode, tokencode)].add(c)
### tokeninfo
sys.stderr.write(' tokeninfo')
r = list(conn.execute('''
SELECT COUNT(*)
FROM sqlite_master
WHERE type='table' AND name='tokeninfo'
'''))
if r[0][0] > 0:
r = conn.execute('''
SELECT corpuscode, datasetcode, tokencode, shortlabel, longlabel
FROM tokeninfo
''')
for corpuscode, datasetcode, tokencode, shortlabel, longlabel in r:
self.token_short[(corpuscode, datasetcode, tokencode)] = shortlabel
### context
sys.stderr.write(' context')
r = list(conn.execute('''
SELECT COUNT(*)
FROM sqlite_master
WHERE type='table' AND name='context'
'''))
if r[0][0] > 0:
r = conn.execute('''
SELECT corpuscode, samplecode, datasetcode, tokencode,
before, word, after, link
FROM context
''')
for row in r:
c = Context(*row)
self.context_by_token[(c.corpuscode, c.datasetcode, c.tokencode)].append(c)
self.context_by_sample[(c.corpuscode, c.datasetcode, c.samplecode)].append(c)
sys.stderr.write('\n')
### fallbacks
for datasetcode, statcode in self.by_dataset_stat.keys():
l = []
for corpuscode in sorted(self.by_corpus.keys()):
if (corpuscode, datasetcode, statcode) in self.by_corpus_dataset_stat:
c = self.by_corpus_dataset_stat[(corpuscode, datasetcode, statcode)]
elif (corpuscode, statcode) in self.by_corpus_stat:
c = self.by_corpus_stat[(corpuscode, statcode)][0]
elif (corpuscode, datasetcode) in self.by_corpus_dataset:
c = self.by_corpus_dataset[(corpuscode, datasetcode)][0]
else:
c = self.by_corpus[corpuscode][0]
l.append(c)
self.by_dataset_stat_fallback[(datasetcode, statcode)] = l
def create_directories(self):
directories = set()
for c in self.curves:
directories.update(c.get_directories())
for d in directories:
if not os.path.exists(d):
os.makedirs(d)
def generate_html(self):
for c in self.curves:
sys.stderr.write('.')
c.generate_html(self)
def generate_corpus_menu(self):
tablerows = []
cell = E.td("Corpora", colspan="2")
tablerows.append(E.tr(cell, **classes(['head'])))
corpuslist = sorted(self.by_corpus.keys())
for i, corpuscode in enumerate(corpuslist):
c = self.by_corpus[corpuscode][0]
cells = [
E.td(E.a(corpuscode, href=c.get_pointname_from_root('html', None))),
E.td(none_to_empty(c.corpus_descr), **classes(['wrap', 'small'])),
]
tablerows.append(E.tr(*cells, **firstlast(i, corpuslist)))
return tablerows
def generate_fdr_table(self):
blocks = []
current = None
fdri = 0
for row in self.result_q:
corpuscode, collectioncode, datasetcode, statcode, side, p, q = row
while fdri < len(FDR) and q > FDR[fdri]:
fdri += 1
current = None
if fdri == len(FDR):
break
if current is None:
current = []
blocks.append((fdri, current))
current.append(row)
small = classes(['small'])
tablerows = []
for fdri, block in blocks:
text = u"Findings — false discovery rate %s" % FDR[fdri]
cell = E.td(text, colspan="6")
l = ['head']
if len(tablerows) > 0:
l.append('sep')
tablerows.append(E.tr(cell, **classes(l)))
for i, row in enumerate(block):
corpuscode, collectioncode, datasetcode, statcode, side, p, q = row
c = self.by_corpus_dataset_stat[(corpuscode, datasetcode, statcode)]
groupcode = c.group_by_collection[collectioncode]
point = c.point_by_collection[collectioncode]
point.fdr = FDR[fdri]
desc = c.collection_descr[collectioncode]
lh = u"−" if side == "below" else "+"
x, y = self.statcode_label[statcode]
attr = dict()
if desc is not None:
attr["title"] = desc
attr["href"] = c.get_pointname_from_root('html', groupcode, point)
cells = [
E.td(E.a(collectioncode, **attr)),
E.td(lh),
E.td("%s/%s" % (y,x), **small),
E.td(datasetcode, **small),
E.td(corpuscode, **small),
E.td("%.5f" % p, **small),
]
tablerows.append(E.tr(*cells, **firstlast(i, block)))
return tablerows
def generate_index(self, htmldir):
sys.stderr.write('.')
headblocks = []
bodyblocks = []
headblocks.append(E.title("Corpus menu"))
headblocks.append(E.link(rel="stylesheet", href="types.css", type="text/css"))
tablerows = self.generate_corpus_menu()
bodyblocks.append(E.div(E.table(*tablerows), **classes(["mainmenu"])))
tablerows = self.generate_fdr_table()
if len(tablerows) > 0:
bodyblocks.append(E.div(E.table(*tablerows), **classes(["findings"])))
doc = E.html(E.head(*headblocks), E.body(*bodyblocks))
with open(os.path.join(htmldir, "index.html"), 'w') as f:
TypesPlot.write_html(f, doc)
with open(os.path.join(htmldir, "types.css"), 'w') as f:
f.write(CSS)
def get_context_filename_sample(self, datasetcode, samplecode):
b = TypesPlot.cleanlist([
'',
's',
self.file_dataset.map[datasetcode],
self.file_sample.map[samplecode],
])
return '_'.join(b) + '.html'
def get_context_filename_token(self, datasetcode, tokencode, collectioncode=None):
b = TypesPlot.cleanlist([
'',
't',
self.file_dataset.map[datasetcode],
self.file_token.map[tokencode],
None if collectioncode is None else self.file_collection.map[collectioncode],
])
return '_'.join(b) + '.html'
def sample_link(self, corpuscode, datasetcode, samplecode, tokencode=None):
if (corpuscode, datasetcode, samplecode) not in self.context_by_sample:
return samplecode
else:
link = self.get_context_filename_sample(datasetcode, samplecode)
if tokencode is not None:
link += "#t{}".format(self.file_token.map[tokencode])
return E.a(samplecode, href=link)
def token_link(self, corpuscode, datasetcode, tokencode, samplecode=None, collectioncode=None, shorten=True):
token = self.token_short[(corpuscode, datasetcode, tokencode)] if shorten else tokencode
flags = {}
if token != tokencode:
flags["title"] = tokencode
if (corpuscode, datasetcode, tokencode) not in self.context_by_token:
return E.span(token, **flags)
else:
link=self.get_context_filename_token(datasetcode, tokencode, collectioncode)
if samplecode is not None:
link += "#s{}".format(self.file_sample.map[samplecode])
return E.a(token, href=link, **flags)
def generate_context(self, htmldir):
for key in sorted(self.context_by_sample.keys()):
sys.stderr.write('.')
corpuscode, datasetcode, samplecode = key
title = samplecode
wordcount, descr, link = self.sample_info[(corpuscode, samplecode)]
if descr is None:
if link is None:
headtext = [E.p(samplecode)]
else:
headtext = [E.p(E.a(samplecode, href=link))]
else:
if link is None:
headtext = [E.p(samplecode, ": ", descr)]
else:
headtext = [E.p(samplecode, ": ", E.a(descr, href=link))]
filename = self.get_context_filename_sample(datasetcode, samplecode)
filename = os.path.join(htmldir, self.file_corpus.map[corpuscode], filename)
l = self.context_by_sample[(corpuscode, datasetcode, samplecode)]
self.generate_context_one(l, filename, title, headtext, "sample")
for key in sorted(self.context_by_token.keys()):
sys.stderr.write('.')
corpuscode, datasetcode, tokencode = key
collectioncodes = sorted(self.collectionset_by_token[key])
l_all = self.context_by_token[(corpuscode, datasetcode, tokencode)]
for collectioncode in [None] + collectioncodes:
if collectioncode is not None:
title = u'{} · {}'.format(tokencode, samplecode)
headtext = [E.p(
self.token_link(corpuscode, datasetcode, tokencode, shorten=False),
u' — ',
collectioncode
)]
sampleset = self.sampleset_by_collection[(corpuscode, collectioncode)]
l = [c for c in l_all if c.samplecode in sampleset]
else:
title = tokencode
if len(collectioncodes) > 0:
links = [
E.a(c, href=self.get_context_filename_token(datasetcode, tokencode, c))
for c in collectioncodes
]
headtext = [E.p(
tokencode,
u' — ',
*TypesPlot.add_sep(links, u' · ')
)]
else:
headtext = [E.p(tokencode)]
l = l_all
filename = self.get_context_filename_token(datasetcode, tokencode, collectioncode)
filename = os.path.join(htmldir, self.file_corpus.map[corpuscode], filename)
self.generate_context_one(l, filename, title, headtext, "token")
def generate_context_one(self, l, filename, title, headtext, what):
headblocks = []
bodyblocks = []
headblocks.append(E.title(title))
headblocks.append(E.link(rel="stylesheet", href="../types.css", type="text/css"))
headrow = [
E.td('Sample', colspan="2"),
E.td('Token', **classes(["pad"])),
E.td(E.span('Before'), **classes(["before"])),
E.td(E.span('Word'), **classes(["word"])),
E.td(E.span('After'), **classes(["after"])),
]
bodyblocks.extend(headtext)
tablerows = [E.tr(*headrow, **classes(["head"]))]
grouped = defaultdict(list)
for c in l:
if what == "sample":
key = "t{}".format(self.file_token.map[c.tokencode])
elif what == "token":
key = "s{}".format(self.file_sample.map[c.samplecode])
else:
assert False
grouped[key].append(c)
for key in sorted(grouped.keys()):
ll = grouped[key]
ll = sorted(ll, key=lambda c: (c.after, c.before, c.word))
block = []
for c in ll:
row = []
wordcount, descr, link = self.sample_info[(c.corpuscode, c.samplecode)]
if descr is None:
if link is None:
dl = None
else:
dl = E.a('link', href=link)
else:
if link is None:
dl = descr
else:
dl = E.a(descr, href=link)
if what == "sample":
sample = c.samplecode
token = self.token_link(c.corpuscode, c.datasetcode, c.tokencode, c.samplecode)
elif what == "token":
sample = self.sample_link(c.corpuscode, c.datasetcode, c.samplecode, c.tokencode)
token = self.token_short[(c.corpuscode, c.datasetcode, c.tokencode)]
else:
assert False
before = none_to_empty(c.before)
word = none_to_empty(c.word)
after = none_to_empty(c.after)
if c.link is not None:
word = E.a(word, href=c.link)
if dl is None:
row = [
E.td(sample, colspan="2")
]
else:
row = [
E.td(sample),
E.td(dl),
]
row += [
E.td(token, **classes(["pad"])),
E.td(E.span(before), **classes(["before"])),
E.td(E.span(word), **classes(["word"])),
E.td(E.span(after), **classes(["after"])),
]
block.append(E.tr(*row))
tablerows.append(E.tbody(*block, id=key))
bodyblocks.append(E.div(E.table(*tablerows), **classes(["context"])))
doc = E.html(E.head(*headblocks), E.body(*bodyblocks))
with open(filename, 'w') as f:
TypesPlot.write_html(f, doc)
def find_outdated(self):
redraw = []
for c in self.curves:
for outdated in c.get_outdated():
redraw.append((c, outdated))
return redraw
def get_typelist(self, corpuscode, datasetcode, collectioncode):
k = (corpuscode, datasetcode, collectioncode)
if k not in self.typelist_cache:
self.typelist_cache[k] = self.calc_typelist(*k)
return self.typelist_cache[k]
def get_samplelist(self, corpuscode, datasetcode, collectioncode):
k = (corpuscode, datasetcode, collectioncode)
if k not in self.samplelist_cache:
self.samplelist_cache[k] = self.calc_samplelist(*k)
return self.samplelist_cache[k]
def get_sample(self, corpuscode, datasetcode, samplecode):
k = (corpuscode, datasetcode, samplecode)
if k not in self.sample_cache:
self.sample_cache[k] = self.calc_sample(*k)
return self.sample_cache[k]
def calc_typelist(self, corpuscode, datasetcode, collectioncode):
if collectioncode is None:
typelist = sorted(self.tokenset_by_dataset[(corpuscode, datasetcode)])
r = defaultdict(list)
for t in typelist:
tsamples = self.sampleset_by_token[(corpuscode, datasetcode, t)]
total = len(tsamples)
if total == 0:
continue
bracket = int(math.log(total, 2))
r[bracket].append((t, total))
tables = []
brackets = sorted(r.keys())
for bracket in brackets:
table = []
l = sorted(r[bracket], key=lambda x: (-x[1], x[0]))
for t, total in l:
table.append(E.tr(
bar(total, 'bara', bracket=bracket),
E.td(E.span(self.token_link(corpuscode, datasetcode, t))),
title=u"{}: {} samples".format(t, total)
))
tables.append(E.table(*table))
else:
csamples = self.sampleset_by_collection[(corpuscode, collectioncode)]
typelist = sorted(self.tokenset_by_dataset[(corpuscode, datasetcode)])
r = defaultdict(list)
for t in typelist:
tsamples = self.sampleset_by_token[(corpuscode, datasetcode, t)]
here = len(tsamples & csamples)
other = len(tsamples - csamples)
total = here + other
if total == 0:
continue
bracket = int(math.log(total, 2))
ratio = here / float(total)
r[bracket].append((t, here, other, ratio))
tables = []
brackets = sorted(r.keys())
for bracket in brackets:
table = []
l = sorted(r[bracket], key=lambda x: (-x[3], -x[1], x[2], x[0]))
for t, here, other, ratio in l:
if here > 0:
tokenlink = self.token_link(corpuscode, datasetcode, t, collectioncode=collectioncode)
else:
tokenlink = self.token_short[(corpuscode, datasetcode, t)]
table.append(E.tr(
bar(here, 'bara', bracket=bracket),
bar(other, 'barb', bracket=bracket),
E.td(tokenlink),
title=u"{} — {}: {} samples, other: {} samples".format(t, collectioncode, here, other)
))
tables.append(E.table(*table))
return [E.table(
E.tr(E.td(u"Types that occur in…", colspan="{}".format(len(brackets)))),
E.tr(*[E.td(descr_bracket(bracket)) for bracket in brackets], **{"class": "head"}),
E.tr(*[E.td(x) for x in tables], **{"class": "first last"}),
)]
def calc_sample(self, corpuscode, datasetcode, samplecode):
s = SampleData()
s.samplecode = samplecode
skey = (corpuscode, datasetcode, samplecode)
s.wordcount, s.descr, s.link = self.sample_info[(corpuscode, samplecode)]
typelist = sorted(self.tokenset_by_sample[skey])
s.collections = sorted(self.collectionset_by_sample[(corpuscode, samplecode)])
s.hapaxlist = []
s.otherlist = []
s.uniquelist = []
for t in typelist:
if self.tokencount_by_token[(corpuscode, datasetcode, t)] == 1:
s.hapaxlist.append(t)
elif len(self.sampleset_by_token[(corpuscode, datasetcode, t)]) == 1:
s.uniquelist.append(t)
else:
s.otherlist.append(t)
s.commonlist = self.tokencount_by_sample_token[skey].most_common(N_COMMON + 1)
if len(s.commonlist) > 0:
if len(s.commonlist) == N_COMMON + 1:
threshold = max(s.commonlist[-1][1], 1)
else:
threshold = 1
s.commonlist = [(x,c) for x,c in s.commonlist if c > threshold]
s.commonlist = sorted(s.commonlist, key=lambda x: (-x[1], x[0]))
s.tokencount = self.tokencount_by_sample[skey]
s.typecount = len(typelist)
s.uniquecount = len(s.uniquelist) + len(s.hapaxlist)
s.hapaxcount = len(s.hapaxlist)
return s
def calc_samplelist(self, corpuscode, datasetcode, collectioncode):
if collectioncode is not None:
csamples = self.sampleset_by_collection[(corpuscode, collectioncode)]
else:
csamples = self.sampleset_by_corpus[corpuscode]
l = []
maxwords = 1
maxtokens = 1
maxtypes = 1
for samplecode in csamples:
s = self.get_sample(corpuscode, datasetcode, samplecode)
l.append(s)
maxwords = max(maxwords, s.wordcount)
maxtokens = max(maxtokens, s.tokencount)
maxtypes = max(maxtypes, s.typecount)
l = sorted(l, key=lambda s: (-s.wordcount, s.samplecode))
tablerows = []
for s in l:
clist = []
for t,c in s.commonlist:
if len(clist) > 0:
clist.append(', ')
clist.append(self.token_link(corpuscode, datasetcode, t, s.samplecode))
clist.append(u"\u202F×\u202F{}".format(c))
ulist = [self.token_link(corpuscode, datasetcode, t, s.samplecode) for t in s.uniquelist + s.hapaxlist]
tablerows.append([
E.td(self.sample_link(corpuscode, datasetcode, s.samplecode)),
E.td(none_to_empty(s.descr)),
E.td(str(s.wordcount), **{"class": "right"}),
bar(s.wordcount, 'bar', maxval=maxwords),
E.td(str(s.tokencount), **{"class": "right"}),
bar(s.tokencount, 'bar', maxval=maxtokens),
E.td(str(s.typecount), **{"class": "right"}),
bar(s.typecount, 'bar', maxval=maxtypes),
E.td(str(s.uniquecount), **{"class": "right"}),
bar(s.uniquecount, 'bar', maxval=maxtypes),
E.td(str(s.hapaxcount), **{"class": "right"}),
bar(s.hapaxcount, 'bar', maxval=maxtypes),
E.td(*clist),
E.td(*TypesPlot.add_sep(ulist, ', '), **{"class": "wrap"}),
])
table = [
E.tr(
E.td('Sample', colspan="2"),
E.td('Words', colspan="2"),
E.td('Tokens', colspan="2"),
E.td('Types', colspan="2"),
E.td('Unique', colspan="2"),
E.td('Hapaxes', colspan="2"),
E.td('Common types'),
E.td('Unique types', **{"class": "wide"}),
**{"class": "head"}
)
]
for i, row in enumerate(tablerows):
table.append(E.tr(*row, **firstlast(i, tablerows)))
return [E.table(*table)]
def descr_bracket(bracket):
a = 2 ** bracket
b = 2 * a
if a == 1:
assert b == 2
return '{} sample'.format(a)
else:
return '< {} samples'.format(b)
def bar(x, label, bracket=None, maxval=None):
x = bar_scale(x, bracket, maxval)
return E.td(
E.span(
'',
style="border-left-width: {}px;".format(x)
),
**classes([label])
)
def bar_scale(x, bracket=None, maxval=None):
if bracket is not None:
scale = math.sqrt(2 ** bracket)
return int(round(5.0 * x / scale))
elif maxval is not None:
return int(round(25.0 * x / maxval))
else:
return x
def get_datafile(args):
return os.path.join(args.tmpdir, DATA_FILE)
def write_data(args, redraw):
with open(get_datafile(args), 'w') as f:
cPickle.dump(redraw, f, -1)
def run(args, nredraw):
cmds = []
for j in range(args.parts):
cmd = [ get_datafile(args), nredraw, args.parts, j+1 ]
cmds.append(cmd)
TypesParallel.Parallel(TOOL, 'types-draw-curves', cmds, args).run()
def main():
args = get_args()
if not os.path.exists(args.tmpdir):
os.makedirs(args.tmpdir)
conn = TypesDatabase.open_db(args.db)
ac = AllCurves()
ac.read_curves(args, conn)
conn.commit()
if len(ac.curves) == 0:
msg('there are no results in the database')
return
ac.create_directories()
sys.stderr.write('%s: write: (' % TOOL)
ac.generate_index(args.htmldir)
if ac.with_lists:
ac.generate_context(args.htmldir)
ac.generate_html()
sys.stderr.write(')\n')
redraw = ac.find_outdated()
nredraw = len(redraw)
if nredraw == 0:
msg('all files up to date')
else:
msg('outdated: %d files' % nredraw)
write_data(args, redraw)
run(args, nredraw)
os.remove(get_datafile(args))
msg('all done')
CSS = """
BODY {
color: #000;
background-color: #fff;
font-family: Helvetica, Arial, sans-serif;
padding: 0px;
margin: 15px;
}
.listing, .stats, .context {
font-size: 85%;
}
.menuitem {
font-size: 90%;
}
.small, .menudesc, .menudescinline {
font-size: 80%;
}
A:link {
color: <DARK>;
text-decoration: none;
}
A:visited {
color: <DARK>;
text-decoration: none;
}
A:hover, A:active {
text-decoration: underline;
}
TABLE {
border-collapse: collapse;
}
.mainmenu, .findings, .listing, .stats {
margin-left: 4px;
margin-bottom: 20px;
}
.findings, .listing, .stats, .context {
margin-top: 20px;
}
TD {
padding: 0px;
padding-top: 1px;
padding-bottom: 1px;
text-align: left;
vertical-align: top;
white-space: nowrap;
}
TD.right {
text-align: right;
}
TD+TD {
padding-left: 15px;
}
TD.pad {
padding-right: 15px;
}
TD.wrap {
white-space: normal;
}
TR.head>TD {
padding-top: 5px;
padding-bottom: 5px;
border-bottom: 1px solid #888;
}
TR.head.sep>TD {
padding-top: 30px;
}
TR.first>TD, .context TBODY>TR:first-child>TD {
padding-top: 5px;
}
TR.last>TD, .context TBODY>TR:last-child>TD {
padding-bottom: 5px;
border-bottom: 1px solid #888;
}
P {
margin: 0px;
margin-top: 3px;
margin-bottom: 3px;
padding: 0px;
}
.plot {
margin-top: 20px;
margin-bottom: 10px;
}
.menudesc {
margin-left: 30px;
}
.menuitem, .menutitle, .menudescinline {
display: inline-block;
padding-top: 1px;
padding-bottom: 1px;
padding-left: 2px;
padding-right: 2px;
border: 1px solid #fff;
margin-top: 1px;
margin-bottom: 1px;
margin-left: 1px;
margin-right: 1px;
}
.menuitem, .menutitle {
white-space: nowrap;
}
.menu A:hover, .menu A:link, .menu A:visited {
text-decoration: none;
}
.menusel {
border: 1px solid #000;
background-color: #fff;
}
A.menuitem:hover, A.menutitle:hover {
border: 1px dotted #000;
background-color: #eee;
}
TD.bar {
padding-left: 5px;
}
TD.bara {
text-align: right;
}
TD.barb {
padding-left: 1px;
}
TD.barb+TD {
padding-left: 5px;
}
TD.bar>SPAN, TD.bara>SPAN {
border-left: 0px solid <DARK>;
}
TD.barb>SPAN {
border-left: 0px solid <LIGHT>;
}
TD.wide {
min-width: 40ex;
}
TD.before {
text-align: right;
}
TD.word {
text-align: center;
}
TD.after {
text-align: left;
}
TD.before, TD.after {
overflow: hidden;
position: relative;
width: 50%;
}
TD.before SPAN {
position: absolute;
right: 0px;
}
TD.after SPAN {
position: absolute;
left: 15px;
}
.menusel {
color: #000;
}
A.menusame, A.menutitle {
color: <DARK>;
}
A.menuother {
color: #888;
}
TBODY:target {
background-color: #eee;
}
"""
CSS = CSS.replace('<DARK>', '#' + TypesPlot.REGIONS_RGB[0])
CSS = CSS.replace('<LIGHT>', '#' + TypesPlot.REGIONS_RGB[2])
main()
<file_sep>import sys
if len(sys.argv) > 1:
sys.stderr.write('(')
import cPickle
import os
import os.path
import multiprocessing
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot
import TypesPlot
if len(sys.argv) == 1:
print "This tool is for internal use only."
print "See 'types-plot' for the user-friendly interface."
sys.exit(0)
def get_limit(nredraw, nproc, id):
assert 0 <= id <= nproc
if nredraw == nproc:
return id
elif id == 0:
return 0
elif id == nproc:
return nredraw
else:
frac = float(id) / float(nproc)
return int(nredraw * frac)
def load():
with open(datafile) as f:
redraw = cPickle.load(f)
return redraw
def do_plot(i):
c, outdated = redraw[i]
c.plot_group(matplotlib, outdated)
sys.stderr.write('.')
return True
dummy, datafile, nredraw, nproc, id = sys.argv
nredraw, nproc, id = [ int(a) for a in [ nredraw, nproc, id ]]
assert 1 <= id <= nproc
id -= 1
fro = get_limit(nredraw, nproc, id)
to = get_limit(nredraw, nproc, id+1)
if fro == to:
sys.exit(0)
redraw = load()
sys.stderr.write('!')
if sys.platform.startswith('cygwin'):
# Multiprocessing causes are DLL address conflicts
# that cannot be solved with "rebaseall".
# Workaround: disable parallelism on cygwin platforms
for i in range(fro, to):
assert do_plot(i)
else:
pool = multiprocessing.Pool()
results = []
for i in range(fro, to):
results.append(pool.apply_async(do_plot, [i]))
pool.close()
pool.join()
for r in results:
assert r.get()
sys.stderr.write(')')
<file_sep># coding=utf-8
from collections import namedtuple
import itertools
import os
import numpy as np
from lxml.builder import E
from lxml import etree
def colour(c):
return tuple([ int(c[2*i:2*i+2], 16)/float(255) for i in range(3) ])
def colours(l):
return [ colour(c) for c in l ]
# Colour scheme from:
# http://colorbrewer2.org/?type=sequential&scheme=PuBu&n=4
REGIONS_RGB = ('0570b0', '74a9cf', 'bdc9e1', 'f1eef6')
WHITE = colour('ffffff')
GREY = colour('999999')
DARK = colour('333333')
BLACK = colour('000000')
REGIONS = colours(REGIONS_RGB)
class CPoint:
def __init__(self, ec, fc, lw):
self.ec = ec
self.fc = fc
self.lw = lw
Layout = namedtuple('Layout', [
'width', 'height', 'dpi',
'label_sep', 'label_area', 'xsep',
'sel', 'unsel',
'xbins', 'spp',
])
layout_slides = Layout(
width = 6,
height = 3,
dpi = 96,
label_sep = 0.12,
label_area = (0.03, 0.97),
xsep = 0.05,
sel = CPoint( BLACK, WHITE, 1.5 ),
unsel = CPoint( GREY, WHITE, 1.0 ),
xbins = 5,
spp = {'left': 0.15, 'right': 0.77, 'bottom': 0.1, 'top': 0.98},
)
layout_normal = Layout(
width = 9,
height = 6,
dpi = 96,
label_sep = 0.06,
label_area = (0.03, 0.97),
xsep = 0.03,
sel = CPoint( BLACK, WHITE, 1.5 ),
unsel = CPoint( GREY, WHITE, 0.5 ),
xbins = None,
spp = {'left': 0.1, 'right': 0.85, 'bottom': 0.1, 'top': 0.98},
)
LISTING_LABEL = { None: 'summary', 't': 'type list', 's': 'sample list' }
AXIS_PAD = 0.02
def lim(maxval):
return (-AXIS_PAD * maxval, (1.0 + AXIS_PAD) * maxval)
def ucfirst(s):
if s == '':
return s
else:
return s[0].upper() + s[1:]
def add_sep(l, sep):
# [1,2,3] -> [1,sep,2,sep,3]
return [x for y in l for x in (y, sep)][:-1]
def write_html(f, doc):
f.write('<!DOCTYPE html>\n')
f.write(etree.tostring(doc, method='html', pretty_print=True))
def longest_common_prefix(a, b):
i = 0
while i < len(a) and i < len(b) and a[i] == b[i]:
i += 1
return i
def wrap_svg_link(el, url, title=None):
link = etree.Element("a")
link.set('{http://www.w3.org/1999/xlink}href', url)
if title is not None:
link.set('{http://www.w3.org/1999/xlink}title', title)
link.set('target', '_top')
parent = el.getparent()
assert parent is not None
parent.replace(el, link)
link.append(el)
def cleanlist(l):
l = ['' if x is None else x for x in l]
while len(l) > 0 and l[-1] == '':
l = l[:-1]
return l
class LabelPlacement:
def __init__(self, layout):
self.layout = layout
self.freelist = set()
self.freelist.add(self.layout.label_area)
def place(self, y):
closest = None
bestdist = None
bestplace = None
for free in self.freelist:
a, b = free
if y < a:
dist = a - y
place = a
elif a <= y <= b:
dist = 0.0
place = y
elif b < y:
dist = y - b
place = b
else:
assert False
if bestdist is None or bestdist > dist or (bestdist == dist and free < closest):
closest = free
bestdist = dist
bestplace = place
if closest is None:
return None
self.freelist.remove(closest)
y1, y4 = closest
y2 = bestplace - self.layout.label_sep
y3 = bestplace + self.layout.label_sep
if y1 < y2:
self.freelist.add((y1, y2))
if y3 < y4:
self.freelist.add((y3, y4))
return bestplace
class Point:
def __init__(self, collectioncode, y, x, above, below, total, fdr):
self.collectioncode = collectioncode
self.y = y
self.x = x
if above < below:
is_above = True
self.side = 'above'
self.pvalue = float(above)/float(total)
else:
is_above = False
self.side = 'below'
self.pvalue = float(below)/float(total)
# negative if larger
self.fdr = fdr
self.ms = 7
self.marker = 'o'
if self.side is None:
pass
elif self.pvalue > 0.01:
pass
elif is_above:
self.ms = 10
self.marker = '^'
else:
self.ms = 10
self.marker = 'v'
self.ec = BLACK
self.fc = WHITE
self.lw = 1.0
class Curve:
def __init__(self, layout, dirdict,
corpuscode, corpus_filename, corpus_descr,
statcode, stat_filename,
xlabel, ylabel, xtotal, ytotal,
datasetcode, dataset_filename, dataset_descr,
listings):
self.layout = layout
self.dirdict = dirdict
self.corpuscode = corpuscode
self.corpus_filename = corpus_filename
self.corpus_descr = corpus_descr
self.statcode = statcode
self.stat_filename = stat_filename
self.xlabel = xlabel
self.ylabel = ylabel
self.xtotal = xtotal
self.ytotal = ytotal
self.datasetcode = datasetcode
self.dataset_filename = dataset_filename
self.dataset_descr = dataset_descr
self.timestamp = None
self.collection_descr = dict()
self.collection_filenames = dict()
self.group_by_collection = dict()
self.group_filenames = dict()
self.point_by_collection = dict()
self.points_by_group = dict()
self.groups = []
self.group_set = set()
self.timestamp_by_group = dict()
self.polys = []
self.maxx = 0
self.maxy = 0
self.group_seen(None)
self.listings = listings
def group_seen(self, groupcode):
if groupcode not in self.group_set:
self.points_by_group[groupcode] = []
self.groups.append(groupcode)
self.group_set.add(groupcode)
self.points_by_group[groupcode] = []
def add_timestamp(self, timestamp):
if self.timestamp is None:
self.timestamp = timestamp
else:
self.timestamp = max(self.timestamp, timestamp)
def add_timestamp_group(self, timestamp, groupcode):
if groupcode not in self.timestamp_by_group:
self.timestamp_by_group[groupcode] = timestamp
else:
self.timestamp_by_group[groupcode] = max(self.timestamp_by_group[groupcode], timestamp)
def add_poly(self, level, upper, lower):
poly = np.concatenate((upper, np.flipud(lower)))
maxs = np.amax(poly, axis=0)
self.polys.append(poly)
self.maxx = max(self.maxx, maxs[0])
self.maxy = max(self.maxy, maxs[1])
def add_collection(self, groupcode, group_filename,
collectioncode, collection_filename, description):
self.group_filenames[groupcode] = group_filename
self.group_by_collection[collectioncode] = groupcode
self.collection_filenames[collectioncode] = collection_filename
self.collection_descr[collectioncode] = description
def add_point(self, p, timestamp):
assert p.collectioncode not in self.point_by_collection
self.point_by_collection[p.collectioncode] = p
groupcode = self.group_by_collection[p.collectioncode]
self.group_seen(groupcode)
self.points_by_group[groupcode].append(p)
self.add_timestamp_group(timestamp, groupcode)
def get_suffixes(self, p=None):
if p is None:
return ['pdf', 'svg']
else:
return ['svg']
def get_pointname(self, suffix, groupcode, p=None, l=None):
b = cleanlist([
self.stat_filename,
self.dataset_filename,
None if groupcode is None else self.group_filenames[groupcode],
None if p is None else self.collection_filenames[p.collectioncode],
None if l is None else l,
])
return '_'.join(b) + '.' + suffix
def get_pointname_from_root(self, suffix, groupcode, p=None, l=None):
return self.corpus_filename + "/" + self.get_pointname(suffix, groupcode, p, l)
def get_pointname_relative(self, other, suffix, groupcode, collectioncode=None, l=None):
changed = False
if groupcode is not None and groupcode not in self.group_set:
groupcode = None
changed = True
if groupcode is None and collectioncode is not None:
collectioncode = None
changed = True
if collectioncode is not None and collectioncode not in self.point_by_collection:
collectioncode = None
changed = True
if collectioncode is not None:
exp = self.group_by_collection[collectioncode]
if exp != groupcode:
changed = True
collectioncode = None
if collectioncode is not None:
p = self.point_by_collection[collectioncode]
else:
p = None
name = self.get_pointname(suffix, groupcode, p, l)
if self.corpuscode == other.corpuscode:
full = name
else:
full = "../" + self.corpus_filename + "/" + name
return full, changed
def get_directory(self, suffix):
return os.path.join(self.dirdict[suffix], self.corpus_filename)
def get_filename(self, suffix, groupcode, p=None, l=None):
return os.path.join(self.get_directory(suffix), self.get_pointname(suffix, groupcode, p, l))
def get_directories(self):
return [ self.get_directory(suffix) for suffix in self.get_suffixes() ]
def get_filenames(self, groupcode, p=None):
return [ self.get_filename(suffix, groupcode, p) for suffix in self.get_suffixes(p) ]
def is_outdated(self, groupcode):
for filename in self.get_filenames(groupcode):
if not os.path.exists(filename):
return True
mtime = os.path.getmtime(filename)
if mtime < self.timestamp:
return True
if groupcode in self.timestamp_by_group and mtime < self.timestamp_by_group[groupcode]:
return True
return False
def get_outdated(self):
outdated = []
for groupcode in sorted(self.points_by_group.keys()):
if self.is_outdated(groupcode):
outdated.append(groupcode)
return outdated
def plot_group(self, matplotlib, groupcode):
self.plot_group_points(matplotlib, groupcode, None)
for point in self.points_by_group[groupcode]:
self.plot_group_points(matplotlib, groupcode, point)
def plot_group_points(self, matplotlib, groupcode, point):
points = sorted(self.points_by_group[groupcode], key=lambda p: p.x, reverse=True)
fig = matplotlib.pyplot.figure(
figsize=(self.layout.width, self.layout.height),
subplotpars=matplotlib.figure.SubplotParams(**self.layout.spp)
)
ax = fig.add_subplot(111)
ax.set_autoscalex_on(False)
ax.set_autoscaley_on(False)
ax.set_xlim(lim(self.maxx))
ax.set_ylim(lim(self.maxy))
if self.layout.xbins != None:
ax.locator_params(axis='x', nbins=self.layout.xbins)
self.plot_polys(ax)
self.plot_points(ax, points, groupcode, point)
self.plot_labels(ax)
for suffix in self.get_suffixes(point):
if suffix == 'svg':
suffix2 = 'tmp.svg'
else:
suffix2 = suffix
filename = self.get_filename(suffix2, groupcode, point)
fig.savefig(filename)
if suffix == 'svg':
for listing in self.listings:
target = self.get_filename(suffix, groupcode, point, listing)
self.add_svg_links(filename, target, points, groupcode, point, listing)
os.remove(filename)
matplotlib.pyplot.close(fig)
def plot_polys(self, ax):
for i, poly in enumerate(self.polys):
f = i/(len(self.polys)-1.0)
j = min(i, len(REGIONS)-1)
fill = REGIONS[-(j+1)]
ax.fill(poly[:,0], poly[:,1], fc=fill, ec=BLACK, linewidth=0.2, zorder=100 + f)
def plot_points(self, ax, points, groupcode, point):
placement = LabelPlacement(self.layout)
for i, p in enumerate(points):
scx, scy = float(p.x)/self.maxx, float(p.y)/self.maxy
stx = scx + self.layout.xsep
sty = placement.place(scy)
zbase = 201.0 - p.pvalue
if point is None:
cp = p
elif point == p:
cp = self.layout.sel
zbase += 100
else:
cp = self.layout.unsel
if sty is not None:
tx = stx * self.maxx
ty = sty * self.maxy
ax.plot(
[p.x, p.x, tx],
[p.y, ty, ty],
color=cp.ec,
linewidth=cp.lw,
clip_on=False,
zorder=zbase,
gid='types_pl_%d' % i,
)
ax.plot(
p.x, p.y,
marker=p.marker,
mec=cp.ec,
mfc=cp.fc,
mew=cp.lw,
ms=p.ms,
zorder=zbase + 2,
gid='types_pm_%d' % i,
)
if sty is not None:
ax.text(
tx, ty,
p.collectioncode,
color=cp.ec,
va='center',
bbox=dict(
boxstyle="round,pad=0.3",
fc=cp.fc,
ec=cp.ec,
linewidth=cp.lw,
),
zorder=zbase + 1,
gid='types_pt_%d' % i,
)
def plot_labels(self, ax):
ax.set_xlabel(ucfirst(self.xlabel), labelpad=10)
ax.set_ylabel(ucfirst(self.ylabel), labelpad=15)
def add_svg_links(self, filename, target, points, groupcode, point, listing):
with open(filename) as f:
svg = etree.parse(f)
for i, p in enumerate(points):
if point is not None and point == p:
url = self.get_pointname('html', groupcode)
else:
url = self.get_pointname('html', groupcode, p, listing)
title = self.collection_descr[p.collectioncode]
if title is None:
title = p.collectioncode
for what in ['pl', 'pm', 'pt']:
gid = 'types_%s_%d' % (what, i)
path = ".//{http://www.w3.org/2000/svg}g[@id='%s']" % gid
el = svg.find(path)
if el is not None:
wrap_svg_link(el, url, title)
with open(target, 'w') as f:
svg.write(f)
def generate_html(self, ac):
for groupcode in sorted(self.points_by_group.keys()):
ps = [None] + self.points_by_group[groupcode]
for p in ps:
for l in self.listings:
filename = self.get_filename('html', groupcode, p, l)
with open(filename, 'w') as f:
self.generate_html_one(f, groupcode, p, l, ac)
def generate_html_one(self, f, groupcode, point, listing, ac):
collectioncode = point.collectioncode if point is not None else None
headblocks = []
bodyblocks = []
t = [ self.corpuscode, self.datasetcode, groupcode, collectioncode, self.statcode ]
t = u" — ".join([a for a in t if a is not None])
headblocks.append(E.title(t))
headblocks.append(E.link(rel="stylesheet", href="../types.css", type="text/css"))
def add_menu(title, cl, gl, xl, ll, labelhook, titlelink=None, groupby=None, stat=None):
prev = []
prevj = 0
result = []
count = len(cl) * len(gl) * len(xl) * len(ll)
for c, g, x, l in itertools.product(cl, gl, xl, ll):
addbreak = False
label, desc = labelhook(c, g, x, l)
selected = c == self and g is groupcode and x is collectioncode and l is listing
if groupby is not None and count >= 5:
cur = label.split(groupby)
# A heuristic rule that tries to produce reasonable abbreviations
j = longest_common_prefix(prev, cur)
if j == len(prev):
j -= 1
if j < prevj:
j = 0
if 0 < prevj < j:
j = prevj
if j > 0:
label = u"…" + groupby.join(cur[j:])
if j == 0 and prevj > 0:
addbreak = True
prev = cur
prevj = j
attr = dict()
if desc is not None:
attr["title"] = desc
if selected:
attr["class"] = "menuitem menusel"
e = E.span(label, **attr)
else:
href, changed = c.get_pointname_relative(self, 'html', g, x, l)
attr["class"] = "menuitem menuother" if changed else "menuitem menusame"
e = E.a(label, href=href, **attr)
if addbreak:
result.append(E.br())
result.append(e)
t = title + ":"
if titlelink is None:
t = E.span(t, **{"class": "menutitle"})
else:
t = E.a(t, href=titlelink, **{"class": "menutitle"})
menu = E.p(*add_sep([t] + result, " "), **{"class": "menurow"})
menublocks.append(menu)
menublocks = []
add_menu(
"Corpus",
ac.by_dataset_stat_fallback[(self.datasetcode, self.statcode)],
[ groupcode ],
[ collectioncode ],
[ listing ],
lambda c, g, x, l: (c.corpuscode, c.corpus_descr),
titlelink="../index.html",
groupby='-'
)
add_menu(
"Dataset",
ac.by_corpus_stat[(self.corpuscode, self.statcode)],
[ groupcode ],
[ collectioncode ],
[ listing ],
lambda c, g, x, l: (c.datasetcode, c.dataset_descr)
)
add_menu(
"Points",
[ self ],
sorted(self.groups),
[ collectioncode ],
[ listing ],
lambda c, g, x, l: ("none", None) if g is None else (g, None)
)
add_menu(
"Axes",
ac.by_corpus_dataset[(self.corpuscode, self.datasetcode)],
[ groupcode ],
[ collectioncode ],
[ listing ],
lambda c, g, x, l: (
"%s/%s" % (c.ylabel, c.xlabel),
"y = %s, x = %s" % (c.ylabel, c.xlabel)
)
)
bodyblocks.append(E.div(*menublocks, **{"class": "menu"}))
fig = E.p(E.object(
data=self.get_pointname('svg', groupcode, point, listing),
type="image/svg+xml",
width=str(self.layout.width * self.layout.dpi),
height=str(self.layout.height * self.layout.dpi),
), **{"class": "plot"})
bodyblocks.append(fig)
menublocks = []
add_menu(
"Collection",
[ self ],
[ groupcode ],
[ None ] + [ p.collectioncode for p in self.points_by_group[groupcode] ],
[ listing ],
lambda c, g, x, l: ("none", None) if x is None else (x, self.collection_descr[x])
)
if collectioncode is not None and self.collection_descr[collectioncode] is not None:
menublocks.append(E.p(self.collection_descr[collectioncode], **{"class": "menudesc"}))
if len(self.listings) > 1:
add_menu(
"Show",
[ self ],
[ groupcode ],
[ collectioncode ],
self.listings,
lambda c, g, x, l: (LISTING_LABEL[l], None)
)
bodyblocks.append(E.div(*menublocks, **{"class": "menu"}))
if listing is None:
stat = []
if collectioncode is None:
what = []
for total, label in [
(self.xtotal, self.xlabel),
(self.ytotal, self.ylabel),
]:
if total is not None:
what.append('{} {}'.format(total, label))
if len(what) > 0:
stat.append(E.p("This corpus contains {}.".format(
' and '.join(what)
)))
bodyblocks.append(E.div(*stat, **{"class": "stats"}))
else:
stat.append(E.p("This collection contains {} {} and {} {}.".format(
point.x, self.xlabel,
point.y, self.ylabel
)))
w = "at most" if point.side == "below" else "at least"
if point.pvalue > 0.1:
ppvalue = "{:.1f}%".format(100 * point.pvalue)
elif point.pvalue > 0.01:
ppvalue = "{:.2f}%".format(100 * point.pvalue)
else:
ppvalue = "{:.3f}%".format(100 * point.pvalue)
stat.append(E.p(
("Only approx. " if point.pvalue < 0.1 else "Approx. "),
E.strong(ppvalue),
" of random collections with {} {} contain {} {} {}.".format(
point.x, self.xlabel, w, point.y, self.ylabel
)
))
if point.pvalue > 0.1:
stat.append(E.p(
"This seems to be a fairly typical collection."
))
elif point.fdr < 0:
stat.append(E.p(
"This finding is probably not interesting: ",
"the false discovery rate is larger than {}".format(-point.fdr)
))
else:
stat.append(E.p(
"This finding is probably interesting: ",
"the false discovery rate is ",
E.strong("smaller than {}".format(point.fdr)),
"."
))
bodyblocks.append(E.div(*stat, **{"class": "stats"}))
elif listing == 't':
typelist = ac.get_typelist(self.corpuscode, self.datasetcode, collectioncode)
bodyblocks.append(E.div(*typelist, **{"class": "listing"}))
elif listing == 's':
samplelist = ac.get_samplelist(self.corpuscode, self.datasetcode, collectioncode)
bodyblocks.append(E.div(*samplelist, **{"class": "listing"}))
else:
assert False
doc = E.html(E.head(*headblocks), E.body(*bodyblocks))
write_html(f, doc)
<file_sep>DESCRIPTION = "Type and hapax accumulation curves"
AUTHOR = "<NAME>"
VERSION = "2014-05-15"
YEAR = "2014"
<file_sep>import os
import os.path
import subprocess
import sys
BIN_DIR = 'bin'
TMP_DIR = 'tmp'
LOGIN_FILE = 'loginfile'
PARTS=1
PARALLEL = 'parallel'
MINVERSION = '20120222'
def add_options(parser):
parser.add_option('--bindir', metavar='DIRECTORY', dest='bindir',
help='where to find program files [default: %default]',
default=BIN_DIR)
parser.add_option('--tmpdir', metavar='FILE', dest='tmpdir',
help='where to store temporary files [default: %default]',
default=TMP_DIR)
parser.add_option('--local', dest='locally', action='store_true',
help='run locally',
default=False)
parser.add_option('--loginfile', metavar='FILE', dest='loginfile',
help='SSH login file if you want to distribute computation on multiple machines, see "parallel --sshloginfile" for more information on the file format [default: %default]',
default=LOGIN_FILE)
parser.add_option('--parts', metavar='N', dest='parts', type=int,
help='split each execution in how many independent parts [default: %default]',
default=PARTS)
class Parallel:
def __init__(self, tool, bin, cmds, args):
self.tool = tool
self.bin = bin
self.fullpath = os.path.join(args.bindir, bin)
self.cmds = cmds
self.locally = args.locally
self.loginfile = args.loginfile
def msg(self, msg):
sys.stderr.write("%s: %s\n" % (self.tool, msg))
def error(self, msg):
sys.stderr.write("%s: error: %s\n" % (self.tool, msg))
sys.exit(1)
def run_serial(self):
sys.stderr.write('%s (%d): ' % (self.bin, len(self.cmds)))
for a in self.cmds:
cmd = [ self.fullpath ] + [ str(i) for i in a ]
# self.msg("run: %s" % ' '.join(cmd))
process = subprocess.Popen(cmd)
process.wait()
if process.returncode != 0:
if process.returncode > 0:
self.error("%s returned %d" % (self.bin, process.returncode))
else:
self.error("%s received signal %d" % (self.bin, -process.returncode))
sys.stderr.write('\n')
def run_parallel(self):
sys.stderr.write('%s [%d]: ' % (self.bin, len(self.cmds)))
cwd = os.getcwd()
cmd0 = [
PARALLEL,
'--ungroup',
'--workdir', cwd,
'--sshloginfile', self.loginfile,
'--delim', '\\n',
'--colsep', '\\t',
'--trim', 'n',
self.fullpath
]
# self.msg("run: %s" % ' '.join(cmd0))
process = subprocess.Popen(cmd0, stdin=subprocess.PIPE)
for a in self.cmds:
b = [ str(i) for i in a ]
# self.msg("queue: %s" % ' '.join(b))
process.stdin.write('\t'.join(b))
process.stdin.write('\n')
process.stdin.close()
process.wait()
sys.stderr.write('\n')
if process.returncode != 0:
if process.returncode > 0:
self.error("%d child processes failed" % process.returncode)
else:
self.error("%s received signal %d" % (PARALLEL, -process.returncode))
def parallel_ok(self):
cmd = [ PARALLEL, '--minversion', MINVERSION ]
try:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
except:
return False
process.communicate()
return process.returncode == 0
def run(self):
if self.locally:
self.run_serial()
elif not os.path.exists(self.loginfile):
if self.loginfile != LOGIN_FILE:
self.msg("login file %s missing, running locally" % self.loginfile)
self.run_serial()
elif not self.parallel_ok():
self.msg("could not find GNU parallel version %s or later, running locally" % MINVERSION)
self.run_serial()
else:
self.run_parallel()
<file_sep>import sys
import codecs
import cPickle
import multiprocessing
import optparse
import sqlite3
import lxml
import numpy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot
assert sys.version_info >= (2,6)
print "OK"
| 8c12976d77f8c8d831d3f1eb31e5d18d2dd3b28f | [
"Markdown",
"C",
"Python"
] | 12 | Python | HaakonME/types | d0ab874e2bf8af83ccb3675ef1648b20cbd5c745 | e66d39b18397faa04b7a8e75447ad83af09fd52d | |
refs/heads/master | <file_sep>#ifndef _vector_h
#define _vector_h
#include <iostream>
#include <array> // Se necesita activar C++11
using namespace std;
//DECLARACIONES:
struct Vector { //Tipo de Dato Vector
array<int,100> lista;
unsigned top;
};
void cargar_datos(Vector &par_vector); //Carga los datos
void mostrar_vector(Vector &par_vector);
void buscar(const Vector &par_vector,const int &par_dato,const unsigned &par_tipo);
void busqueda_secuencial(const Vector &par_vector,const int &par_dato);
void busqueda_binaria(const Vector &par_vector,const int &par_dato);
#endif
<file_sep>#include <iostream>
#include <array>
#include "vector.h"
/* Trabajo Practico N15 - BUSQUEDA
REQUISITO:
Se necesita probar los diferentes tipos de busqueda:
- 1. Secuencial.
- 2. Binaria.
PRE-CONDICIONES:
El usuario no ingresa nada, el vector esta previamente cargado
por codigo.
El usuario solo debe ver si se busco correctamente.
MATERIA:
Algoritmos y Estructura de Datos
INTEGRANTES:
<NAME>
<NAME>
<NAME>
<NAME>
*/
using namespace std;
int main(int argc, char** argv) {
//Declaraciones
Vector var_vector;
int var_dato = 63;
cargar_datos(var_vector);
cout<<"Lista:"<<endl;
mostrar_vector(var_vector);
//Desarrollo
for (unsigned i = 1; i <= 2; i++){
cout<<"Dato a buscar: "<<var_dato<<endl;
buscar(var_vector,var_dato,i);
}
return 0;
}
<file_sep>#include "vector.h"
//Definiciones
void cargar_datos(Vector &par_vector){ //Carga los datos
par_vector.lista = {13,21,33,45,54,63,75,88,91};
par_vector.top = 9;
}
void mostrar_vector(Vector &par_vector){
for (int i = 0; i < par_vector.top; i++){
cout<<par_vector.lista.at(i)<<";";
}
cout<<endl<<endl;
}
void buscar(const Vector &par_vector,const int &par_dato,const unsigned &par_tipo){
switch (par_tipo){
case 1:
busqueda_secuencial(par_vector,par_dato);
break;
case 2:
busqueda_binaria(par_vector,par_dato);
break;
}
}
void busqueda_secuencial(const Vector &par_vector,const int &par_dato){
cout<<"Buqueda Secuencial: "<<endl;
int i;
for(i=0; (i<par_vector.top)&&(par_vector.lista.at(i)!=par_dato); i++){
}
cout<<"Posicion: "<<i<<endl<<endl;
}
void busqueda_binaria(const Vector &par_vector,const int &par_dato){
int ini = 0;
int fin = par_vector.top;
int mitad = (ini+fin) / 2;
int s=-1;
while(ini>=0 && ini<=fin && fin<=par_vector.top && s==-1){
if (par_vector.lista.at(mitad)<par_dato){
ini=mitad+1;
mitad=(ini+fin)/2;
}
else{
if(par_vector.lista.at(mitad)==par_dato){
s=mitad;
}
else{
fin=mitad-1;
mitad=(ini+fin)/2;
}
}
}
cout<<"Busqueda Binaria: "<<endl;
cout<<"Esta en la posicion: "<<s<<endl;
}
| d171c0110ad883036f7151ba8b53d7e4aa085e7b | [
"C++"
] | 3 | C++ | AdrielChambi/AED-TP15-BUSQUEDA | 5ecbd4ea46a060a128d0dce534490b3423d77273 | 0ad3c517f951cf14278648a80b5f6894619a45d8 | |
refs/heads/master | <file_sep>const data = {
"list":[
{
"adminDescription":"测试新系统",
"amount":1,
"assetId":"01740214-7429-400e-b220-a0e500cb93b2",
"bakCategoryName":"台式电脑",
"bakFeatureId":62,
"categoryId":100201301401000102,
"categoryIdString":100201301401000102,
"categoryName":"台式电脑",
"creator":"system",
"curResourceCode":"A58010100000023",
"currentCost":0,
"demander":"WB034764",
"demanderName":"刘宇航",
"depreciationReserve":0,
"endDate":1493308800000,
"feature":"苹果-iMac27",
"featureDescription":"",
"featureId":5300827910569984,
"gmtCreated":1411562350000,
"gmtModified":1512617416000,
"id":1083,
"idString":"1083",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"macWired":"C02JD3B9DHJP",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"045424",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":17,
"ouCode":"A58",
"ouCompany":"阿里巴巴科技(北京)有限公司",
"ouResourceCode":"TD010100050676",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO68868",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A58010100000023",
"sn":"C02JD3B9DHJP",
"startDate":1349712000000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":66,
"user":"WB034764",
"userName":"刘宇航",
"vendorName":"浙江澳凌信息科技有限公司"
},
{
"adminDescription":"重新分配标签-无",
"amount":1,
"assetId":"090ea2e1-56ff-42f5-ad43-9fc10010e190",
"bakCategoryName":"台式电脑",
"bakFeatureId":520780277996589060,
"categoryId":100201301401000110,
"categoryIdString":"100201301401000106",
"categoryName":"显示器",
"creator":"system",
"curResourceCode":"T57100600000222",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"endDate":1513008000000,
"feature":"其他-其他",
"featureDescription":"",
"featureId":520780277996589060,
"gmtCreated":1411562350000,
"gmtModified":1521093816000,
"houseId":42,
"id":6944,
"idString":"6944",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"WB124379",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":9,
"ouCode":"T57",
"ouCompany":"浙江口碑网络技术有限公司",
"ouResourceCode":"TD100600022157",
"owner":"WB124379",
"ownerName":"陆冬林",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"T57100600000222",
"sn":"CND71121SB",
"startDate":1254326400000,
"status":"Scrapped",
"statusDetail":"CleanedUp",
"statusDetailName":"已清理",
"statusName":"报废",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":102,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":""
},
{
"adminDescription":"66666666666test",
"amount":1,
"assetId":"0fb73d23-7e0b-4f14-92e8-a05100aa4897",
"bakCategoryName":"台式电脑",
"bakFeatureId":43,
"categoryId":100201301401000100,
"categoryIdString":100201301401000102,
"categoryName":"台式电脑",
"creator":"system",
"curResourceCode":"B50010100003406",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"endDate":1520265600000,
"feature":"联想-M4880",
"featureDescription":"",
"featureId":5300827846377472,
"gmtCreated":1411562350000,
"gmtModified":1464746999000,
"houseId":42,
"id":12026,
"idString":"12026",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":127,
"ouCode":"B50",
"ouCompany":"阿里巴巴(中国)网络技术有限公司",
"ouResourceCode":"TD010100051492",
"owner":"WB124379",
"ownerName":"陆冬林",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"B50010100003406",
"sn":"EA01621218",
"startDate":1180540800000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":130,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":""
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"endDate":1513094400000,
"feature":"戴尔-E6220",
"featureDescription":"",
"featureId":5300827717959680,
"gmtCreated":1457073026000,
"gmtModified":1464746999000,
"houseId":42,
"id":5512824486166528,
"idString":"5512824486166528",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000050",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028002",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"sn":"YUCT43",
"startDate":1457073027000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001464",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1500048000000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523360000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527581038313472,
"idString":"5527581038313472",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000132",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001464",
"sn":"YUCT189",
"startDate":1457523361000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A58030300000003",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1520265600000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523389000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527581987471360,
"idString":"5527581987471360",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000184",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A58030300000003",
"sn":"YUCT241",
"startDate":1457523390000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001570",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1512748800000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523419000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527582966054912,
"idString":"5527582966054912",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000238",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001570",
"sn":"YUCT295",
"startDate":1457523420000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001572",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1515859200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523420000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527583001870336,
"idString":"5527583001870336",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000240",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001572",
"sn":"YUCT297",
"startDate":1457523421000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001592",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1515859200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523432000,
"gmtModified":1515466147000,
"houseId":42,
"id":5527583377522688,
"idString":"5527583377522688",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"WB124379",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000260",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001592",
"startDate":1457523432000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001603",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1513353600000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523438000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527583574982656,
"idString":"5527583574982656",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000271",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001603",
"sn":"YUCT328",
"startDate":1457523438000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001605",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1513353600000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523439000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527583611125760,
"idString":"5527583611125760",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000273",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001605",
"sn":"YUCT330",
"startDate":1457523439000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001609",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1515859200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523441000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527583685312512,
"idString":"5527583685312512",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000277",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001609",
"sn":"YUCT334",
"startDate":1457523442000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001616",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1515859200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523445000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527583812878336,
"idString":"5527583812878336",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000284",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001616",
"sn":"YUCT341",
"startDate":1457523446000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001622",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1515859200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523448000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527583921340416,
"idString":"5527583921340416",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000290",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001622",
"sn":"YUCT347",
"startDate":1457523449000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001623",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1515859200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523449000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527583939821568,
"idString":"5527583939821568",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000291",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001623",
"sn":"YUCT348",
"startDate":1457523449000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001624",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1515859200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523449000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527583958040576,
"idString":"5527583958040576",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000292",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001624",
"sn":"YUCT349",
"startDate":1457523450000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>.com====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001626",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1512921600000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523451000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527583994707968,
"idString":"5527583994707968",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000294",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001626",
"sn":"YUCT351",
"startDate":1457523451000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001627",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1512921600000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523451000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527584012795904,
"idString":"5527584012795904",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000295",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001627",
"sn":"YUCT352",
"startDate":1457523452000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"adminDescription":"TD10801000000296",
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001628",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1513008000000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523452000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527584030621696,
"idString":"5527584030621696",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000296",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001628",
"sn":"YUCT353",
"startDate":1457523452000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001629",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1513008000000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523452000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527584048349184,
"idString":"5527584048349184",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000297",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001629",
"sn":"YUCT354",
"startDate":1457523453000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001633",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1515859200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523454000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527584120078336,
"idString":"5527584120078336",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000301",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001633",
"sn":"YUCT358",
"startDate":1457523455000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001636",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1515859200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523456000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527584173391872,
"idString":"5527584173391872",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000304",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001636",
"sn":"YUCT361",
"startDate":1457523457000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001637",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1515859200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523457000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527584191152128,
"idString":"5527584191152128",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000305",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001637",
"sn":"YUCT362",
"startDate":1457523457000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001665",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1516118400000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523472000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527584697778176,
"idString":"5527584697778176",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000333",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001665",
"sn":"YUCT390",
"startDate":1457523473000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001675",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1521734400000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523478000,
"gmtModified":1521018302000,
"houseId":42,
"id":5527584877445120,
"idString":"5527584877445120",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"WB124379",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000343",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001675",
"sn":"YUCT400",
"startDate":1457523478000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001676",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1520265600000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523478000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527584895401984,
"idString":"5527584895401984",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000344",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001676",
"sn":"YUCT401",
"startDate":1457523479000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001681",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1520265600000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523481000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527584986628096,
"idString":"5527584986628096",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000349",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001681",
"sn":"YUCT406",
"startDate":1457523481000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001684",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1521302400000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523482000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527585040695296,
"idString":"5527585040695296",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000352",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001684",
"sn":"YUCT409",
"startDate":1457523483000,
"status":"Using",
"statusDetail":"Normal",
"statusDetailName":"正常",
"statusName":"在用",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001690",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1520265600000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523486000,
"gmtModified":1517488693000,
"houseId":42,
"id":5527585150828544,
"idString":"5527585150828544",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"WB124379",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000358",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001690",
"sn":"YUCT415",
"startDate":1457523486000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001697",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1520265600000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523490000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527585278197760,
"idString":"5527585278197760",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000365",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001697",
"sn":"YUCT422",
"startDate":1457523490000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001698",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1520611200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523490000,
"gmtModified":1520233140000,
"houseId":42,
"id":5527585296908288,
"idString":"5527585296908288",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"WB124379",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000366",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001698",
"sn":"YUCT423",
"startDate":1457523491000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001704",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1520611200000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523494000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527585404026880,
"idString":"5527585404026880",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000372",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001704",
"sn":"YUCT429",
"startDate":1457523494000,
"status":"Stocking",
"statusDetail":"Available",
"statusDetailName":"可用",
"statusName":"库存",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001715",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1522252800000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523500000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527585601257472,
"idString":"5527585601257472",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000383",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001715",
"sn":"YUCT440",
"startDate":1457523500000,
"status":"Using",
"statusDetail":"Normal",
"statusDetailName":"正常",
"statusName":"在用",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
},
{
"amount":1,
"bakCategoryName":"台式电脑",
"categoryId":100201301401000100,
"categoryIdString":"100201301401000101",
"categoryName":"笔记本电脑",
"creator":"System",
"curResourceCode":"A50010200001717",
"currentCost":0,
"demander":"WB124379",
"demanderName":"陆冬林",
"depreciationReserve":0,
"doNumber":"DO10007140",
"endDate":1521302400000,
"feature":"联想-X31",
"featureDescription":"",
"featureId":5300827537932288,
"gmtCreated":1457523501000,
"gmtModified":1464746999000,
"houseId":42,
"id":5527585636810752,
"idString":"5527585636810752",
"isDeleted":"n",
"isFitting":"n",
"isSafe":"n",
"managerClass":"按件",
"managerType":"it",
"managerTypeName":"it",
"modifier":"083568",
"netCost":0,
"newType":"购置",
"originalCost":0,
"ou":14,
"ouCode":"A50",
"ouCompany":"阿里巴巴(中国)有限公司",
"ouResourceCode":"TD10801000000385",
"owner":"WB124379",
"ownerName":"陆冬林",
"poNumber":"PO25028222",
"reBorrowType":"日常临时借用",
"reborrowCount":"0",
"requestQty":0,
"resourceCode":"A50010200001717",
"sn":"YUCT442",
"startDate":1457523501000,
"status":"Using",
"statusDetail":"Normal",
"statusDetailName":"正常",
"statusName":"在用",
"storeHouseName":"员工库房",
"useRemark":"4",
"useRemarkName":"借用",
"usedMonths":25,
"user":"WB124379",
"userName":"陆冬林",
"vendorName":"洪著测试<EMAIL>====测试"
}
]
}
export default data;<file_sep>import * as React from 'react'
import * as ReactDOM from 'react-dom'
import SelfAddGoods from './selfAddGoods'
ReactDOM.render(
<SelfAddGoods/>,
document.getElementById('SelfAddGoods'))<file_sep>import * as ReactDOM from 'react-dom';
import ChangeSelectSubmit from './changeSelectSubmit';
ReactDOM.render(
<ChangeSelectSubmit />,
document.getElementById('changeSelectSubmit'),
);
<file_sep>function parseURL(url) {
const a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':', ''),
host: a.hostname,
port: a.port,
query: a.search,
params: (() => {
const ret = {};
const seg = a.search.replace(/^\?/, '').split('&');
const len = seg.length;
let i = 0;
let s;
for (;i < len; i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
};
}
export default { parseURL };
<file_sep>import * as ReactDOM from 'react-dom';
import ChangeSelectAsset from './changeSelectAsset';
ReactDOM.render(
<ChangeSelectAsset />,
document.getElementById('changeSelectAsset'),
);
<file_sep>import Form from 'uxcore-form';
import Icon from 'uxcore-icon';
import './xujieSelect.less';
const { NumberInputFormField, Validators } = Form;
class XujieSelect extends React.Component {
constructor(props) {
super(props);
this.formData = this.formData.bind(this);
}
formData() {
return this.xujieTime.getValues().pass;
}
render() {
// temp("temp", "日常临时借用", 30), project("project", "项目借用", 90), special("special", "双11,12专项", 90),
const { data } = this.props;
const { reBorrowType } = data.assetDescribe;
const maxDay = reBorrowType === '日常临时借用' ? 30 : 90;
return (
<div className="xujie-select-box">
<div className="top">
<div className="img"><img alt="暂无图片" src={'/public/images/category_pic/' + data.assetDescribe.categoryIdString + '.jpg'} /></div>
<div className="xujie-info">
<p>名 称:<span className="asset-name">{data.assetDescribe.categoryName}</span></p>
<p>特 征:<span>{data.assetDescribe.feature}</span></p>
<p>借用类型:<span className="asset-user">{data.assetDescribe.reBorrowType}</span></p>
</div>
</div>
<div className="bottom">
<Form className="length-form" ref={(c) => { this.xujieTime = c; }} jsxonChange={this.props.xujieDayChange.bind(null, data.assetDescribe.id)}>
<NumberInputFormField
jsxname="cycle"
jsxlabel="续借时长"
jsxplaceholder="请填写"
jsxrules={[
{ validator: Validators.isNotEmpty, errMsg: '不能为空' },
{ validator(value) { return value <= maxDay; }, errMsg: `最长${maxDay}天` },
]}
/>
</Form>
<span className="time-tip">/天(最长可借用{maxDay}天)</span>
</div>
<div className="close-box">
<Icon onClick={this.props.closeAsset.bind(null, data)} name="guanbi" className="close-btn" />
</div>
</div>
);
}
}
export default XujieSelect;
<file_sep>// Map转数组
function mapToArray(map) {
const arr = [];
map.forEach((value, key) => {
arr.push({
type: key,
info: value,
});
});
return arr;
}
// 对象转数组
function objToArray(obj) {
const arr = Object.keys(obj).map((key) => ({
text: obj[key], // [{}, {}]
value: key, // 笔记本电脑
}));
return arr;
}
// 特殊情况,获取地点,text == value
function locationObjToArray(obj) {
const arr = Object.keys(obj).map((key) => ({
text: obj[key],
value: obj[key],
}));
return arr;
}
// 字符串不足6为,前面补全
function stringFormat(str) {
const { length } = str;
if (length < 6) {
const cha = 6 - length;
for (let i = 0; i < cha; i += 1) {
str = '0' + str.toString();
}
}
return str;
}
export { mapToArray, objToArray, locationObjToArray, stringFormat };
<file_sep>import PropTypes from 'prop-types';
import classnames from 'classnames';
import TabPane from './TabPane';
import './Tabs.less';
class Tabs extends React.Component {
constructor(props) {
super(props);
this.state = {
inkBarWidth: 0,
inkBarTranslate: 0,
tabActiveIndex: 0, // 激活的tab
};
this.lastTabPos; // 第一个tab的位置,只需要开始保存下就可以
this.tabIndex = 0;
}
componentDidMount() {
// setTimeout(() => {
// if (this.tab0) {
// const firstTabRect = this.tab0.getBoundingClientRect();
// this.lastTabPos = firstTabRect.left;
// this.setState({
// inkBarWidth: firstTabRect.width,
// });
// }
// }, 10);
}
componentWillReceiveProps(newProps) {
if (this.tab0 && this.tabIndex === 0) {
this.tabIndex = 1;
const firstTabRect = this.tab0.getBoundingClientRect();
// this.lastTabPos = firstTabRect.left;
this.setState({
inkBarWidth: firstTabRect.width,
});
}
}
// 加载子元素
processContent() {
const me = this;
const elements = React.Children.map(me.props.children, (child, index) => React.cloneElement(child, {}));
return elements;
}
// 加载tab
processTabNav() {
const me = this;
const TabsElement = React.Children.map(me.props.children, (child, index) => (
<div
onClick={me.tabClick.bind(this, child.props.value, index)}
className={classnames('asset-tab-tab', {
[`asset-tab-tab-${index}`]: true,
'asset-tab-tab-active': this.state.tabActiveIndex === index,
})}
ref={(c) => { me[`tab${index}`] = c; }}
>
{child.props.tabNum == 0 ? '' : <div className="asset-tab-num">{child.props.tabNum }</div>}
{child.props.tab}
</div>
));
return TabsElement;
}
// tab点击
tabClick(value, index, e) {
const clickEle = e.target;
const clickEleSize = clickEle.getBoundingClientRect();
if (!this.lastTabPos) {
this.lastTabPos = this.tab0.getBoundingClientRect().left;
}
// 获取宽度
const eleWidth = clickEleSize.width;
// 获取位置
const eleLeft = clickEleSize.left;
// 移动ink-bar
// 计算差值,正值 右移。负值-左移动
const inkBarCha = eleLeft - this.lastTabPos;
this.setState({
inkBarWidth: eleWidth,
inkBarTranslate: inkBarCha,
tabActiveIndex: index,
});
this.props.onTabClick(value);
}
render() {
const inkBarWidth = this.state.inkBarWidth;
const inkBarTranslate = this.state.inkBarTranslate;
const inkBarStyle = {
width: `${inkBarWidth}px`,
transform: `translate3d(${inkBarTranslate}px, 0, 0)`,
};
return (
<div className={classnames('asset-tab', {
[this.props.type]: !!this.props.type,
})}
>
<div className="asset-tab-nav-container">
<div style={inkBarStyle} className="asset-tab-ink-bar" />
{this.processTabNav()}
</div>
<div className="asset-tab-content">
{this.processContent()[this.state.tabActiveIndex]}
</div>
</div>
);
}
}
Tabs.TabPane = TabPane;
Tabs.defaultProps = {
onChange: () => {},
onTabClick: () => {},
};
Tabs.propTypes = {
onChange: PropTypes.func,
onTabClick: PropTypes.func,
};
export default Tabs;
/**
* componentDidMount getBoundingClientRect 有问题。延时没问题
*
*/
<file_sep>import produce from 'immer';
import BigImg from 'lxq-react-zoom';
import moment from 'moment';
class TestImmer extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
console.log(moment(1523462400000).format('YYYY-MM-DD'));
const obj = {
a: 1,
b: 2,
};
console.log(obj, '1');
const obj4 = obj;
obj4.a = '8';
console.log(obj, '2');
const arr = [{
a: 1,
b: {
b1: 'b1',
},
}];
const newObj = produce(obj, (draft) => {
draft.a = 'a';
});
console.log(obj, 'obj');
console.log(newObj, 'newObj');
const newArr = produce(arr, draft => {
draft[0].b.b1 = '333';
});
console.log(arr, 'arr');
console.log(newArr, 'newArr');
const newProxy = new Proxy(obj, {
get(target, key) {
console.log(target, key);
},
});
newProxy.a;
function testImmer(callback) {
console.log(callback(obj), 'callback');
}
testImmer(produce((state) => {
state.c = 9;
}));
}
render() {
return (
<div>
TestImmer
<BigImg original="https://img.alicdn.com/tfs/TB1Jq7qmbSYBuNjSspiXXXNzpXa-1024-768.jpg" src="https://img.alicdn.com/tfs/TB1_ME1mf5TBuNjSspcXXbnGFXa-250-187.jpg" />
</div>
);
}
}
export default TestImmer;
<file_sep>import Icon from 'uxcore-icon';
import Dialog from 'uxcore-dialog';
import Message from 'uxcore-message';
import Select from 'uxcore-select2';
import Button from 'uxcore-button';
import moment from 'moment';
import Form from 'uxcore-form';
import Table from 'uxcore-table';
import classnames from 'classnames';
import CheckboxGroup from 'uxcore-checkbox-group';
import ReplacePeople from 'components/ReplacePeople';
import Tabs from 'components/Tabs';
import Uploader from 'components/uploader';
import { http } from '../../lib/http';
import AssetDescribe from './assetDescribe';
import XujieSelect from './xujieSelect';
import Asset from './asset';
import { objToArray, locationObjToArray } from '../../lib/util';
import './borrow.less';
const TabPane = Tabs.TabPane;
const { Item } = CheckboxGroup;
const Option = Select.Option;
const {
SelectFormField,
DateFormField,
TextAreaFormField,
SearchFormField,
} = Form;
const { TextAreaCount } = TextAreaFormField;
function sum(arr) {
let result = 0;
for (let i = 0; i < arr.length; i++) {
result += arr[i];
}
return result;
}
// 处理续借列表返回的数据
function handleTableData(data) {
return data.map((list) => ({
assetDescribe: {
categoryName: list.categoryName, // 名称
feature: list.feature, // 特征
userName: list.userName, // 使用人
categoryIdString: list.categoryIdString, // 获取资产图片的id
id: list.id,
user: list.user,
reBorrowType: list.reBorrowType,
},
assetLabel: {
ouResourceCode: list.ouResourceCode, // 大阿里编号
resourceCode: list.resourceCode, // 资产编号
sn: list.sn, // 序列号
},
useCondition: {
startDate: list.startDate, // 启用日期
usedMonths: list.usedMonths, // 已使用月
useRemarkName: list.useRemarkName, // 使用说明
},
workFlowName: list.workFlowName,
workFlowType: list.workFlowType,
instanceId: list.instanceId,
resourceId: list.id,
reBorrowType: list.reBorrowType,
requestType: list.reBorrowType === '日常临时借用' ? 'temp' : list.reBorrowType === '项目借用' ? 'project' : 'special',
reborrowCount: list.reborrowCount,
idString: list.idString,
// jsxchecked: true, // 这一列被选中
}));
}
// 资源标签
const AssetLabel = (props) => (
<div className="assetLabel-wrapper">
<p>大阿里编号:{props.data.ouResourceCode}</p>
<p>资 产 编 号:{props.data.resourceCode}</p>
<p>序 列 号:{props.data.sn}</p>
</div>
);
// 使用情况
const AssetUseCondation = (props) => (
<div className="assetLabel-condation">
<p>启用日期:{props.data.startDate ? moment(props.data.startDate).format('YYYY-MM-DD') : ''}</p>
<p>已使用月:{props.data.usedMonths}</p>
<p>使用说明:{props.data.useRemarkName}</p>
</div>
);
class Borrow extends React.Component {
constructor(props) {
super(props);
this.state = {
tabActive: '1',
checkboxValue: '', // 代理人激活按钮
replaceInputDisabled: true, // 代理人选择框状态
citys: [], // 获取的城市
selectCityCode: '', // 选择的城市
parks: [], // 获取的园区
selectParkCode: '', // 选择的园区
locations: [], // 获取的地点
selectLocationText: '', // 选择的地点
locationId: '', // 选择的地点ID
storeHouseId: '', // 选择的库房ID
resEquipmentInfo: [], // 请求的资产列表
categoryType: [], // 获取的所属类别
categoryTypeId: '', // 哪一个Tab
selectedAsset: [], // 选择的设备
m4InfoDialog: false, // 资产box提示信息
noDevice: false, // loading
fileList: [], // 附件
sureDisabled: false, // 提交申请
borrowDay: '', // 最长可借用多少天
resEquipmentXujie: [], // 资产续借列表
selectXujie: [], // 已选续借
fileListXujie: [],
sureDisabledXujie: false,
isShowXujie: true,
is11: false, // 借用类型是不是双11
};
this.tabTranslateClick1 = this.tabTranslateClick1.bind(this);
this.tabTranslateClick2 = this.tabTranslateClick2.bind(this);
this.checkboxChange = this.checkboxChange.bind(this); // 激活按钮
this.handleReplaceSelect = this.handleReplaceSelect.bind(this); // 选择代理人
this.handleCityChange = this.handleCityChange.bind(this);
this.handleParkChange = this.handleParkChange.bind(this);
this.handleLocationChange = this.handleLocationChange.bind(this);
this.obtainLocationId = this.obtainLocationId.bind(this);
this.tabClick = this.tabClick.bind(this);
this.radioOrCheckChange = this.radioOrCheckChange.bind(this);
this.cancelAsset = this.cancelAsset.bind(this);
this.add = this.add.bind(this);
this.decrease = this.decrease.bind(this);
this.borrowTypeChange = this.borrowTypeChange.bind(this);
this.uploaderFileChange = this.uploaderFileChange.bind(this);
this.submitSelect = this.submitSelect.bind(this);
this.search = this.search.bind(this); // 搜索
this.cancelXujie = this.cancelXujie.bind(this);
this.uploaderFileChangeXujie = this.uploaderFileChangeXujie.bind(this);
this.submitSelectXujie = this.submitSelectXujie.bind(this);
this.xujieDayChange = this.xujieDayChange.bind(this);
this.tabXujieHasClick = false;
this.xujieUi = []; // 保存续借详情组件
}
componentDidMount() {
// 获取城市
http.get('/linkage/locationStoreMap/getCity.json').then((res) => {
if (res.hasError) {
Message.error(res.content, 3);
} else {
this.setState({
citys: objToArray(res),
});
}
});
// 获取城市,园区,地点,提示元素
this.cityPlaceholderEle = document.getElementsByClassName('select-city')[0].getElementsByClassName('kuma-select2-selection__placeholder')[0];
this.parkPlaceholderEle = document.getElementsByClassName('select-park')[0].getElementsByClassName('kuma-select2-selection__placeholder')[0];
this.locationPlaceholderEle = document.getElementsByClassName('select-location')[0].getElementsByClassName('kuma-select2-selection__placeholder')[0];
// 获取所属类别
new Promise((resolve) => {
http.get('/newemployee/equipment/getCategoryType.json').then((res) => {
this.setState({
categoryType: res,
categoryTypeId: res[0].id,
});
resolve(res[0].id);
});
}).then((categoryTypeId) => {
this.requestAsset(categoryTypeId);
});
}
// 资产借用tab
tabTranslateClick1() {
this.tabContent.style.transform = 'translateX(0)';
this.tabBottom.style.transform = 'translateX(0)';
this.setState({
tabActive: '1',
});
}
// 资产续借tab
tabTranslateClick2() {
this.tabContent.style.transform = 'translateX(-100%)';
this.tabBottom.style.transform = 'translateX(104px)';
if (this.state.resEquipmentXujie.length === 0 && !this.tabXujieHasClick) {
this.requestAssetXujie();
this.tabXujieHasClick = true;
}
this.setState({
tabActive: '2',
});
}
// 配置标准&&领用详情
policyTip() {
return (
<Dialog
title={<span><Icon name="jinggao-full" className="icon" />借用政策</span>}
visible={this.state.m4InfoDialog}
className="m4-info-dialog"
footer={
<Button onClick={() => {
this.setState({
m4InfoDialog: false,
});
}}
type="primary"
>知道啦</Button>}
onCancel={() => {
this.setState({
m4InfoDialog: false,
});
}}
>
<p>1、可借用场景:临时出差、临时会议、紧急项目需求。</p>
<p>2、借用周期:个人借用最长一个月;项目借用最长3个月;都可以续借一次。</p>
<p>3、借用规则:供借用的资产数量有限,一旦超出了借用池的数量,将不再提供借用。</p>
<p>4、借用失效:借用审批通过后的1天内需完成领用,否则借用单将失效,需要重新提交。</p>
</Dialog>
);
}
// 获取资产
/**
*
* @param {} categoryTypeId 电脑 显示器
* @param {*} workNo 代理人的工号
*/
requestAsset(categoryTypeId, workNo = '', storeLocationMappingId = '') {
this.setState({
noDevice: false,
});
// 请求对应类别的设备信息
http.get('/workflow/borrow/getEquipmentInfo.json?workFlowType=借用&categoryTypeId=' + categoryTypeId + '&enumWorkFlowType=Borrow&workNo=' + workNo + '&storeLocationMappingId=' + storeLocationMappingId).then((res) => {
if (res.hasError) {
Message.info(res.content, 2);
this.setState({
resEquipmentInfo: [],
noDevice: true,
});
} else {
this.setState({
resEquipmentInfo: objToArray(res),
noDevice: true,
});
}
});
}
// 借用政策
borrowPolicy() {
return (
<div className="change-policy">
<Icon name="jinggao-full" className="icon" />
<span className="policy">借用政策</span>
<span onClick={() => {
this.setState({
m4InfoDialog: true,
});
}}
className="info-tip"
>[查看详情]
</span>
</div>
);
}
// 代他人申请
replaceBox() {
return (
<div className="replace-box">
<div className="top">
<CheckboxGroup onChange={this.checkboxChange} value={this.state.checkboxValue}>
<Item text="代他人申请" value="replace" />
</CheckboxGroup>
<div className="replace-tip">*主管可代直接下属申请;直接上级主管相同的员工可相互代理</div>
</div>
<div className="bottom">
<Form
ref={(c) => { this.form_replace_person = c; }}
jsxonChange={this.handleReplaceSelect}
>
<SelectFormField
jsxdisabled={this.state.replaceInputDisabled}
jsxplaceholder="选择代领人"
jsxname="replacePerson"
jsxfetchUrl="https://work.alibaba-inc.com/work/xservice/open/api/v1/suggestion/suggestionAt.jsonp"
dataType="jsonp"
className="replace-select"
beforeFetch={(data) => {
data.key = data.q;
data.offset = 0;
data.size = 8;
data.accessToken = '<KEY>';
return data;
}}
afterFetch={(obj) => {
let data = null;
data = obj.userList.map(item => ({
text: <ReplacePeople userList={item} />,
value: item.emplid, // 返回数据 key:
}));
return data;
}}
/>
</Form>
</div>
</div>
);
}
// 代理人激活框
checkboxChange(value) {
if (value.length === 2) { // 选中
this.setState({
checkboxValue: value,
replaceInputDisabled: false,
});
} else {
// 判断有没有选人,有--> 清空,触发数据
// 没有--> 不触发数据
const replacePerson = this.form_replace_person.getValues().values.replacePerson;
if (replacePerson) { // 有人
this.form_replace_person.resetValues(); // 清数据
this.requestAsset(this.state.categoryTypeId);
}
this.setState({
checkboxValue: value,
replaceInputDisabled: true,
});
}
}
// 代理人选择,选了人后再去请求数据
handleReplaceSelect(value) {
this.requestAsset(this.state.categoryTypeId, value.replacePerson.key.padStart(6, '0'));
}
// 选择领用地点
selectAddress() {
return (
<div className="step-1">
<div className="step-title">第一步:选择新设备的领用地点</div>
<span>领用地点</span>
<Select onChange={this.handleCityChange} className="select-city" placeholder="城市">
{this.state.citys.map((city) => (<Option value={city.value}>{city.text}</Option>))}
</Select>
<Select value={this.state.selectParkCode} onChange={this.handleParkChange} className="select-park" placeholder="园区">
{this.state.parks.map((park) => (<Option value={park.value}>{park.text}</Option>))}
</Select>
<Select value={this.state.selectLocationText} onChange={this.handleLocationChange} className="select-location" placeholder="领用位置">
{this.state.locations.map((location) => (<Option value={location.value}>{location.text}</Option>))}
</Select>
</div>
);
}
// 选择城市,获取园区
handleCityChange(value) {
this.cityPlaceholderEle.setAttribute('style', 'opacity: 0');
this.parkPlaceholderEle.style.opacity = 1; // 恢复提示
this.locationPlaceholderEle.style.opacity = 1;
this.setState({
selectCityCode: value,
selectParkCode: '', // 清空园区
selectLocationText: '', // 清空地点 ps 清空值,也要清空下拉数据
locations: [], // 清空地点下拉数据
selectedAsset: [], // 清空选择的
});
http.get('/linkage/locationStoreMap/getPark.json?cityCode=' + value).then((res) => {
this.setState({
parks: objToArray(res),
});
});
}
// 选择园区,获取地点
handleParkChange(value) {
this.parkPlaceholderEle.style.opacity = 0;
this.locationPlaceholderEle.style.opacity = 1;
const cityCode = this.state.selectCityCode;
this.setState({
selectParkCode: value,
selectLocationText: '', // 清空地点
selectedAsset: [], // 清空选择的
});
http.get('/linkage/locationStoreMap/getLocation.json?cityCode=' + cityCode + '&parkCode=' + value).then((res) => {
this.setState({
locations: locationObjToArray(res),
});
});
}
// 选择领用地点
handleLocationChange(text) {
this.locationPlaceholderEle.style.opacity = 0;
this.obtainLocationId(text);
this.setState({
selectLocationText: text,
noDevice: false,
selectedAsset: [], // 清空选择的
});
}
// 选择完地点后,获取locationId和storeHouseId
obtainLocationId(location) {
const cityCode = this.state.selectCityCode;
const parkCode = this.state.selectParkCode;
// 这儿改变一次state,会重新渲染render
http.get('/linkage/locationStoreMap/getLocation.json?cityCode=' + cityCode + '&parkCode=' + parkCode + '&location=' + location).then((res) => {
this.setState({
locationId: res.locationId,
storeHouseId: res.storeHouseId,
});
// 传过去库房ID,请求资产
// 要判断有没有选择代理人
let workNo = '';
const isReplaceDisabled = this.state.isReplaceDisabled; // false 选中
if (!isReplaceDisabled) { // 选了
const replacePerson = this.form_replace_person.getValues().values.replacePerson;
workNo = replacePerson && replacePerson.key.padStart(6, '0');
}
// 这儿又一次改变一次state,导致又重新渲染一次render。子组件会执行render
this.requestAsset(this.state.categoryTypeId, workNo, res.locationId);
});
}
tabClick(key) {
// 要判断有没有选择代理人
let workNo = '';
const isReplaceDisabled = this.state.isReplaceDisabled; // false 选中
if (!isReplaceDisabled) { // 选了
const replacePerson = this.form_replace_person.getValues().values.replacePerson;
workNo = replacePerson && replacePerson.key.padStart(6, '0');
}
this.requestAsset(key, workNo);
this.setState({
categoryTypeId: key,
// noDevice: false,
});
}
deviceListItem(resEquipmentInfo) {
if (resEquipmentInfo.length) {
return (
resEquipmentInfo.map((item) => (
<div className="deviceList-box">
<div className="deviceList-title">{item.value}</div>
<div className="deviceList-list">
{item.text.map((assetInfo) => (
<Asset
is11={this.state.is11}
selectLocationText={!!this.state.selectLocationText} // 是否选择了城市
storeLocationMappingId={this.state.storeHouseId}
add={this.add}
decrease={this.decrease}
radioOrCheckChange={this.radioOrCheckChange}
resDeviceInfo={assetInfo}
selectedAsset={this.state.selectedAsset.filter((list) => list.id === assetInfo.id)} // 选中的资产
showDialogInfo={() => { this.setState({ m4InfoDialog: true }); }}
/>
))}
</div>
</div>
))
);
}
return '没有找到设备';
}
// 单选多选选择事件
radioOrCheckChange(deviceInfo, value) {
const borrowType = this.formSelectTime.getValues().values.borrowType;
// 判断有没有选领用地点
if (!this.state.selectLocationText) {
Message.error('请选择领用地点!', 3);
return;
}
if (deviceInfo.stockNumber <= 0 && borrowType !== '双11、12专项') {
Message.error('设备无库存', 3);
return;
}
if (value.length === 0) {
this.cancelAsset(deviceInfo);
return;
}
const selectedAsset = this.state.selectedAsset;
// 先判断这个资产有没有选过
const thisAsset = selectedAsset.filter((list) => list.id === deviceInfo.id);
if (thisAsset.length) { // 选择过
} else { // 没有选择过,直接push
selectedAsset.push({ ...deviceInfo, num: 1, active: true });
}
this.setState({
selectedAsset,
});
}
// 取消选择
cancelAsset(deviceInfo) {
const selectedAsset = this.state.selectedAsset;
const result = selectedAsset.filter((list) => list.id !== deviceInfo.id);
this.setState({
selectedAsset: result,
});
}
// 增加
add(deviceInfo, num) {
// 双十一无
const borrowType = this.formSelectTime.getValues().values.borrowType;
if (deviceInfo.stockNumber <= num && borrowType !== '双11、12专项') {
Message.error('数量不能大于库存量!', 3);
return;
}
const selectedAsset = this.state.selectedAsset;
const result = selectedAsset.map((list) => {
if (list.id === deviceInfo.id) {
return {
...list,
num: list.num + 1,
};
}
return list;
});
this.setState({
selectedAsset: result,
});
}
// 减少
decrease(deviceInfo) {
const selectedAsset = this.state.selectedAsset;
const result = selectedAsset.map((list) => {
if (list.id === deviceInfo.id) {
return {
...list,
num: list.num - 1 <= 0 ? 1 : list.num - 1,
};
}
return list;
});
this.setState({
selectedAsset: result,
});
}
borrowTypeChange(values, name) {
// 从双十一切换到别的,要清空
if (name === 'borrowType') {
this.setState({
borrowDay: values.borrowType === '日常临时借用' ? 30 : 90,
is11: values.borrowType === '双11、12专项',
selectedAsset: [], // 清空选择的
});
}
}
// 上传附件
uploaderFileChange(fileList) {
const arr = fileList.map((list) => ({
...list,
response: {
...list.response,
data: {
downloadUrl: list.response.path,
},
},
}));
this.setState({
fileList: arr,
});
}
// 提交申请
submitSelect() {
const me = this;
// 判断有没有选领用地点
if (!this.state.selectLocationText) {
Message.error('请选择领用地点!', 3);
return;
}
const locationId = this.state.locationId;
const storeHouseId = this.state.storeHouseId;
// 判断有没有选择设备
const selectedAsset = this.state.selectedAsset;
if (!selectedAsset.length) {
Message.error('请选择领用的设备!', 3);
return;
}
// 借用类型
const formSelectTime = this.formSelectTime.getValues().values;
const borrowType = formSelectTime.borrowType;
if (!borrowType) {
Message.error('请选择借用类型!', 3);
return;
}
const borrowDate = formSelectTime.borrowDate;
if (!borrowDate || borrowDate.length !== 2) {
Message.error('请选择借用时间!', 3);
return;
}
const borrowDay = this.state.borrowDay;
if (this.formSelectTime.errors.borrowDate) {
Message.error(`借用时间不能大于${borrowDay}天!`, 3);
return;
}
// 有没有填写申请原因
const reasonForm = this.formReason.getValues();
const reasonData = reasonForm.values.reason;
if (!reasonData) {
Message.error('请填写申请原因!', 3);
return;
}
if (!reasonForm.pass) {
Message.error('申请原因不能超过字数限制!', 3);
return;
}
// 代理人
const replacePerson = this.form_replace_person.getValues().values.replacePerson;
const principleWorkId = replacePerson ? replacePerson.key.padStart(6, '0') : '';
// 附件
// 附件
const attachments = this.state.fileList.filter((file) => file.type !== 'delete').map((file) => ({
...file.response,
$model: {
...file.response,
},
$events: {},
$skipArray: true,
$accessors: {},
$1520219871783: [],
}));
this.setState({
sureDisabled: true,
});
const items = selectedAsset.map((list) => (
{
categoryAndFetureId: list.ampCategoryId,
equipmentConfigureId: list.idString,
categoryId: list.ampCategoryId,
categoryName: list.ampCategory,
stock: borrowType === '双11、12专项' ? '充足' : list.stockNumber,
requestStartDate: moment(borrowDate[0]).format('YYYY-MM-DD'),
requestEndDate: moment(borrowDate[1]).format('YYYY-MM-DD'),
requestAmount: list.num,
}
));
const jsonData = {
formType: 'Borrow',
principleWorkId,
locationId: storeHouseId,
storeLocationMappingId: locationId,
reason: reasonData + '(' + borrowType + ')',
items,
};
http.get('/workflow/event/applyBorrowValidate.json?jsonData=' + JSON.stringify(jsonData) + '&attachments=' + JSON.stringify(attachments)).then((res) => {
if (res.hasError) {
Dialog.info({
title: '提示',
content: res.errors[0].msg,
onOk() {
me.submit(jsonData, attachments);
},
});
} else {
me.submit(jsonData, attachments);
}
});
}
// submit
submit(jsonData, attachments) {
http.get('/workflow/event/applyAssetBorrow.json?jsonData=' + JSON.stringify(jsonData) + '&attachments=' + JSON.stringify(attachments)).then((res) => {
this.setState({
sureDisabled: false,
});
if (!res.hasError) {
window.location.href = '/workflow/task/mysubmit.htm';
}
});
}
// 搜索
search() {
const searchContent = this.form_select_Asset.getValues().values.search_content;
this.requestAssetXujie(searchContent && searchContent.main);
}
// 加载续借资产列表
requestAssetXujie(searchContent) {
this.setState({
isShowXujie: true,
});
http.get('/workflow/borrow/getBorrowAssets.json', {
params: {
search_content: searchContent, // undefined 不会传
},
}).then((res) => {
this.setState({
resEquipmentXujie: handleTableData(res.list),
isShowXujie: false,
});
});
}
xujieDayChange(id, values) {
this.setState({
selectXujie: this.state.selectXujie.map((list) => {
if (list.assetDescribe.id === id) {
return {
...list,
cycle: values.cycle,
};
}
return {
...list,
};
}),
});
}
// 续借取消选择
cancelXujie(data) {
this.xujieUi = this.xujieUi.filter((list) => list.props.data.assetDescribe.id !== data.assetDescribe.id);
this.setState({
selectXujie: this.state.selectXujie.filter((list) => list.assetDescribe.id !== data.assetDescribe.id),
resEquipmentXujie: this.state.resEquipmentXujie.map((list) => {
if (data.assetDescribe.id === list.assetDescribe.id) {
return {
...list,
jsxchecked: false,
};
}
return {
...list,
};
}),
});
}
uploaderFileChangeXujie(fileList) {
const arr = fileList.map((list) => ({
...list,
response: {
...list.response,
data: {
downloadUrl: list.response.path,
},
},
}));
this.setState({
fileListXujie: arr,
});
}
// 续借提交
submitSelectXujie() {
// 判断有没有选择续借设备
const { selectXujie } = this.state;
if (selectXujie.length === 0) {
Message.error('请选择续借设备!', 3);
return;
}
// 判断有没有填写续借时长
const formXujie = [];
this.xujieUi.forEach((xujie) => {
formXujie.push(xujie.formData());
});
if (formXujie.indexOf(false) !== -1) {
return;
}
// 申请原因
const reasonForm = this.formReasonXujie.getValues();
const reasonData = reasonForm.values.reason;
if (!reasonData) {
Message.error('请填写申请原因!', 3);
return;
}
if (!reasonForm.pass) {
Message.error('申请原因不能超过字数限制!', 3);
return;
}
this.setState({
sureDisabledXujie: true,
});
// 附件
const attachments = this.state.fileListXujie.filter((file) => file.type !== 'delete').map((file) => ({
...file.response,
$model: {
...file.response,
},
$events: {},
$skipArray: true,
$accessors: {},
$1520219871783: [],
}));
const jsonData = {
formType: 'ReBorrow',
reason: reasonData,
items: this.state.selectXujie.map((list) => ({
resourceId: list.idString,
cycle: list.cycle,
requestType: list.requestType,
requestAmount: 1,
})),
};
http.get('/workflow/borrow/ReBorrowSubmit.json?jsonData=' + JSON.stringify(jsonData) + '&attachments=' + JSON.stringify(attachments)).then((res) => {
if (res.hasError) {
Message.error(res.content, 3);
} else {
window.location.href = '/workflow/task/mysubmit.htm';
}
});
}
render() {
const me = this;
const rowSelection = {
onSelect(record, selected, selectedRows) {
// me.xujieUi = [];
me.setState({
selectXujie: selectedRows,
resEquipmentXujie: me.state.resEquipmentXujie.map((list) => {
if (list.assetDescribe.id === selected.assetDescribe.id) {
return {
...list,
jsxchecked: record,
};
}
return {
...list,
};
}),
});
},
onSelectAll(selected, selectedRows) {
// me.xujieUi = [];
me.setState({
selectXujie: selectedRows,
resEquipmentXujie: me.state.resEquipmentXujie.map((list) => ({
...list,
jsxchecked: selected,
})),
});
},
isDisabled(rowData) {
if (rowData.reborrowCount === '0') {
return false;
}
return true;
},
};
const columns = [
{
dataKey: 'assetDescribe',
title: '资源描述',
width: 249,
render: (data) => (<AssetDescribe data={data} />),
}, {
dataKey: 'assetLabel',
title: '资源标签',
width: 245,
message: <span>大阿里编号:号码为<font style={{ color: 'red' }}>TD</font>开头的标签。<br />资产标签:号码为<font style={{ color: 'red' }}>T50</font>或<font style={{ color: 'red' }}>B50</font>等等开头的标签。<br />电脑上贴的标签号码只要与前面2个中的其中1个对的上就可以了。</span>,
render: (data) => (<AssetLabel data={data} />),
}, {
dataKey: 'useCondition',
title: '使用情况',
width: 165,
render: (data) => (<AssetUseCondation data={data} />),
}, {
dataKey: 'reBorrowType',
title: '借用类型',
}, {
dataKey: 'reborrowCount',
title: '状态',
render: (data) => (data === '0' ? '可借用' : '已借用' + data + '次'),
},
];
const renderProps = {
height: 600,
jsxdata: { data: this.state.resEquipmentXujie },
rowSelection,
jsxcolumns: columns,
};
this.xujieUi = []; // 每次都要清空
return (
<div className="page-borrow">
{this.policyTip()}
<div className="borrow-title">
<span>资产借用申请单</span>
</div>
<div className="tab-wrapper">
<div className="tab-bar">
<div onClick={this.tabTranslateClick1} className={classnames('tab-bar-ink', { active: this.state.tabActive === '1' })}>资产借用</div>
<div onClick={this.tabTranslateClick2} className={classnames('tab-bar-ink', { active: this.state.tabActive === '2' })}>资产续借</div>
<div ref={(c) => { this.tabBottom = c; }} className="tab-bottom" />
</div>
<div ref={(c) => { this.tabContent = c; }} className="tab-content">
<div className="tab1">
{this.borrowPolicy()}
{this.replaceBox()}
{this.selectAddress()}
<div className="step-3">
{this.state.borrowDay ? <span className="max-date">(最长可借用{this.state.borrowDay}天)</span> : ''}
<div className="step-title">第二步:选择借用时间</div>
<Form ref={(c) => { this.formSelectTime = c; }} jsxonChange={this.borrowTypeChange}>
<SelectFormField jsxname="borrowType" jsxlabel="借用类型" jsxdata={[{ value: '日常临时借用', text: '日常临时借用' }, { value: '项目借用', text: '项目借用' }, { value: '双11、12专项', text: '双11、12专项' }]} />
<DateFormField jsxrules={[{ validator(value) { if (value && value[1] && me.state.borrowDay) { return moment(value[1]).diff(moment(value[0]), 'days') < me.state.borrowDay; } return true; }, errMsg: '借用时长大于最长借用时长!' }]} jsxname="borrowDate" jsxlabel="借用时间" jsxtype="cascade" />
</Form>
</div>
<div className="step-2">
<div className="step-title">第三步:选择领用的设备</div>
<div className="tab-box">
{this.state.noDevice ? '' : <div className="tab-loader-box">
<img alt="" src="https://aliwork.alicdn.com/tps/TB1fPYRMXXXXXcdXFXXXXXXXXXX-480-238.svg" />
</div>}
<Tabs type="stand" onTabClick={this.tabClick}>
{this.state.categoryType.map((item) => (<TabPane tabNum={sum(this.state.selectedAsset.filter((list) => list.categoryType === item.name).map((list) => list.num))} tab={item.name} value={item.id}>
{this.deviceListItem(this.state.resEquipmentInfo)}
</TabPane>))}
</Tabs>
</div>
</div>
{/* 选择详情 */}
<div className="select-info-box">
{this.state.selectedAsset.length ? <div className="select-info-title">已选设备:</div> : ''}
<div className="select-info">
{this.state.selectedAsset.map((selectAsset) => (
<div className="select-info-list">
<Asset
radioOrCheck="none"
showClose
closeAsset={this.cancelAsset}
resDeviceInfo={selectAsset}
add={this.add}
decrease={this.decrease}
selectedAsset={this.state.selectedAsset.filter((list) => list.id === selectAsset.id)}
/>
</div>
))}
</div>
</div>
<div className="step-4">
<div className="step-title">第四步:填写申请原因</div>
<Form
ref={(c) => { this.formReason = c; }}
>
<TextAreaFormField
jsxname="reason"
jsxplaceholder="请详细描述需求原因,减少审批人员的二次沟通;描述不清楚的需求,资产审批人员可能会直接驳回哦!"
jsxrules={[
{ validator(value) { return value ? value.length <= 256 : true; }, errMsg: '仅限256个字符' },
]}
>
<TextAreaCount total={256} />
</TextAreaFormField>
</Form>
</div>
{/* 添加附件 */}
<div className="add-file">
<Uploader
isOnlyImg={false}
multiple
name="assetUploadFile"
fileList={this.state.fileList}
url="/workflow/common/uploadFile.do"
onChange={this.uploaderFileChange}
/>
</div>
<div className="btn-box">
<Button disabled={this.state.sureDisabled} onClick={this.submitSelect}>提交申请</Button>
</div>
</div>
<div className="tab2">
{this.borrowPolicy()}
<div className="select-box">
<div className="select-form-label">搜索</div>
<Form ref={(c) => { this.form_select_Asset = c; }}>
<SearchFormField
jsxname="search_content"
tidy
placeholder="资产编号/大阿里编号/序列号"
onIconClick={this.search}
/>
</Form>
</div>
<div className="table-box">
{this.state.isShowXujie ? <div className="xujieLoading">
<img alt="" src="https://img.alicdn.com/tfs/TB132EFhntYBeNjy1XdXXXXyVXa-64-64.gif" />
</div> : ''}
<Table {...renderProps} />
</div>
<div className="xujie-select-info">
{this.state.selectXujie.length ? <div className="select-info-title">已选设备:</div> : ''}
<div className="select-info">
{this.state.selectXujie.map((list) => (
<XujieSelect ref={(c) => { c && this.xujieUi.push(c); }} data={list} closeAsset={this.cancelXujie} xujieDayChange={this.xujieDayChange} />
))}
</div>
</div>
{/* 第三步填写申请原因 */}
<div className="reason-box step-4">
<div className="step-title">请填写续借原因</div>
<Form
ref={(c) => { this.formReasonXujie = c; }}
>
<TextAreaFormField
jsxname="reason"
jsxplaceholder="请详细描述需求原因,减少审批人员的二次沟通;描述不清楚的需求,资产审批人员可能会直接驳回哦!"
jsxrules={[
{ validator(value) { return value ? value.length <= 256 : true; }, errMsg: '仅限256个字符' },
]}
>
<TextAreaCount total={256} />
</TextAreaFormField>
</Form>
</div>
{/* 添加附件 */}
<div className="add-file">
<Uploader
isOnlyImg={false}
multiple
name="assetUploadFile"
fileList={this.state.fileListXujie}
url="/workflow/common/uploadFile.do"
onChange={this.uploaderFileChangeXujie}
/>
</div>
<div className="btn-box">
<Button disabled={this.state.sureDisabledXujie} onClick={this.submitSelectXujie}>提交申请</Button>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Borrow;
// temp("temp", "日常临时借用", 30), project("project", "项目借用", 90), special("special", "双11,12专项", 90),
// 城市切换,选择的数据清空
// 借用类型切换
<file_sep>/**
* 自助柜补货
* author 刘玄清
* 2018-2-1
* 日常 0.1.1
* 线上 0.0.8
*/
import Button from 'uxcore-button';
import Form from 'uxcore-form';
import Table from 'uxcore-table';
import Dialog from 'uxcore-dialog';
import RadioGroup from 'uxcore-radiogroup';
import moment from 'moment';
import ReplacePeople from 'components/ReplacePeople';
import { http } from '../../lib/http';
import './selfAddGoods.less';
const { Constants } = Table;
const Message = require('uxcore-message'); // 全局提醒
// 本地开发 true
// 线上false
// 导航没有margin
// 内容 内边距20px
const { Item } = RadioGroup;
const {
InputFormField: Input,
SelectFormField,
FormRow: Row,
TextAreaFormField: TextArea,
} = Form;
// 提示信息
function errorTip(type, msg) {
Message[type](msg, 3);
}
// 时间格式化
function timeFormat(time) {
return moment(time).format('YYYY-MM-DD HH:mm:ss');
// 1注意不传字段时也会返回显示时间,要处理下
// 2 H 24小时制 h 12小时制
}
// 字符串不足6为,前面补全
function stringFormat(str) {
const { length } = str;
if (length < 6) {
const cha = 6 - length;
for (let i = 0; i < cha; i += 1) {
str = '0' + str.toString();
}
}
return str;
}
class SelfAddGoods extends React.Component {
constructor(props) {
super(props);
this.state = {
selectFormData: '', // 查询表单值
createGoodsDialogVisible: false, // 创建补货单弹窗的显示
dialogRadioValue: 'ou', // 补货单弹窗单选按钮的值
createErrorVisible: false, // 补货失败弹窗的显示
createFeedbackInfo: '', // 补货反馈信息
operatorInput: false, // 是否显示操作人
accessToken: '', // 获取accessToken
};
this.formPreValue = null; // 判断两次的表单值有没有变化
this.form_create = null;
}
componentDidMount() {
// 调用是否显示操作人
http.get('/admin/replenish/hiddenOperator.json').then((res) => {
if (res.hidden) { // 隐藏
this.setState({
operatorInput: false,
});
} else {
this.setState({
operatorInput: true,
accessToken: res.accessToken,
});
}
});
}
// 查询
selectClick() {
const me = this;
const formData = me.form.getValues().values;
if (window._.isEqual(formData, this.formPreValue)) { // 相等
this.tableE.fetchData(); // 如果每次都更新数据 会有异常
} else {
me.setState({
selectFormData: formData,
});
this.formPreValue = formData;
}
}
// 创建补货单弹窗
createClick() {
this.form_create && this.form_create.resetValues(); // 清空表单文本域
this.setState({
createGoodsDialogVisible: true,
dialogRadioValue: 'ou', // 重置按钮
});
}
// 补货单弹窗单选按钮
dialogRadioChange(value) {
this.setState({
dialogRadioValue: value,
});
}
// 创建补货单提交
submitCreate() {
const strType = this.state.dialogRadioValue;
const textArea = this.form_create.getValues().values.create;
this.setState({
createFeedbackInfo: '',
});
if (!textArea) { // 没有输入补货单
errorTip('info', '标签不能为空!');
return;
}
const assetCodes = textArea.split('\n').join(',');
http.post('/admin/replenish/addReplenish.json?assetCodes=' + assetCodes + '&strType=' + strType).then((res) => {
if (res.hasError) { // 失败
errorTip('error', res.errors[0].msg, 3);
} else {
this.setState({
createFeedbackInfo: res, // 反馈信息
createErrorVisible: true, // 显示反馈弹窗
createGoodsDialogVisible: false, // 隐藏创建弹窗
});
}
});
}
// 补货异常
createError() {
const { createFeedbackInfo } = this.state;
const errorTotal = createFeedbackInfo.errSum;
return (
<Dialog
title="补货信息反馈"
className="create-feedback"
visible={this.state.createErrorVisible}
footer={[
<Button onClick={this.errorDaochu.bind(this, errorTotal)} key="submit" size="small">{errorTotal === 0 ? '确定' : '确认并导出异常详情'}</Button>,
]}
onCancel={() => {
this.setState({
createErrorVisible: false,
});
}}
width={300}
>
<div>成功:{createFeedbackInfo.success}条</div>
<div>失败:{errorTotal}条</div>
</Dialog>
);
}
// 异常导出
errorDaochu(errorTotal) {
if (errorTotal === 0) { // 没有
this.setState({
createErrorVisible: false,
});
this.tableE.fetchData();
} else {
window.open('/admin/replenish/getResultExcel.json?data=' + JSON.stringify(this.state.createFeedbackInfo));
this.setState({
createErrorVisible: false,
});
}
}
// 撤销补货
cancelReplenish(rowData, table) {
Dialog.confirm({
title: '您确定要撤销补货吗?',
content: '撤销补货后,资产将存入“调出库房”;\n请您将实物也同步存入“调出库房”。',
onOk() {
http.post('/admin/replenish/cancelReplenish.json?id=' + rowData.id).then((res) => {
if (res.hasError) {
Message.error(res.errors[0].msg, 3);
} else {
Message.success(res.content, 3);
table.fetchData(); // 更新表格数据
}
});
},
onCancel() {},
});
}
// 格式化表格数据
tableBackData(tableData) {
return {
...tableData,
data: tableData.data.map(item => ({
...item,
__mode__: (item.replenishStatus === 'CANCEL' || item.replenishStatus === 'REPLENISHED') ? 'CANCEL' : 'view',
gmtCreated: item.gmtCreated && timeFormat(item.gmtCreated),
replenishDate: item.replenishDate && timeFormat(item.replenishDate),
cancelDate: item.cancelDate && timeFormat(item.cancelDate),
replenishStatus: item.replenishStatus === 'REPLENISHING' ? '补货中' : item.replenishStatus === 'REPLENISHED' ? '补货完成' : item.replenishStatus === 'CANCEL' ? '撤销' : '',
})),
};
}
render() {
const me = this;
const { selectFormData } = this.state;
// 列配置项
const columns = [
{
dataKey: 'assetCode',
title: '资产编号', // 表头
width: 130,
},
{
dataKey: 'resourceCode', // 匹配的字段
title: '大阿里编号',
width: 150,
},
{
dataKey: 'assetName',
title: '资产类目',
width: 80,
},
{
dataKey: 'featureName',
title: '特征',
width: 100,
},
{
dataKey: 'useRemark',
title: '使用说明',
width: 80,
},
{
dataKey: 'storePosition',
title: '调出库房',
width: 220,
},
{
dataKey: 'cabinetProperty',
title: '存入的自助柜',
width: 220,
},
{
dataKey: 'operatorName',
title: '操作人',
width: 150,
},
{
dataKey: 'gmtCreated',
title: '创建时间',
width: 150,
},
{
dataKey: 'replenishDate',
title: '存柜时间',
width: 150,
},
{
dataKey: 'replenishStatus',
title: '补货状态',
width: 80,
},
{
dataKey: 'cancelDate',
title: '撤销时间',
width: 150,
},
{
dataKey: 'action',
title: '操作',
width: 80,
type: 'action',
actions: [
{
title: '撤销',
callback: me.cancelReplenish.bind(this),
mode: Constants.MODE.VIEW,
},
],
},
];
const renderProps = {
height: 650,
width: 1140,
fetchUrl: '/admin/replenish/listReplenish.json',
jsxcolumns: columns,
showPager: true,
showPagerTotal: true,
fetchParams: { // 请求数据参数
assetCode: selectFormData.assetCodes,
operator: selectFormData.operator && stringFormat(selectFormData.operator.key),
status: selectFormData.status === 'all' ? '' : selectFormData.status,
},
processData: me.tableBackData.bind(this),
className: 'table-container',
doubleClickToEdit: false,
};
return (
<div className="page-selfAddGoods">
<div className="page-inner">
<div className="title">
<span>自助柜补货</span>
</div>
<div className="select-area">
<Form
ref={(c) => { this.form = c; }}
className="select-from"
jsxvalues={{
status: 'all',
}}
>
<Row>
<Input allowClear jsxname="assetCodes" jsxlabel="编号查询:" jsxplaceholder="资产编号\大阿里编号\序列号" />
{this.state.operatorInput ? (
<SelectFormField
jsxname="operator"
allowClear
jsxlabel="操作人:"
jsxplaceholder=""
jsxfetchUrl="https://work.alibaba-inc.com/work/xservice/open/api/v1/suggestion/suggestionAt.jsonp"
dataType="jsonp"
className="oprater-select"
beforeFetch={(data) => {
data.key = data.q;
data.offset = 0;
data.size = 8;
data.accessToken = me.state.accessToken;
return data;
}}
afterFetch={(obj) => {
let data = null;
data = obj.userList.map(item => ({
text: <ReplacePeople userList={item} />,
value: item.emplid, // 返回数据 key:
}));
return data;
}}
/>) : ''}
<SelectFormField
jsxname="status"
jsxlabel="补货状态:"
className="select-status"
jsxdata={[
{ value: 'REPLENISHING', text: '补货中' },
{ value: 'REPLENISHED', text: '完成' },
{ value: 'CANCEL', text: '撤销' },
{ value: 'all', text: '全部' },
]}
/>
</Row>
</Form>
<Button onClick={me.selectClick.bind(me)} className="select-btn">查 询</Button>
<Button onClick={me.createClick.bind(me)} className="select-btn-create">创建补货单</Button>
<Dialog title="创建补货单"
visible={this.state.createGoodsDialogVisible}
className="create-dialog"
onOk={me.submitCreate.bind(me)}
onCancel={() => {
this.setState({
createGoodsDialogVisible: false,
});
}}
>
<RadioGroup className="radio_select" value={me.state.dialogRadioValue} onChange={me.dialogRadioChange.bind(me)}>
<Item value="ou" text="大阿里编号" />
<Item value="assetcode" text="资产编号" />
</RadioGroup>
<Form ref={(c) => { this.form_create = c; }} className="dialog_form">
<TextArea jsxname="create" jsxplaceholder="一个标签占一行,用回车换行" jsxshowLabel={false} />
</Form>
</Dialog>
{this.createError()}
</div>
<div className="content-list">
<Table ref={(c) => { this.tableE = c; }} {...renderProps} />
</div>
</div>
</div>
);
}
}
export default SelfAddGoods;
/**
* 查询 注意表单为空的情况
* dialog 按钮value改变 可以用自定义footer
* From jsxvalues 默认值 匹配每个jsxname
* merge 本地
* dialog 使用自定义footer 确认取消时间要自己加
* 表格默认行内编辑
* 查询每次都可更新数据,如果两次数据一样,只执行更新表格数据;如果不一样则更新state来更显表格数据
* 下载 window.open(接口)
* state改变 重新刷新 render ,render所有的都会执行
* 不管state值两次有没有变化,执行setState都会触发render渲染
* table 可能是参数两次一样不会调用接口更新数据
* table默认可双击,进入编辑状态,操作按钮会消失 doubleClickToEdit: false
* 在daily执行tag
* tag 自动删除当前分支
* 先创建一个新分支,git pull origin master
*/
<file_sep>import * as React from 'react';
import * as ReactDOM from 'react-dom';
import SelfUse from './selfUse';
ReactDOM.render(
<SelfUse />,
document.getElementById('SelfUse'),
);
<file_sep>import Popover from 'uxcore-popover';
import { http } from '../../lib/http';
import './peoplePop.less';
class PeoplePop extends React.Component {
constructor(props) {
super(props);
this.state = {
personInfo: {}, // 员工信息
};
this.handleMouseOver = this.handleMouseOver.bind(this);
}
// 鼠标悬浮获取员工信息
handleMouseOver(workNum) {
http.get('/workflow/myassets/nikeName.json?workNo=' + workNum).then((res) => {
this.setState({
personInfo: res,
});
});
}
render() {
const {
person,
peopleIcon,
showLine,
} = this.props;
const { personInfo } = this.state;
const overlay = (
<div className="peopleInfoContent">
<p>部门:{personInfo.deptName}</p>
<table>
<tbody>
<tr>
<td>职位:{personInfo.postName}</td>
<td>工号:{personInfo.workNo}</td>
</tr>
<tr>
<td>分机:{personInfo.indirectPhone}</td>
<td>手机:{personInfo.mobile}</td>
</tr>
<tr>
<td>旺旺:{personInfo.wangwang}</td>
<td>邮箱:<a href={`mailto:${personInfo.email}`}>{personInfo.email}</a></td>
</tr>
</tbody>
</table>
</div>
);
if (person === '资产小助手') {
return <span>资产小助手</span>;
}
if (Object.prototype.toString.call(person) === '[object Array]') {
if (showLine) {
const perNameNumShowLine = person[0].split(',');
return (<Popover placement="bottom" overlay={overlay}>
<a className="personPop" href={`https://work.alibaba-inc.com/u/${perNameNumShowLine[1]}`} target="_blank">
<span onMouseOver={() => this.handleMouseOver(perNameNumShowLine[1])} className={`${this.props.className || ''}`}>{peopleIcon ? <i className="peopleIcon" /> : ''}{perNameNumShowLine[0]}</span>
</a>
</Popover>);
}
const result = person.map((per) => {
const perNameNum = per.split(',');
if (!perNameNum[0] || !perNameNum[1]) {
return <span style={{ lineHeight: '22px' }}>{per}</span>;
}
return (
<Popover placement="bottom" overlay={overlay}>
<p className="personPop">
<a href={`https://work.alibaba-inc.com/u/${perNameNum[1]}`} target="_blank">
<span onMouseOver={() => this.handleMouseOver(perNameNum[1])} className={`${this.props.className || ''}`}>{peopleIcon ? <i className="peopleIcon" /> : ''}{perNameNum[0]}</span>
</a>
</p>
</Popover>
);
});
// }
return <span>{result}</span>;
}
if (person) {
// 从person分离工号和人名
if (person.indexOf('**') !== -1) {
const _perNameNum = person.split('**');
const _perNameNum2 = _perNameNum[1].split(',');
return (
<div className="_perNameNum2">
<span>{_perNameNum[0]}</span>
<Popover placement="bottom" overlay={overlay}>
<a className="personPop" href={`https://work.alibaba-inc.com/u/${_perNameNum2[2]}`} target="_blank">
<span onMouseOver={() => this.handleMouseOver(_perNameNum2[2])} className={`${this.props.className || ''}`}>{peopleIcon ? <i className="peopleIcon" /> : ''}{_perNameNum2[0]}</span>
</a>
</Popover>
</div>
);
}
const perNameNum = person.split(',');
if (!perNameNum[0] || !perNameNum[1]) {
return <span>{person}</span>;
}
return (<Popover placement="bottom" overlay={overlay}>
<a className="personPop" href={`https://work.alibaba-inc.com/u/${perNameNum[1]}`} target="_blank">
<span onMouseOver={() => this.handleMouseOver(perNameNum[1])} className={`${this.props.className || ''}`}>{peopleIcon ? <i className="peopleIcon" /> : ''}{perNameNum[0]}</span>
</a>
</Popover>);
}
return <span />;
}
}
export default PeoplePop;
/**
* 2 等待领用不显示
* 3 加载中
*/
<file_sep>import ReplacePeople from './replacePeople';
export default ReplacePeople;
<file_sep>import Icon from 'uxcore-icon';
import Popover from 'uxcore-popover';
import RadioGroup from 'uxcore-radiogroup';
import classnames from 'classnames';
import './asset.less';
const RadioItem = RadioGroup.Item;
class Asset extends React.Component {
constructor(props) {
super(props);
}
render() {
const { deviceInfo, showClose } = this.props;
const overlay = (
<div className="m4-info-content">
超出岗位配置,需要部门M4审批
<span onClick={this.props.showDialogInfo}>[配置标准]</span>
</div>
);
return (
<div className="device-container">
<div className={classnames('device-header', { closeBtn: showClose })}>
<RadioGroup
className="check-asset"
onChange={this.props.radioOrCheckChange.bind(null, deviceInfo)}
value={this.props.selectAssetRadio}
>
<RadioItem value={deviceInfo.modelDetailId + deviceInfo.categoryType} text={deviceInfo.modelDetail} />
</RadioGroup>
{showClose ?
<div className="close-box">
<Icon onClick={this.props.closeAsset.bind(null, deviceInfo)} name="guanbi" className="close-btn" />
</div> :
deviceInfo.authority ? '' :
<Popover overlay={overlay} placement="bottomRight" overlayClassName="asset-m4-info">
<div className="m4-info">
<Icon name="jinggao-full" className="icon" />
</div>
</Popover>
}
</div>
<div className="describe">{deviceInfo.configureMsg}</div>
<div className="img-num">
<div className="img-box">
<span>
<img data-action="zoom" data-original={'/workflow/common/getFile.json?path=' + deviceInfo.bigImgPath1} alt="" src={'/workflow/common/getFile.json?path=' + deviceInfo.smallImgPath1} />
</span>
{deviceInfo.smallImgPath2 ? (
<span>
<img data-action="zoom" data-original={'/workflow/common/getFile.json?path=' + deviceInfo.bigImgPath2} alt="" src={'/workflow/common/getFile.json?path=' + deviceInfo.smallImgPath2} />
</span>
) : ''}
</div>
</div>
</div>
);
}
}
Asset.defaultProps = {
radioOrCheck: 'radio', // 默认单选
deviceInfo: {}, // 一个资产信息
selectAssetRadio: '', // 单选 --- 选中的资产
radioOrCheckChange: () => {}, // 选择函数
// authority: true, // true不显示M4提示,false显示
showDialogInfo: () => {},
closeAsset: () => {},
};
export default Asset;
<file_sep>import * as ReactDOM from 'react-dom';
import ChangeViewTask from './changeViewTask';
ReactDOM.render(
<ChangeViewTask />,
document.getElementById('changeViewTask'),
);
<file_sep>import Icon from 'uxcore-icon';
import Popover from 'uxcore-popover';
import CheckboxGroup from 'uxcore-checkbox-group';
import classnames from 'classnames';
import CalNum from './calNum';
import BigImg from './bigImg';
import './asset.less';
const Item = CheckboxGroup.Item;
// 组件
class Asset extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false,
num: 0,
};
this.add = this.add.bind(this);
this.decrease = this.decrease.bind(this);
}
// Tab切换导致组件重新渲染
componentDidMount() {
const activeAsset = (this.props.selectedAsset && this.props.selectedAsset.filter((list) => list.modelDetail === this.props.resDeviceInfo.modelDetail)) || [];
if (activeAsset.length === 0) {
this.setState({
active: false,
num: 0,
});
} else {
this.setState({
active: true,
num: activeAsset[0].num,
});
}
}
// 传递来新的props触发
componentWillReceiveProps(nextProps) {
/**
*
* 这里说的不会造成第二次的渲染,并不是说这里的setState不会生效。在这个方法里调用setState会在组件更新完成之后在render方法执行之前更新状态,
* 将两次的渲染合并在一起。可以在componentWillReceiveProps执行setState,但是如果你想在这个方法里获取this.state得到的将会是上一次的状态。
*/
// 过滤出当前的
const activeAsset = (nextProps.selectedAsset && nextProps.selectedAsset.filter((list) => list.modelDetail === nextProps.resDeviceInfo.modelDetail)) || [];
if (activeAsset.length === 0) {
this.setState({
active: false,
num: 0,
});
} else {
this.setState({
active: true,
num: activeAsset[0].num,
});
}
}
add(num) {
if (this.state.active) {
this.props.add(this.props.resDeviceInfo, num);
}
}
decrease() {
if (this.state.active) {
this.props.decrease(this.props.resDeviceInfo);
}
}
render() {
const {
resDeviceInfo,
showClose,
radioOrCheck,
selectedAsset,
selectLocationText,
is11,
} = this.props;
const overlay = (
<div className="m4-info-content">
超出岗位配置,需要部门M4审批
<span onClick={this.props.showDialogInfo}>[配置标准]</span>
</div>
);
let stockNumber = null;
if (resDeviceInfo.stockNumber >= 10 || is11) {
stockNumber = <div style={{ paddingLeft: '38px', color: '#666', opacity: 0.8 }}>库存充足</div>;
} else if (resDeviceInfo.stockNumber > 0) {
stockNumber = <div style={{ paddingLeft: '38px', color: '#F37327' }}>库存紧张,剩余{resDeviceInfo.stockNumber}</div>;
} else {
stockNumber = <div style={{ paddingLeft: '38px', color: '#F37327' }}>所选区域无库存</div>;
}
return (
<div className={classnames('device-container', { active: this.state.active })}>
<div className={classnames('device-header', { closeBtn: showClose })}>
{radioOrCheck === 'checkbox' ? (
<CheckboxGroup
className="check-asset"
onChange={this.props.radioOrCheckChange.bind(null, resDeviceInfo)}
value={selectedAsset[0] && selectedAsset[0].id.toString()}
disabled={selectLocationText ? is11 ? false : resDeviceInfo.stockNumber <= 0 : false}
>
<Item value={resDeviceInfo.id + ''} text={resDeviceInfo.modelDetail} />
</CheckboxGroup>
) : (<CheckboxGroup
className="check-asset"
>
<Item text={resDeviceInfo.modelDetail} />
</CheckboxGroup>)}
{showClose ?
<div className="close-box">
<Icon onClick={this.props.closeAsset.bind(null, resDeviceInfo)} name="guanbi" className="close-btn" />
</div> :
resDeviceInfo.authority ? '' :
<Popover overlay={overlay} placement="bottomRight" overlayClassName="asset-m4-info">
<div className="m4-info">
<Icon name="jinggao-full" className="icon" />
</div>
</Popover>
}
</div>
<div className="describe">{resDeviceInfo.configureMsg}</div>
{selectLocationText ? stockNumber : ''}
<div className="img-num">
<div className="img-box">
<span>
<BigImg original={'/workflow/common/getFile.json?path=' + resDeviceInfo.bigImgPath1} src={'/workflow/common/getFile.json?path=' + resDeviceInfo.smallImgPath1} />
</span>
{resDeviceInfo.smallImgPath2 ? (
<span>
<BigImg src={'/workflow/common/getFile.json?path=' + resDeviceInfo.smallImgPath2} original={'/workflow/common/getFile.json?path=' + resDeviceInfo.bigImgPath2} />
</span>
) : ''}
</div>
<CalNum num={this.state.num} add={this.add} decrease={this.decrease} className="select-num" />
</div>
</div>
);
}
}
Asset.defaultProps = {
radioOrCheck: 'checkbox', // 默认单选
resDeviceInfo: {}, // 一个资产信息
selectAssetRadio: '', // 单选 --- 选中的资产
radioOrCheckChange: () => {}, // 选择函数
// authority: true, // true不显示M4提示,false显示
showDialogInfo: () => {},
};
export default Asset;
<file_sep>import * as ReactDOM from 'react-dom';
import DeviceManage from './deviceManage';
ReactDOM.render(
<DeviceManage />,
document.getElementById('deviceManage'),
);
<file_sep>import Icon from 'uxcore-icon';
import CalNum from './calNum';
import './selectAsset.less';
class SelectAsset extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
const props = this.props;
const { deviceInfo, radioOrCheck, closeAsset } = props;
return (
<div className="selectAsset-box">
<div className="img-box">
<img alt="" data-action="zoom" data-original={'/workflow/common/getFile.json?path=' + deviceInfo.bigImgPath1} src={'/workflow/common/getFile.json?path=' + deviceInfo.smallImgPath1} />
</div>
<div className="right-describe">
<span className="asset-name">{deviceInfo.modelDetail}</span>
{radioOrCheck === 'radio' ? <p className="asset-num">1</p> : <CalNum className="selectAsset-num" />}
</div>
<div onClick={closeAsset.bind(null, deviceInfo)} className="close">
<Icon name="guanbi" />
</div>
</div>
);
}
}
SelectAsset.defaultProps = {
deviceInfo: {}, // 资产信息
radioOrCheck: 'radio', // 默认单选
closeAsset: () => {},
};
export default SelectAsset;
<file_sep>import * as React from 'react'
import * as ReactDOM from 'react-dom'
import UseAddress from './useAddress'
ReactDOM.render(
<UseAddress/>,
document.getElementById('UseAddress'))
<file_sep>import Icon from 'uxcore-icon';
import Popover from 'uxcore-popover';
import RadioGroup from 'uxcore-radiogroup';
import classnames from 'classnames';
import CalNum from './calNum';
import './asset.less';
const RadioItem = RadioGroup.Item;
class Asset extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false,
num: 0,
};
this.add = this.add.bind(this);
this.decrease = this.decrease.bind(this);
}
// Tab切换导致组件重新渲染
componentDidMount() {
const activeAsset = this.props.activeDevice && this.props.activeDevice.filter((list) => list.modelDetail === this.props.deviceInfo.modelDetail);
// console.log(this.props.activeDevice, 'componentDidMount');
if (activeAsset.length === 0) {
this.setState({
active: false,
num: 0,
});
} else {
this.setState({
active: true,
num: activeAsset[0].num,
});
}
}
// 传递来新的props触发
componentWillReceiveProps(nextProps) {
// 过滤出当前的
const activeAsset = (nextProps.activeDevice && nextProps.activeDevice.filter((list) => list.modelDetail === nextProps.deviceInfo.modelDetail)) || [];
// console.log(nextProps.activeDevice, 'componentWillReceiveProps');
if (activeAsset.length === 0) {
this.setState({
active: false,
num: 0,
});
} else {
this.setState({
active: true,
num: activeAsset[0].num,
});
}
}
add() {
if (this.state.active) {
this.props.add(this.props.deviceInfo);
}
}
decrease() {
if (this.state.active) {
this.props.decrease(this.props.deviceInfo);
}
}
render() {
const {
deviceInfo,
showClose,
radioOrCheck,
} = this.props;
const overlay = (
<div className="m4-info-content">
超出岗位配置,需要部门M4审批
<span onClick={this.props.showDialogInfo}>[配置标准]</span>
</div>
);
return (
<div className={classnames('device-container', { active: this.state.active })}>
<div className={classnames('device-header', { closeBtn: showClose })}>
{radioOrCheck === 'radio' ? (
<RadioGroup
className="check-asset"
onChange={this.props.radioOrCheckChange.bind(null, 'radio', deviceInfo)}
value={this.props.selectAssetRadio}
>
<RadioItem value={deviceInfo.modelDetailId + deviceInfo.categoryType} text={deviceInfo.modelDetail} />
</RadioGroup>
) : <RadioGroup
className="check-asset"
>
<RadioItem text={deviceInfo.modelDetail} />
</RadioGroup>}
{showClose ?
<div className="close-box">
<Icon onClick={this.props.closeAsset.bind(null, deviceInfo)} name="guanbi" className="close-btn" />
</div> :
deviceInfo.authority ? '' :
<Popover overlay={overlay} placement="bottomRight" overlayClassName="asset-m4-info">
<div className="m4-info">
<Icon name="jinggao-full" className="icon" />
</div>
</Popover>
}
</div>
<div className="describe">{deviceInfo.configureMsg}</div>
<div className="img-num">
<div className="img-box">
<span>
<img data-action="zoom" data-original={'/workflow/common/getFile.json?path=' + deviceInfo.bigImgPath1} alt="" src={'/workflow/common/getFile.json?path=' + deviceInfo.smallImgPath1} />
</span>
{deviceInfo.smallImgPath2 ? (
<span>
<img data-action="zoom" data-original={'/workflow/common/getFile.json?path=' + deviceInfo.bigImgPath2} alt="" src={'/workflow/common/getFile.json?path=' + deviceInfo.smallImgPath2} />
</span>
) : ''}
</div>
<CalNum num={this.state.num} add={this.add} decrease={this.decrease} className="select-num" />
</div>
</div>
);
}
}
Asset.defaultProps = {
radioOrCheck: 'radio', // 默认单选
deviceInfo: {}, // 一个资产信息
selectAssetRadio: '', // 单选 --- 选中的资产
radioOrCheckChange: () => {}, // 选择函数
// authority: true, // true不显示M4提示,false显示
showDialogInfo: () => {},
};
export default Asset;
<file_sep>import Crumb from 'uxcore-crumb';
import moment from 'moment';
import Icon from 'uxcore-icon';
import Select from 'uxcore-select2';
import Button from 'uxcore-button';
import Dialog from 'uxcore-dialog';
import Popover from 'uxcore-popover';
import Form from 'uxcore-form';
import Message from 'uxcore-message';
import Table from 'uxcore-table';
import Uploader from 'components/uploader';
import './zooming';
import { http } from '../../lib/http';
import AssetDescribe from './assetDescribe';
import Asset from './asset';
import util from './util';
import { objToArray, locationObjToArray } from '../../lib/util';
import './changeSelectSubmit.less';
/**
* 第三步选择更换设备
*/
const { parseURL } = util;
const Option = Select.Option;
const { TextAreaFormField } = Form;
const { TextAreaCount } = TextAreaFormField;
// 处理列表返回的数据
function handleTableData(data) {
return data.map((list) => ({
assetDescribe: {
categoryName: list.categoryName, // 名称
feature: list.feature, // 特征
userName: list.userName, // 使用人
categoryIdString: list.categoryIdString, // 获取资产图片的id
id: list.id,
user: list.user,
},
assetLabel: {
ouResourceCode: list.ouResourceCode, // 大阿里编号
resourceCode: list.resourceCode, // 资产编号
sn: list.sn, // 序列号
},
useCondition: {
startDate: list.startDate, // 启用日期
usedMonths: list.usedMonths, // 已使用月
useRemarkName: list.useRemarkName, // 使用说明
},
workFlowName: list.workFlowName,
workFlowType: list.workFlowType,
instanceId: list.instanceId,
}));
}
// 资源标签
const AssetLabel = (props) => (
<div className="assetLabel-wrapper">
<p>大阿里编号:{props.data.ouResourceCode}</p>
<p>资 产 编 号:{props.data.resourceCode}</p>
<p>序 列 号:{props.data.sn}</p>
</div>
);
// 使用情况
const AssetUseCondation = (props) => (
<div className="assetLabel-condation">
<p>启用日期:{props.data.startDate ? moment(props.data.startDate).format('YYYY-MM-DD') : ''}</p>
<p>已使用月:{props.data.usedMonths}</p>
<p>使用说明:{props.data.useRemarkName}</p>
</div>
);
class ChangeSelectBill extends React.Component {
constructor(props) {
super(props);
this.state = {
assetData: [], // 表格数据
citys: [], // 获取的城市
selectCityCode: '', // 选择的城市
parks: [], // 获取的园区
selectParkCode: '', // 选择的园区
locations: [], // 获取的地点
selectLocationText: '', // 选择的地点
locationId: '', // 选择的地点ID
storeHouseId: '', // 选择的库房ID
noDevice: false,
resEquipmentInfo: [], // 资产列表
m4InfoDialog: false, // 资产领用政策
selectAssetInfo: [], // 选中的资产
fileList: [], // 附件
jsonData: {}, // 提交数据
attachments: [], // 附件
chnageInfoShowDialog: false, // 更换详情弹窗
submitDisabled: false,
sureDisabled: false,
validate: [], // 校验信息
usedMonths: '',
};
this.handleCityChange = this.handleCityChange.bind(this);
this.handleParkChange = this.handleParkChange.bind(this);
this.handleLocationChange = this.handleLocationChange.bind(this);
this.obtainLocationId = this.obtainLocationId.bind(this);
this.radioOrCheckChange = this.radioOrCheckChange.bind(this);
this.cancelAsset = this.cancelAsset.bind(this);
this.submitSelect = this.submitSelect.bind(this);
this.handleDialogOk = this.handleDialogOk.bind(this);
this.uploaderFileChange = this.uploaderFileChange.bind(this);
}
componentDidMount() {
http.get('/workflow/common/checkCanProcess.json').then((resp) => {
if (!resp) { // 不能
Dialog.error({
content: '此设备不能更换',
onOk() {
window.location.href = '/workflow/change/select_asset.htm';
},
onCancel() {
window.location.href = '/workflow/change/select_asset.htm';
},
});
} else {
const url = window.location.href;
const paramsData = parseURL(url).params;
// 获取要更换的资产详细信息
http.get('/workflow/change/getDetail.json?resourceId=' + paramsData.resourceId).then((res) => {
this.setState({
assetData: handleTableData(res),
usedMonths: res[0].usedMonths,
});
});
// 获取城市
http.get('/linkage/locationStoreMap/getCity.json').then((res) => {
if (res.hasError) {
Message.error(res.content, 3);
} else {
this.setState({
citys: objToArray(res),
});
}
});
// 获取城市,园区,地点,提示元素
this.cityPlaceholderEle = document.getElementsByClassName('select-city')[0].getElementsByClassName('kuma-select2-selection__placeholder')[0];
this.parkPlaceholderEle = document.getElementsByClassName('select-park')[0].getElementsByClassName('kuma-select2-selection__placeholder')[0];
this.locationPlaceholderEle = document.getElementsByClassName('select-location')[0].getElementsByClassName('kuma-select2-selection__placeholder')[0];
// 获取资产信息
http.get('/workflow/change/getChangeData.json?resourceId=' + paramsData.resourceId).then((resChangeData) => {
const categoryTypeId = resChangeData.mapping.monitor ? 1 : 0;
http.get('/newemployee/equipment/getEquipmentInfo.json', {
params: {
workFlowType: '更换',
categoryTypeId,
enumWorkFlowType: 'Change',
workNo: paramsData.userId,
usedMonths: this.state.usedMonths,
},
}).then((resEquipmentInfo) => {
this.setState({
resEquipmentInfo: objToArray(resEquipmentInfo),
});
});
});
}
});
}
// 选择城市,获取园区
handleCityChange(value) {
this.cityPlaceholderEle.setAttribute('style', 'opacity: 0');
this.parkPlaceholderEle.style.opacity = 1; // 恢复提示
this.locationPlaceholderEle.style.opacity = 1;
this.setState({
selectCityCode: value,
selectParkCode: '', // 清空园区
selectLocationText: '', // 清空地点 ps 清空值,也要清空下拉数据
locations: [], // 清空地点下拉数据
});
http.get('/linkage/locationStoreMap/getPark.json?cityCode=' + value).then((res) => {
this.setState({
parks: objToArray(res),
});
});
}
// 选择园区,获取地点
handleParkChange(value) {
this.parkPlaceholderEle.style.opacity = 0;
this.locationPlaceholderEle.style.opacity = 1;
const cityCode = this.state.selectCityCode;
this.setState({
selectParkCode: value,
selectLocationText: '', // 清空地点
});
http.get('/linkage/locationStoreMap/getLocation.json?cityCode=' + cityCode + '&parkCode=' + value).then((res) => {
this.setState({
locations: locationObjToArray(res),
});
});
}
// 选择领用地点
handleLocationChange(text) {
this.locationPlaceholderEle.style.opacity = 0;
this.obtainLocationId(text);
this.setState({
selectLocationText: text,
});
}
// 选择完地点后,获取locationId和storeHouseId
obtainLocationId(location) {
const cityCode = this.state.selectCityCode;
const parkCode = this.state.selectParkCode;
http.get('/linkage/locationStoreMap/getLocation.json?cityCode=' + cityCode + '&parkCode=' + parkCode + '&location=' + location).then((res) => {
this.setState({
locationId: res.locationId,
storeHouseId: res.storeHouseId,
});
});
}
// 资产领用政策
assetUsePolicy() {
return (
<Dialog
title={<span><Icon name="jinggao-full" className="icon" />资产领用规则</span>}
visible={this.state.m4InfoDialog}
className="m4-info-dialog"
footer={
<Button onClick={() => {
this.setState({
m4InfoDialog: false,
});
}}
type="primary"
>知道啦</Button>}
onCancel={() => {
this.setState({
m4InfoDialog: false,
});
}}
>
<ol>
<li>B2B销售:M2以下不配置公司电脑,M2及以上标配普通笔记本;直销不配置电脑。</li>
<li>外包、实习生、客满座席(P4以下)标配普通台式机。</li>
<li>Jobcode(内网岗位名称)是技术、UED:新入职员工或名下电脑使用满42个月的老员工可申请MacBook Pro。</li>
<li>Jobcode(内网岗位名称)是技术、UED、BI:可配置大屏显示器(22寸及以上)。</li>
<li>除以上其他岗位标配普通笔记本;应蚂蚁金服安全部要求,蚂蚁、口碑非技术、UED同学不配置MAC电脑。</li>
<li>电脑、耳麦等领用遵循一人一机原则。</li>
</ol>
</Dialog>
);
}
// 资产选择
radioOrCheckChange(deviceInfo, value) {
const selectAssetInfoArr = [];
selectAssetInfoArr.push(deviceInfo);
this.setState({
selectAssetRadio: value,
selectAssetInfo: selectAssetInfoArr,
});
}
// 取消选择
cancelAsset() {
this.setState({
selectAssetRadio: '',
selectAssetInfo: [],
});
}
// 上传附件
uploaderFileChange(fileList) {
const arr = fileList.map((list) => ({
...list,
response: {
...list.response,
data: {
downloadUrl: list.response.path,
},
},
}));
this.setState({
fileList: arr,
});
}
// 提交申请
submitSelect() {
const url = window.location.href;
const params = parseURL(url).params;
// 判断有没有选领用地点
if (!this.state.selectLocationText) {
Message.error('请选择领用地点!', 3);
return;
}
const locationId = this.state.storeHouseId.split(',')[0];
const storeLocationMappingId = this.state.locationId;
// 判断有没有选择设备
const selectAssetRadio = this.state.selectAssetRadio;
if (!selectAssetRadio) {
Message.error('请选择领用的设备!', 3);
return;
}
// 有没有填写申请原因
const reasonForm = this.formReason.getValues();
const reason = reasonForm.values.reason;
if (!reason) {
Message.error('请填写申请原因!', 3);
return;
}
if (!reasonForm.pass) {
Message.error('申请原因不能超过字数限制!', 3);
return;
}
this.setState({
sureDisabled: true,
});
const selectAssetInfo = this.state.selectAssetInfo[0];
// 附件
const attachments = this.state.fileList.filter((file) => file.type !== 'delete').map((file) => ({
...file.response,
$model: {
...file.response,
},
$events: {},
$skipArray: true,
$accessors: {},
$1520219871783: [],
}));
const jsonData = {
principleWorkId: params.userId,
locationId,
reason,
manageType: 'it',
formType: 'Change',
returnType: params.returnType,
storeLocationMappingId,
items: [
{
categoryAndFetureId: selectAssetInfo.ampCategoryId,
requestAmount: 1,
equipmentConfigureId: selectAssetInfo.id,
},
{
resourceId: params.resourceId,
requestAmount: 1,
returnType: params.returnType,
},
],
};
http.get('/workflow/change/validate.json', {
params: {
jsonData,
attachments: JSON.stringify(attachments), // 数组参数前自带[]
},
}).then((res) => {
this.setState({
chnageInfoShowDialog: true,
jsonData,
attachments,
sureDisabled: false,
validate: res,
});
});
}
// 提交
handleDialogOk() {
this.setState({
submitDisabled: true,
});
const jsonData = this.state.jsonData;
const attachments = this.state.attachments;
http.get('/workflow/change/submitChange.json', {
params: {
jsonData,
attachments: JSON.stringify(attachments),
},
}).then((res) => {
this.setState({
submitDisabled: false,
});
if (res.hasError) {
Message.error(res.content, 3);
} else {
window.location.href = '/workflow/task/mysubmit.htm';
}
});
}
render() {
const overlay = (
<div className="tip">
<Icon name="jinggao-full" className="icon" />
<div className="important-tip">更换政策:</div>
<p>1、内网岗位名称是技术、UED、BI、风控的岗位:可配置台式机+单屏大屏、台式机+双屏(大屏+中屏)、笔记本+单屏大屏;客服-热线&在线和
客服-交易保障:可配置中屏双屏。其余岗位不配置双屏显示器(笔记本算一块显示屏); 大屏:22寸及以上;中屏:大于17寸小于22寸;小屏:
17寸及以下。
</p>
<p>2. 其他因显示器故障问题置换需选择损坏更换:提交流程前请先打1818-3检测处理;</p>
<p>3. 显示器暂不支持自购。</p>
</div>
);
const columns = [
{
dataKey: 'assetDescribe',
title: '资源描述',
width: 299,
render: (data) => (<AssetDescribe data={data} />),
},
{
dataKey: 'assetLabel',
title: '资源标签',
width: 265,
message: <span>大阿里编号:号码为<font style={{ color: 'red' }}>TD</font>开头的标签。<br />资产标签:号码为<font style={{ color: 'red' }}>T50</font>或<font style={{ color: 'red' }}>B50</font>等等开头的标签。<br />电脑上贴的标签号码只要与前面2个中的其中1个对的上就可以了。</span>,
render: (data) => (<AssetLabel data={data} />),
},
{
dataKey: 'useCondition',
title: '使用情况',
width: 185,
render: (data) => (<AssetUseCondation data={data} />),
},
];
const renderTable = {
jsxdata: { data: this.state.assetData },
jsxcolumns: columns,
doubleClickToEdit: false,
// height: 575,
};
const url = window.location.href;
const params = parseURL(url).params;
return (
<div className="changeSelectBill">
{this.assetUsePolicy()}
<div className="bill-crumb">
<Crumb className="crumb-style crumb-root">
<Crumb.Item target="_blank" href="/workflow/change/select_asset.htm" className="crumb-item-style">资产更换</Crumb.Item>
<Crumb.Item>申请单</Crumb.Item>
</Crumb>
</div>
<div className="bill-title">
<span>资产更换申请单</span>
</div>
<div className="change-policy">
<Icon name="jinggao-full" className="icon" />
<span className="policy">更换政策</span>
<Popover overlay={overlay} placement="top" trigger="click">
<span className="info-tip">[查看详情]</span>
</Popover>
</div>
<div className="daiChange-tip">
<span>待更换设备</span>
<a href="/workflow/change/select_asset.htm">重新选择</a>
</div>
<div className="daiChange-table">
<Table ref={(c) => { this.table = c; }} {...renderTable} />
</div>
<div className="step-1">
<div className="step-title">第一步:选择新设备的领用地点</div>
<span>领用地点</span>
<Select onChange={this.handleCityChange} className="select-city" placeholder="城市">
{this.state.citys.map((city) => (<Option value={city.value}>{city.text}</Option>))}
</Select>
<Select value={this.state.selectParkCode} onChange={this.handleParkChange} className="select-park" placeholder="园区">
{this.state.parks.map((park) => (<Option value={park.value}>{park.text}</Option>))}
</Select>
<Select value={this.state.selectLocationText} onChange={this.handleLocationChange} className="select-location" placeholder="领用位置">
{this.state.locations.map((location) => (<Option value={location.value}>{location.text}</Option>))}
</Select>
</div>
<div className="step-2">
<div className="step-title">第二步:选择需领用的设备</div>
<div className="tab-box">
{this.state.resEquipmentInfo.map((list) => (
<div className="deviceList-box">
<div className="deviceList-title">{list.value}</div>
<div className="deviceList-list">
{list.text.map((assetInfo) => (
<Asset
radioOrCheckChange={this.radioOrCheckChange}
selectAssetRadio={this.state.selectAssetRadio}
deviceInfo={assetInfo}
showDialogInfo={() => { this.setState({ m4InfoDialog: true }); }}
/>
))}
</div>
</div>
))}
</div>
</div>
{/* 已选设备 */}
{this.state.selectAssetInfo.map((list) => (
<div className="select-info-box">
<div className="select-info-title">已选设备:</div>
<div className="select-info-list">
<Asset radioOrCheck="none" showClose closeAsset={this.cancelAsset} deviceInfo={list} />
</div>
</div>
))}
{/* 第三步填写申请原因 */}
<div className="reason-box">
<div className="step-title">第三步:填写申请原因</div>
<Form
ref={(c) => { this.formReason = c; }}
>
<TextAreaFormField
jsxname="reason"
jsxplaceholder="请详细描述需求原因,减少审批人员的二次沟通;描述不清楚的需求,资产审批人员可能会直接驳回哦!"
>
<TextAreaCount total={256} />
</TextAreaFormField>
</Form>
</div>
{/* 添加附件 */}
<div className="add-file">
<Uploader
isOnlyImg={false}
multiple
name="assetUploadFile"
fileList={this.state.fileList}
url="/workflow/common/uploadFile.do"
onChange={this.uploaderFileChange}
/>
</div>
{/* 确认按钮 */}
<div className="btn-box">
<Button disabled={this.state.sureDisabled} onClick={this.submitSelect}>提交申请</Button>
</div>
{/* 对话框详情 */}
<Dialog
className="asset-detail-dialog"
visible={this.state.chnageInfoShowDialog}
title="资产更换"
footer={[
<Button className="cancel-btn" onClick={() => { this.setState({ chnageInfoShowDialog: false }); }} size="small">取消</Button>,
<Button disabled={this.state.submitDisabled} onClick={this.handleDialogOk} size="small">确定</Button>,
]}
onCancel={() => {
this.setState({
chnageInfoShowDialog: false,
});
}}
>
<div className="changeInfo">
<table>
<thead>
<tr>
<td>资产更换名称</td>
<td>资产描述</td>
<td>归还方式</td>
</tr>
</thead>
<tbody>
<tr>
<td>{this.state.assetData[0] && this.state.assetData[0].assetDescribe.categoryName}</td>
<td>{this.state.assetData[0] && this.state.assetData[0].assetDescribe.feature}</td>
<td>{decodeURIComponent(params.returnTypeName)}</td>
</tr>
</tbody>
</table>
</div>
<div className="changeInfo-now">
<table>
<thead>
<tr>
<td>领用资产名称</td>
<td>资产描述</td>
</tr>
</thead>
<tbody>
<tr>
<td>{this.state.selectAssetInfo[0] && this.state.selectAssetInfo[0].modelDetail}</td>
<td>{this.state.selectAssetInfo[0] && this.state.selectAssetInfo[0].configureMsg}</td>
</tr>
</tbody>
</table>
</div>
{this.state.validate.length ? (<div className="validate-tip">
<Icon name="jinggao-full" className="icon" />
<div className="tip-title">您的申请超出了集团IT资产配置标准,需要审批!</div>
<span>超标原因:</span>
{this.state.validate.map((tip, index) => (
<p>{index + 1}、{tip}</p>
))}
</div>) : ''}
</Dialog>
</div>
);
}
}
export default ChangeSelectBill;
<file_sep>/**
* 设备信息配置
* author 刘玄清
* 2018-2-11
*/
import Form from 'uxcore-form';
import Button from 'uxcore-button';
import Icon from 'uxcore-icon';
import Table from 'uxcore-table';
import Dialog from 'uxcore-dialog';
import Message from 'uxcore-message'; // 全局提醒
import Uploader from 'components/uploader';
import { http } from '../../lib/http';
import './deviceManage.less';
const {
InputFormField,
TextAreaFormField,
SelectFormField,
NumberInputFormField,
} = Form;
const { TextAreaCount } = TextAreaFormField;
class DeviceManage extends React.Component {
constructor(props) {
super(props);
this.state = {
showDialog: false,
dialogTitle: '',
modelNormal: [], // 型号大类list
modelDetail: [], // 型号小类list
categoryType: [], // 所属类别list
workFlowType: [], // 所属流程list
fileList: [],
jsxvalues: {},
edit: false,
id: '', // 编辑的数据id
keyword: '',
editModelDetailId: '', // 编辑时保存型号小类Id
editAmpCategoryId: '', // 编辑时保存amp资产类目Id
};
this.hasSelect = false; // 是否是有效的搜索
}
componentDidMount() {}
// 关键字查询
handleSelect() {
this.hasSelect = true;
const keyword = this.formSelet.getValues().values.keyword;
this.setState({
keyword,
});
}
// 获取型号大类
obtainModelNormal() {
http.get('/newemployee/equipment/getModelNormal.json').then((res) => {
this.setState({
modelNormal: res.map((list) => ({
value: list,
text: list,
})),
});
});
}
// 获取型号小类与amp资产类目
obtainModelDetail() {
http.get('/newemployee/equipment/GetModelDetail.json').then((res) => {
this.setState({
modelDetail: res.map((list) => ({
value: list.modelDetail + '&' + list.modelDetailId + '*' + list.ampCategory + '&' + list.ampCategoryId,
text: list.modelDetail,
})),
});
});
}
// 获取所属类别
obtainCategoryType() {
http.get('/newemployee/equipment/getCategoryType.json?add=true').then((res) => {
this.setState({
categoryType: res.map((list) => ({
value: list.name + '&' + list.id,
text: list.name,
})),
});
});
}
// 获取所属流程
obtainWorkFlowType() {
http.get('/newemployee/equipment/getWorkFlowType.json').then((res) => {
this.setState({
workFlowType: res.map((list) => ({
value: list,
text: list,
})),
});
});
}
// 新增
handleAdd() {
// 清空表单
this.setState({
fileList: [],
jsxvalues: {
ampCategory: '',
},
edit: false,
});
this.form && this.form.resetValues();
// 获取型号大类
this.obtainModelNormal();
// 获取型号小类与amp资产类目
this.obtainModelDetail();
// 获取所属类别
this.obtainCategoryType();
// 获取所属流程
this.obtainWorkFlowType();
this.setState({
showDialog: true,
dialogTitle: '设备新增',
}, () => {
const inputBtn = document.getElementsByClassName('kuma-upload-picker-visual')[0];
const imgTip = document.getElementsByClassName('imgTip')[0];
inputBtn.style.display = 'inline-block';
imgTip.style.display = 'inline-block';
});
}
// form表单值变化
handleFormChange(values) {
const result = values.modelDetail;
const edit = this.state.edit;
if (result && !edit) {
const ampCategoryValue = result.split('*')[1];
const ampCategory = ampCategoryValue.split('&')[0];
this.setState({
jsxvalues: {
ampCategory,
},
});
}
}
// 图片上传 点击删除这个样执行一次
handleImgChange(fileList) {
const inputBtn = document.getElementsByClassName('kuma-upload-picker-visual')[0];
const imgTip = document.getElementsByClassName('imgTip')[0];
if (fileList.filter((list) => list.type !== 'delete').length >= 2) { // 最多上传两张
inputBtn.style.display = 'none';
imgTip.style.display = 'none';
} else {
inputBtn.style.display = 'inline-block';
imgTip.style.display = 'inline-block';
}
const fileListResult = fileList.map((data) => {
if (data.__uploaderId) { // 已经上传过的有__uploaderId
return data;
}
return {
...data,
response: {
data: {
downloadUrl: '/workflow/common/getFile.json?path=' + data.response.newPath, // 放大图
previewUrl: '/workflow/common/getFile.json?path=' + data.response.newSmallPath, // 回显图
},
},
newSmallPath: data.response.newSmallPath,
newPath: data.response.newPath,
};
});
this.setState({
fileList: fileListResult,
});
}
// 图片过滤掉
imgUploaderError() {
Message.error('图片大小不能超过1M', 3);
}
// 删除图片
handleImgDelete(file) {
http.get('/newemployee/equipment/deleteImg.json?newPath=' + file.newPath + '&newSmallPath=' + file.newSmallPath).then((res) => {
if (!res.hasError) {
Message.success(res.content, 2);
} else {
Message.error(res.content, 2);
}
});
}
// 编辑
async tableEdit(rowData) {
await this.form && this.form.resetValues();
await this.setState({
showDialog: true,
dialogTitle: '设备编辑',
edit: true,
id: rowData.id,
fileList: [],
});
// 获取型号大类
this.obtainModelNormal();
// 获取所属类别
this.obtainCategoryType();
// 获取所属流程
this.obtainWorkFlowType();
// 型号小类不可编辑
http.get('/newemployee/equipment/getOne.json?id=' + rowData.id).then((res) => {
const fileList = [{
newPath: res.bigImgPath1,
newSmallPath: res.smallImgPath1,
response: {
previewUrl: '/workflow/common/getFile.json?path=' + res.smallImgPath1, // 显示的缩略图
name: '',
downloadUrl: '/workflow/common/getFile.json?path=' + res.bigImgPath1, // 点击放大的图片
},
}];
if (res.smallImgPath2) {
fileList.push({
newPath: res.bigImgPath2,
newSmallPath: res.smallImgPath2,
response: {
previewUrl: '/workflow/common/getFile.json?path=' + res.smallImgPath2,
name: '',
downloadUrl: '/workflow/common/getFile.json?path=' + res.bigImgPath2,
},
});
}
const inputBtn = document.getElementsByClassName('kuma-upload-picker-visual')[0];
const imgTip = document.getElementsByClassName('imgTip')[0];
// 如果两张图片,隐藏上传按钮
if (fileList.length >= 2) {
inputBtn.style.display = 'none';
imgTip.style.display = 'none';
} else {
inputBtn.style.display = 'inline-block';
imgTip.style.display = 'inline-block';
}
this.setState({
jsxvalues: {
modelNormal: res.modelNormal,
modelDetail: res.modelDetail,
ampCategory: res.ampCategory,
categoryType: res.categoryType + '&' + res.categoryTypeId,
workFlowType: res.workFlowType,
sortOrder: res.sortOrder,
configureMsg: res.configureMsg,
},
fileList,
editModelDetailId: res.modelDetailId,
editAmpCategoryId: res.ampCategoryId,
});
});
}
// 删除
tableDelete(rowData) {
const me = this;
Dialog.confirm({
title: '确定删除吗?',
content: '目标删除后将不可恢复,如有子目标将会被同时删除!',
onOk() {
http.get('/newemployee/equipment/deleteEquipmentConfigure.json?id=' + rowData.id).then((res) => {
if (res.hasError) {
Message.error(res.content, 3);
} else {
Message.success(res.content, 2);
me.table.fetchData();
}
});
},
onCancel() {},
});
}
// 对话框确认
deviceConfirm() {
const inputValue = this.form.getValues().values;
const modelNormal = inputValue.modelNormal; // 型号大类
const modelDetail = inputValue.modelDetail; // 型号小类
const categoryType = inputValue.categoryType; // 所属类别
const workFlowType = inputValue.workFlowType; // 所属流程
const sortOrder = inputValue.sortOrder; // 排序
const configureMsg = inputValue.configureMsg; // 配置信息
const imgInputList = this.state.fileList.filter((list) => list.type !== 'delete'); // 上传的图片
if (!modelNormal) {
Message.info('型号大类必填!');
return;
}
if (!modelDetail) {
Message.info('型号小类必填!');
return;
}
if (!categoryType) {
Message.info('所属类别必填!');
return;
}
if (!workFlowType) {
Message.info('所属流程必填!');
return;
}
if (!sortOrder) {
Message.info('排序必填!');
return;
}
if (!configureMsg) {
Message.info('配置信息必填!');
return;
}
if (configureMsg && configureMsg.length > 50) {
Message.info('配置信息仅限50个字符!');
return;
}
if (!imgInputList.length) {
Message.info('请上传图片!');
return;
}
const edit = this.state.edit;
if (edit) {
const ampCategoryId = this.state.editAmpCategoryId;
const modelDetailId = this.state.editModelDetailId;
const jsonData = {
id: this.state.id,
modelNormal,
categoryType: categoryType.split('&')[0],
categoryTypeId: categoryType.split('&')[1],
modelDetailId,
ampCategoryId,
workFlowType,
sortOrder,
configureMsg,
bigImgPath1: imgInputList[0].newPath,
smallImgPath1: imgInputList[0].newSmallPath,
bigImgPath2: imgInputList[1] ? imgInputList[1].newPath : '',
smallImgPath2: imgInputList[1] ? imgInputList[1].newSmallPath : '',
};
http.get('/newemployee/equipment/addOrUpdateEquipmentConfigure.json?jsonData=' + JSON.stringify(jsonData)).then((res) => {
if (res.hasError) {
Message.error(res.content, 3);
} else {
Message.success(res.content, 2);
this.setState({
showDialog: false,
});
this.table.fetchData();
}
});
} else {
const jsonData = {
modelNormal,
modelDetail: modelDetail.split('*')[0].split('&')[0], // 型号小类名称
modelDetailId: modelDetail.split('*')[0].split('&')[1], // 型号小类Id
ampCategory: modelDetail.split('*')[1].split('&')[0], // amp资产类目
ampCategoryId: modelDetail.split('*')[1].split('&')[1], // amp资产类目Id
categoryType: categoryType.split('&')[0], // 所属类别
categoryTypeId: categoryType.split('&')[1], // 所属类别Id
workFlowType,
sortOrder,
configureMsg,
bigImgPath1: imgInputList[0].newPath,
smallImgPath1: imgInputList[0].newSmallPath,
bigImgPath2: imgInputList[1] ? imgInputList[1].newPath : '',
smallImgPath2: imgInputList[1] ? imgInputList[1].newSmallPath : '',
};
http.get('/newemployee/equipment/addOrUpdateEquipmentConfigure.json?jsonData=' + JSON.stringify(jsonData)).then((res) => {
if (res.hasError) {
Message.error(res.content, 3);
} else {
Message.success(res.content, 2);
this.setState({
showDialog: false,
});
this.table.fetchData();
}
});
}
}
// 编辑或新增
deviceManage() {
return (
<Dialog
title={this.state.dialogTitle}
className="device-dialog"
visible={this.state.showDialog}
onCancel={() => {
this.setState({
showDialog: false,
jsxvalues: null,
});
}}
onOk={this.deviceConfirm.bind(this)}
>
<Form
ref={(c) => { this.form = c; }}
jsxvalues={this.state.jsxvalues}
jsxonChange={(values) => { this.handleFormChange(values); }}
>
<SelectFormField
jsxlabel="型号大类"
jsxname="modelNormal"
jsxdata={this.state.modelNormal}
/>
{!this.state.edit ? <SelectFormField
jsxlabel="型号小类"
jsxname="modelDetail"
jsxdata={this.state.modelDetail}
/> : ''}
{this.state.edit ? <InputFormField
jsxlabel="型号小类"
jsxname="modelDetail"
jsxdisabled
/> : ''}
<InputFormField
jsxlabel="资产类目"
jsxname="ampCategory"
jsxdisabled
/>
<SelectFormField
jsxlabel="所属类别"
jsxname="categoryType"
jsxdata={this.state.categoryType}
/>
<SelectFormField
jsxlabel="所属流程"
jsxname="workFlowType"
jsxdata={this.state.workFlowType}
/>
<NumberInputFormField jsxname="sortOrder" jsxlabel="排序" />
<TextAreaFormField jsxname="configureMsg"
jsxlabel="配置信息"
jsxplaceholder="仅限50个字符"
jsxrules={[
{ validator(value) { return value ? value.length <= 50 : true; }, errMsg: '仅限50个字符' },
]}
>
<TextAreaCount total={50} />
</TextAreaFormField>
</Form>
<div className="imgUploader">
<div className="imgLabel">图片</div>
<Uploader
isOnlyImg
isVisual
sizeLimit="1mb"
fileList={this.state.fileList}
accept="jpg,jpeg,png,gif,webp,bmp"
name="assetUploadFile"
url="/newemployee/equipment/upLoadImg.json"
onCancel={this.handleImgDelete.bind(this)}
onChange={this.handleImgChange.bind(this)}
onqueuefilefiltered={this.imgUploaderError}
/>
<div className="imgTip">建议尺寸500 x 500px<p>图片大小不超过1M</p></div>
</div>
</Dialog>
);
}
// table 请求之前
tableBeforeFetch(data) {
if (this.hasSelect) { // 查询返回第一页的数据
data.currentPage = 1;
}
return data;
}
// 表格返回数据处理
tableBackData(tableData) {
this.hasSelect = false; // 数据返回后恢复为没有查询状态
return tableData;
}
render() {
const me = this;
const columns = [
{
dataKey: 'modelNormal',
title: '型号大类',
width: 165,
},
{
dataKey: 'modelDetail',
title: '型号小类',
width: 165,
},
{
dataKey: 'ampCategory',
title: '资产类目',
width: 165,
},
{
dataKey: 'categoryType',
title: '所属类别',
width: 100,
},
{
dataKey: 'workFlowType',
title: '所属流程',
width: 100,
},
{
dataKey: 'sortOrder',
title: '排序',
width: 100,
},
{
dataKey: 'configureMsg',
title: '配置信息',
width: 195,
},
{
dataKey: 'action',
title: '操作',
width: 150,
type: 'action',
actions: [
{
title: '编辑',
callback: me.tableEdit.bind(this),
},
{
title: '删除',
callback: me.tableDelete.bind(this),
},
],
},
];
const renderTable = {
doubleClickToEdit: false,
className: 'table-container',
fetchUrl: '/newemployee/equipment/listAll.json',
jsxcolumns: columns,
beforeFetch: me.tableBeforeFetch.bind(me),
fetchParams: {
keyword: me.state.keyword,
},
processData: me.tableBackData.bind(this),
};
return (
<div className="page-deviceManage">
<div className="page-inner">
<div className="title">
<span>领用/借用设备维护</span>
</div>
<div className="select-area">
<Form
ref={(c) => { this.formSelet = c; }}
className="select-from"
>
<InputFormField jsxname="keyword" jsxlabel="关键字查询:" jsxplaceholder="" />
</Form>
<Button className="select-btn" onClick={me.handleSelect.bind(me)}><Icon name="sousuo" /></Button>
<div className="space" />
<Button type="outline" className="addBtn" onClick={me.handleAdd.bind(me)}>新增</Button>
</div>
<div className="table-box">
<Table ref={(c) => { this.table = c; }} {...renderTable} />
</div>
{this.deviceManage()}
</div>
</div>
);
}
}
// 下拉列表显示黑色 和value对应
// 编辑和新增是否用一个
export default DeviceManage;
<file_sep>import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Borrow from './borrow';
ReactDOM.render(
<Borrow />,
document.getElementById('borrow'),
);
<file_sep>import { http } from '../../lib/http';
class AssetDescribe extends React.Component {
constructor(props) {
super(props);
this.state = {
imgPath: '',
};
}
componentDidMount() {
http.get('/linkage/assetCategory/selectReource.json?id=' + this.props.data.categoryIdString).then((res) => {
this.setState({
imgPath: res.picList[0] && res.picList[0].path,
});
});
}
render() {
const { data } = this.props;
const { imgPath } = this.state;
return (
<div className="assetDescribe-wrapper">
<div className="img-content"><img alt="暂无图片" src={'/workflow/common/getFile.json?path=' + imgPath} /></div>
<div className="asset-infomation">
<p>名 称:<span className="asset-name"><a target="_blank" href={'/workflow/myassets/detail.htm?resource_id=' + data.id}>{data.categoryName}</a></span></p>
<p>特 征:<span>{data.feature}</span></p>
<p>使用人:<span className="asset-user"><a target="_blank" href={'https://work.alibaba-inc.com/u/' + data.user}>{data.userName}</a></span></p>
</div>
</div>
);
}
}
export default AssetDescribe;
<file_sep>/**
* 领用地点维护
* author 刘玄清
* 2018-2-1
* 0.1.9
*
*
*/
import Form from 'uxcore-form';
import Button from 'uxcore-button';
import Icon from 'uxcore-icon';
import Table from 'uxcore-table';
import Dialog from 'uxcore-dialog';
import Select from 'uxcore-select2';
import Message from 'uxcore-message';
import { http } from '../../lib/http';
import './useAddress.less';
const { InputFormField } = Form;
const { Option } = Select;
class UseAddress extends React.Component {
constructor(props) {
super(props);
this.state = {
addressDialog: false, // 新增领用地弹窗
editAddressDialog: false, // 领用地编辑弹窗
cityCollection: {}, // 搜索获取城市集合
parkCollection: {}, // 搜搜获取园区集合
cityValue: '', // 选择的城市
cityValueCode: '',
parkValue: '', // 选择的园区
parkValueCode: '', //
selectKeyWord: '', // 查询关键字
newCityValue: '', // 新增城市选中
newParkValue: '', // 新增添加园区
newLocationValue: '', // 新增添加地点
newParkCollection: {}, // 新增园区options
newLocationCollection: {}, // 新增库房options
newRegionValue: '', // 新增选择的区域
newRegionCollection: [], // 新增所属区域
newHouseCollection: [], // 新增关联库房
newHouseValue: [], //
editData: {}, // 编辑数据
editId: '',
editSuper: false, // 是否有编辑权限
};
this.cityMap = new Map(); // cityName codeValue
this.parkMap = new Map(); // parkName codeValue
this.locationMap = new Map(); // location
this.newParkCloseEl = null; //
this.newLocationCloseEl = null;//
this.newCityCloseEl = null; //
this.newHouseMap = new Map(); //
this.hasSelect = false; // 是否是有效的搜索
this.selectCity; // 保存选择的城市
this.selectPark; // 保存选择的园区
this.selectKeyword; // 保存输入的关键字
this.oldLocationValue;// 保存旧的
}
componentDidMount() {
const me = this;
http('/linkage/locationStoreMap/getCity.json').then((res) => {
if (!res.hasError) {
me.setState({
cityCollection: res,
});
for (let i = 0; i < Object.keys(res).length; i++) {
this.cityMap.set(res[Object.keys(res)[i]], Object.keys(res)[i]);
}
}
});
// 隐藏搜搜园区的icon
this.selectParkEl = document.getElementsByClassName('select2-park')[0].getElementsByClassName('kuma-select2-selection__clear')[0];
this.selectParkEl.style.display = 'none'; // 因为有value,初始化的时候隐藏close按钮
}
// 查询,下拉城市选择
handleCityChange(value) {
const me = this;
me.selectParkEl.style.display = 'none';
if (value) { // 有值时
me.setState({
cityValue: value,
});
http('/linkage/locationStoreMap/getPark.json?cityCode=' + me.cityMap.get(value)).then((res) => {
if (!res.hasError) {
me.setState({
parkCollection: res,
parkValue: '', // 清空园区
});
for (let i = 0; i < Object.keys(res).length; i++) {
me.parkMap.set(res[Object.keys(res)[i]], Object.keys(res)[i]);
}
}
});
} else {
me.setState({
parkValue: '',
parkCollection: {},
cityValue: '',
});
}
}
// 查询,下拉园区选择
handleParkChange(value) {
if (value) {
this.selectParkEl.style.display = 'inline-block';
this.setState({
parkValue: value,
});
} else {
this.selectParkEl.style.display = 'none';
this.setState({
parkValue: '',
});
}
}
// 查询
handleSelect() {
const formData = this.form_select_keywords.getValues().values;
const city = this.cityMap.get(this.state.cityValue);
const park = this.parkMap.get(this.state.parkValue);
// 判断是否是有效的搜索 1 都为空无效, 两次三个值都不变
// 如果是有效的搜索,页数置位1
// 这里最好别用state,state改变会导致页面渲染一次
// 有效的搜索table会刷新
if (this.selectCity === city && this.selectPark === park && this.selectKeyword === formData.keyword) { // 无效的搜索
this.hasSelect = false;
} else {
this.hasSelect = true;
}
this.setState({
selectKeyWord: formData.keyword,
cityValueCode: city,
parkValueCode: park,
});
}
// 添加按钮
handleAdd() {
const me = this;
// 清空描述输入框的值
this.form_address_dis && this.form_address_dis.setValues({
description: '',
});
// 清空选中数据
me.setState({
newCityValue: '',
newParkValue: '',
newLocationValue: '',
newRegionValue: '',
newHouseValue: [],
newParkCollection: {},
newLocationCollection: {},
addressDialog: true,
});
http('/linkage/locationStoreMap/getCity.json').then((res) => {
if (!res.hasError) {
me.setState({
cityCollection: res,
});
for (let i = 0; i < Object.keys(res).length; i++) {
me.cityMap.set(res[Object.keys(res)[i]], Object.keys(res)[i]);
}
}
});
// // 获取所属区域
http('/linkage/locationStoreMap/getRegion.json').then((res) => {
if (!res.hasError) {
me.setState({
newRegionCollection: res,
});
}
});
// // 获取库房
http('/linkage/locationStoreMap/getStoreHouse.json').then((res) => {
if (!res.hasError) {
me.setState({
newHouseCollection: res.slice(0, 10),
});
res.map((item) => {
me.newHouseMap.set(item.name, item.id);
return '';
});
}
});
me.setState({
addressDialog: true,
}, () => {
me.newParkCloseEl = document.getElementsByClassName('new-park-box')[0].getElementsByClassName('kuma-select2-selection__clear')[0];
me.newParkCloseEl.style.display = 'none';
me.newLocationCloseEl = document.getElementsByClassName('new-location-box')[0].getElementsByClassName('kuma-select2-selection__clear')[0];
me.newLocationCloseEl.style.display = 'none';
me.newCityCloseEl = document.getElementsByClassName('new-city-box')[0].getElementsByClassName('kuma-select2-selection__clear')[0];
me.newCityCloseEl.style.display = 'none';
me.newRagionCloseEl = document.getElementsByClassName('new-area-box')[0].getElementsByClassName('kuma-select2-selection__clear')[0];
me.newRagionCloseEl.style.display = 'none';
});
}
// 添加城市改变
handleNewCity(value) {
const me = this;
if (value) {
me.setState({
newCityValue: value,
newParkValue: '',
newLocationValue: '', // 改变的时候先清空下面的
newLocationCollection: {},
});
if (me.newCityCloseEl) {
me.newCityCloseEl.style.display = 'inline';
}
http('/linkage/locationStoreMap/getPark.json?cityCode=' + me.cityMap.get(value)).then((res) => {
if (res.hasError) { // 输入有误
me.setState({
newParkCollection: {},
newLocationCollection: {},
});
} else {
for (let i = 0; i < Object.keys(res).length; i++) {
me.parkMap.set(res[Object.keys(res)[i]], Object.keys(res)[i]);
}
me.setState({
newParkCollection: res,
});
}
});
http('/linkage/locationStoreMap/getStoreHouse.json?city=' + value).then((res) => {
if (!res.hasError) { // 有返回的库房
me.setState({
newHouseCollection: res,
});
} else {
me.setState({
newHouseCollection: [],
newHouseValue: [],
});
}
});
} else { // 没有输入值
me.newCityCloseEl.style.display = 'none';
me.newParkCloseEl.style.display = 'none';
me.newLocationCloseEl.style.display = 'none';
// 清空
me.setState({
newParkCollection: {},
newLocationCollection: {},
newParkValue: '',
newLocationValue: '',
newCityValue: '',
newHouseValue: [],
newHouseCollection: [],
});
}
}
// 添加园区改变
handleNewPark(value) {
const me = this;
if (value) {
me.setState({
newParkValue: value,
newLocationValue: '',
});
// 获取地点
http('/linkage/locationStoreMap/getLocation.json?cityCode=' +
me.cityMap.get(me.state.newCityValue) + '&parkCode=' +
me.parkMap.get(value)).then((res) => {
if (res.hasError) { // 可以输入
} else {
for (let i = 0; i < Object.keys(res).length; i++) {
me.locationMap.set(res[Object.keys(res)[i]], Object.keys(res)[i]);
}
me.setState({
newLocationCollection: res,
newLocationValue: '',
});
}
});
if (me.newParkCloseEl) {
me.newParkCloseEl.style.display = 'inline-block';
}
} else {
me.newParkCloseEl.style.display = 'none';
me.newLocationCloseEl.style.display = 'none';
me.setState({
newLocationCollection: {},
newParkValue: '',
newLocationValue: '',
});
}
}
// 新增地点改变
handleNewLocation(value) {
const me = this;
if (value) {
if (me.newLocationCloseEl) {
me.newLocationCloseEl.style.display = 'inline-block';
}
this.setState({
newLocationValue: value,
});
} else {
if (me.newLocationCloseEl) {
me.newLocationCloseEl.style.display = 'none';
}
this.setState({
newLocationValue: '',
});
}
}
// 关联库房选择
handleNewHouse(value) {
this.setState({
newHouseValue: value,
});
}
// 所属库房改变
handleNewRegion(value) {
this.setState({
newRegionValue: value,
});
}
// 新增领用地点提交
createAddress() {
const me = this;
const city = this.state.newCityValue;
const park = this.state.newParkValue;
const location = this.state.newLocationValue;
const regionId = this.state.newRegionValue.split(',')[0];
const regionName = this.state.newRegionValue.split(',')[1];
const description = this.form_address_dis.getValues().values.description;
const house = this.state.newHouseValue;
if (!city) {
Message.error('城市必填!');
return;
}
if (!park) {
Message.error('园区必填!');
return;
}
if (!location) {
Message.error('领用地点必填!');
return;
}
if (!regionName) {
Message.error('所属区域必填!');
return;
}
// // 拼接json字符串
const cityCode = this.cityMap.get(city);
const parkCode = this.parkMap.get(park);
const locationCode = this.locationMap.get(location);
const storeHouseId = house.map((item) => me.newHouseMap.get(item)).join(',');
const storeHouseName = house.join(',');
const reqData = {
city,
cityCode,
park,
parkCode,
location,
locationCode,
regionId,
regionName,
description,
storeHouseName,
storeHouseId,
};
const strData = JSON.stringify(reqData, (key, value) => {
if (key === 'storeHouseName') {
value = encodeURIComponent(value);
}
return value;
});
http('/linkage/locationStoreMap/addOrUpdateLocation.json?locationMapping=' + strData).then((res) => {
if (res.hasError) {
Message.error(res.content, 3);
} else {
Message.success('新增成功!');
// 关闭diaog
this.setState({
addressDialog: false,
});
// 更新表格
this.table.fetchData();
http('/linkage/locationStoreMap/getCity.json').then((resCity) => {
if (!resCity.hasError) {
me.setState({
cityCollection: resCity,
});
for (let i = 0; i < Object.keys(resCity).length; i++) {
me.cityMap.set(resCity[Object.keys(resCity)[i]], Object.keys(resCity)[i]);
}
}
});
}
});
}
// 表格返回数据处理
tableBackData(tableData) {
this.hasSelect = false; // 数据返回后恢复为无效值
return {
...tableData,
data: tableData.data.map((item) => ({
...item,
storeHouseName: item.storeHouseName.split(',').map((name) => (<div title={name} className="table-house-item">{name}</div>)),
})),
};
}
// table编辑
tableEdit(tableData) {
const me = this;
me.setState({
editId: tableData.id,
});
// 判断地点是否有编辑权限
http.get('/linkage/locationStoreMap/canChange.json').then((res) => {
this.setState({
editSuper: res.super,
});
});
// 获取初始园区
http('/linkage/locationStoreMap/getPark.json?cityCode=' + tableData.cityCode).then((res) => {
if (!res.hasError) {
for (let i = 0; i < Object.keys(res).length; i++) {
me.parkMap.set(res[Object.keys(res)[i]], Object.keys(res)[i]);
}
me.setState({
newParkCollection: res,
});
}
});
// 获取初始领用地点
http('/linkage/locationStoreMap/getLocation.json?cityCode=' + tableData.cityCode + '&parkCode=' + tableData.parkCode).then((res) => {
if (!res.hasError) {
for (let i = 0; i < Object.keys(res).length; i++) {
me.locationMap.set(res[Object.keys(res)[i]], Object.keys(res)[i]);
}
me.setState({
newLocationCollection: res,
});
}
});
// 获取所属区域
http('/linkage/locationStoreMap/getRegion.json').then((res) => {
if (!res.hasError) {
me.setState({
newRegionCollection: res,
});
}
});
// 获取关联库房
http('/linkage/locationStoreMap/getStoreHouse.json').then((res) => {
if (!res.hasError) {
res.map((item) => {
me.newHouseMap.set(item.name, item.id);
return '';
});
me.setState({
newHouseCollection: res,
});
}
});
http('/linkage/locationStoreMap/getLocationById.json?id=' + tableData.id).then((res) => {
if (!res.hasError) {
this.oldLocationValue = res.location;
const storeHouseNameReq = res.storeHouseName;
const storeHouseNameReslut = storeHouseNameReq && storeHouseNameReq.split(',');
// 所属区域
const ragionReslut = res.regionId + ',' + res.regionName;
// 把旧的storeHouseName 和 storeHouseId 匹配上
res.storeHouseName.split(',').map((storeHouse, index) => {
me.newHouseMap.set(storeHouse, res.storeHouseId.split(',')[index]);
return '';
});
this.setState({
editAddressDialog: true,
editData: res,
newCityValue: res.city,
newParkValue: res.park,
newLocationValue: res.location,
newRegionValue: ragionReslut,
newHouseValue: storeHouseNameReslut,
}, () => {
this.form_address_dis_edit.setValues({
description: res.description,
});
});
}
});
}
// 编辑提交
editeAddress() {
const me = this;
const city = this.state.newCityValue;
const park = this.state.newParkValue;
const location = this.state.newLocationValue;
const regionId = this.state.newRegionValue.split(',')[0];
const regionName = this.state.newRegionValue.split(',')[1];
const description = this.form_address_dis_edit.getValues().values.description;
const house = this.state.newHouseValue;
const cityCode = this.cityMap.get(city);
const parkCode = this.parkMap.get(park);
const locationCode = this.locationMap.get(location) || this.locationMap.get(this.oldLocationValue);
const storeHouseId = house.map((item) => me.newHouseMap.get(item)).join(',');
const storeHouseName = house.join(',');
const reqData = {
city,
cityCode,
park,
parkCode,
location,
locationCode,
regionId,
regionName,
description,
storeHouseName,
storeHouseId,
edit: true, // 编辑
id: me.state.editId,
};
const strData = JSON.stringify(reqData, (key, value) => {
if (key === 'storeHouseName') {
value = encodeURIComponent(value); // 处理#传不过去
}
return value;
});
http('/linkage/locationStoreMap/addOrUpdateLocation.json?locationMapping=' + strData).then((res) => {
if (res.hasError) {
Message.error(res.content, 3);
} else {
Message.success(res.content, 2);
this.table.fetchData();
me.setState({
editAddressDialog: false,
});
}
});
}
// table 删除
tableDelete(tableData) {
const me = this;
Dialog.confirm({
title: '确定删除吗?',
content: '目标删除后将不可恢复,如有子目标将会被同时删除!',
onOk() {
// 执行删除逻辑
http('/linkage/locationStoreMap/DeleteLocation.json?id=' + tableData.id + '&storeHouseId=' + tableData.storeHouseId).then((res) => {
if (!res.hasError) { // 删除成功
Message.success('删除成功!');
me.table.fetchData();
} else {
Message.error(res.content, 3);
}
});
// 刷新表格数据
},
onCancel() {},
});
}
// // table 请求之前
tableBeforeFetch(data) {
if (this.hasSelect) {
data.currentPage = 1;
}
return data;
}
render() {
const me = this;
const cityOptionItem = me.state.cityCollection;
const parkOptionItem = me.state.parkCollection;
const newParkOptionTtem = me.state.newParkCollection;
const newLocationOptionItem = me.state.newLocationCollection;
const newRegionOptionItem = me.state.newRegionCollection;
const newHouseOptionItem = me.state.newHouseCollection;
// console.log(JSON.parse(newRegionOptionItem))
// 搜索城市options
const selectCityOptions = Object.keys(cityOptionItem).map((item) => <Option key={cityOptionItem[item]}>{cityOptionItem[item]}</Option>);
// 搜索园区options
const selectParkOptions = Object.keys(parkOptionItem).map((item) => <Option key={parkOptionItem[item]}>{parkOptionItem[item]}</Option>);
// 新增园区options
const newParkOptions = Object.keys(newParkOptionTtem).map((item) => <Option key={newParkOptionTtem[item]}>{newParkOptionTtem[item]}</Option>);
// 新增库房options
const newLocationOptions = Object.keys(newLocationOptionItem).map((item) => <Option key={newLocationOptionItem[item]}>{newLocationOptionItem[item]}</Option>);
// 新增区域options
const newRegionOptions = newRegionOptionItem.length && newRegionOptionItem.map((item) => <Option key={item.id + ',' + item.name}>{item.name}</Option>);
// 新增关联库房options
const newHouseOptions = newHouseOptionItem.length && newHouseOptionItem.map((item) => (<Option key={item.name}>{item.name}</Option>));
// 表格表头
const columns = [
{
dataKey: 'city',
title: '城市',
width: 150,
},
{
dataKey: 'park',
title: '园区',
width: 150,
},
{
dataKey: 'location',
title: '位置',
width: 150,
},
{
dataKey: 'regionName',
title: '区域',
width: 150,
},
{
dataKey: 'storeHouseName',
title: '关联库房',
width: 390,
},
{
dataKey: 'action',
title: '操作',
width: 150,
type: 'action',
actions: [
{
title: '编辑',
callback: me.tableEdit.bind(this),
},
{
title: '删除',
callback: me.tableDelete.bind(this),
render: (title, rowData) => {
if (rowData.isDeleted === 'n') { // 没有删除
return title;
}
return false;
},
},
],
},
];
const renderProps = {
fetchUrl: '/linkage/locationStoreMap/getLocationList.json',
jsxcolumns: columns,
showPager: true,
showPagerTotal: true,
beforeFetch: me.tableBeforeFetch.bind(me),
fetchParams: { // 请求数据参数
cityCode: me.state.cityValueCode,
parkCode: me.state.parkValueCode,
keyword: me.state.selectKeyWord,
// [me.hasSelect ? 'currentPage' : '']: 1,
},
// onPagerChange: me.tablePageChange.bind(me),
processData: me.tableBackData.bind(this),
className: 'table-container',
doubleClickToEdit: false,
};
return (
<div className="useAddress-container">
<div className="title">
<span>领用地点维护</span>
</div>
<div className="select-box">
<div className="select">
<div className="city-label">城市:</div>
<Select allowClear className="select2-city" onChange={me.handleCityChange.bind(me)} dropdownClassName="kuma-select2-selected-has-icon">
{selectCityOptions}
</Select>
<div className="city-label">园区:</div>
<Select allowClear value={me.state.parkValue} onChange={me.handleParkChange.bind(me)} className="select2-park" dropdownClassName="kuma-select2-selected-has-icon">
{selectParkOptions}
</Select>
<div className="keyword-label">关键字:</div>
<Form ref={(c) => { this.form_select_keywords = c; }}>
<InputFormField jsxname="keyword" />
</Form>
</div>
<Button className="select-btn" onClick={me.handleSelect.bind(me)}><Icon name="sousuo" /></Button>
<div className="space" />
<Button type="outline" className="addBtn" onClick={me.handleAdd.bind(me)}>新增</Button>
</div>
<div className="table-box">
<Table ref={(c) => { this.table = c; }} {...renderProps} />
</div>
{/* 添加领用地弹窗 */}
<Dialog
title="领用地点新增"
className="add-address"
visible={me.state.addressDialog}
onCancel={() => {
this.setState({
addressDialog: false,
});
}}
onOk={me.createAddress.bind(me)}
>
<div className="new-city-box">
<span className="city-label">城市:</span>
<Select value={me.state.newCityValue} combobox allowClear style={{ width: 200 }} className="new-city" onChange={me.handleNewCity.bind(me)} dropdownClassName="kuma-select2-selected-has-icon">
{selectCityOptions}
</Select>
</div>
<div className="new-park-box">
<span className="city-label">园区:</span>
<Select value={me.state.newParkValue} combobox allowClear style={{ width: 200 }} className="new-park" onChange={me.handleNewPark.bind(me)} dropdownClassName="kuma-select2-selected-has-icon">
{newParkOptions}
</Select>
</div>
<div className="new-location-box">
<span className="city-label">领用地点:</span>
<Select value={me.state.newLocationValue} combobox allowClear style={{ width: 200 }} className="new-location" onChange={me.handleNewLocation.bind(me)} dropdownClassName="kuma-select2-selected-has-icon">
{newLocationOptions}
</Select>
</div>
<div className="new-area-box">
<span className="city-label">所属区域:</span>
<Select value={me.state.newRegionValue} allowClear style={{ width: 200 }} showSearch={false} className="new-region" onChange={me.handleNewRegion.bind(me)} dropdownClassName="kuma-select2-selected-has-icon">
{newRegionOptions}
</Select>
</div>
<div className="new-dis-box">
<Form ref={(c) => { this.form_address_dis = c; }}>
<InputFormField jsxname="description" jsxlabel="描述:" />
</Form>
</div>
<div className="new-house-box">
<span className="city-label">关联库房:</span>
<Select value={me.state.newHouseValue} multiple showSearch={false} style={{ width: 200 }} className="new-house" onChange={me.handleNewHouse.bind(me)} dropdownClassName="kuma-select2-selected-has-icon">
{newHouseOptions}
</Select>
</div>
</Dialog>
{/* 领用地点编辑 */}
<Dialog title="领用地点编辑"
className="edit-address"
visible={me.state.editAddressDialog}
onCancel={() => {
this.setState({
editAddressDialog: false,
});
}}
onOk={me.editeAddress.bind(me)}
>
<div className="new-city-box">
<span className="city-label">城市:</span>
<Select value={me.state.newCityValue} showSearch={false} style={{ width: 200 }} className="new-city" onChange={me.handleNewCity.bind(me)} dropdownClassName="kuma-select2-selected-has-icon">
{selectCityOptions}
</Select>
</div>
<div className="new-park-box">
<span className="city-label">园区:</span>
<Select showSearch={false} value={me.state.newParkValue} style={{ width: 200 }} className="new-park" onChange={me.handleNewPark.bind(me)} dropdownClassName="kuma-select2-selected-has-icon">
{newParkOptions}
</Select>
</div>
<div className="new-location-box">
<span className="city-label">领用地点:</span>
<Select combobox={this.state.editSuper} value={me.state.newLocationValue} style={{ width: 200 }} className="new-location" onChange={me.handleNewLocation.bind(me)} dropdownClassName="kuma-select2-selected-has-icon">
{newLocationOptions}
</Select>
</div>
<div className="new-area-box">
<span className="city-label">所属区域:</span>
<Select value={me.state.newRegionValue} style={{ width: 200 }} showSearch={false} className="new-region" onChange={me.handleNewRegion.bind(me)} dropdownClassName="kuma-select2-selected-has-icon">
{newRegionOptions}
</Select>
</div>
<div className="new-dis-box">
<Form ref={(c) => { this.form_address_dis_edit = c; }}>
<InputFormField jsxname="description" jsxlabel="描述:" />
</Form>
</div>
<div className="new-house-box">
<span className="city-label">关联库房:</span>
<Select showSearch={false} value={me.state.newHouseValue} multiple style={{ width: 200 }} className="new-house" onChange={me.handleNewHouse.bind(me)} dropdownClassName="kuma-select2-selected-has-icon">
{newHouseOptions}
</Select>
</div>
</Dialog>
</div>
);
}
}
export default UseAddress;
/**
* Table
* 样式覆盖去掉滚动条
* 样式指定最小高度
*/
// "indent": ["error","tab"], 使用tab缩进
// SelectFormField combobox可输入, 输入的时候获取参数
// 新增关联库房 value值为空,鼠标悬浮options会有警告提示
// https://www.cnblogs.com/smalldark/p/6496675.html
// 分页,搜索数据分页要置为第一页
<file_sep>import * as React from 'react';
import * as ReactDOM from 'react-dom';
import ViewTask from './viewTask';
ReactDOM.render(
<ViewTask />,
document.getElementById('ViewTask'),
);
| e0db32100a0ac381a20146f0ba634ed63b64b53c | [
"JavaScript"
] | 27 | JavaScript | lxqsdau/it-asset-pc | 9c0e2d8a906b16cb37aae3a5ff936b892cd72080 | bd5cd242b538848960a7c03558a1f522678cef82 | |
refs/heads/main | <file_sep>document.onload = onloadfunction();
function onloadfunction() {
console.log("Loaded!");
const promise = fetch("http://localhost:3000/hello")
.then((res) => {
console.log(res);
return res.json();
})
.then((res) => {
const resTwo = JSON.stringify(res);
$("#response").text(resTwo);
});
console.log(promise);
}
var userName = $("name").val();
var Intrests = $("intrests").val();
// const testImport = () => {
// console.log("test import");
// };
// export default testImport;
<file_sep>// import express for backend API
const express = require("express");
// import cors so people can talk rom other computers
var cors = require("cors");
// init your backend
const app = express();
// make use of the CORS
app.use(cors());
// specify port number
const port = 3000;
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.get("/hello", (req, res) => {
res.send({ troy: "neild" });
});
// turn on the server with a given port, and a function to
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
| a833b36427901f3a5b1d3c0786223d3b631f0b28 | [
"JavaScript"
] | 2 | JavaScript | MyCabbages123/friendship | 027e0ac490a71a08ad80896d8abaa44c67500162 | e134841ef6a5f95ef4a28ff56e6be3050d8d4830 | |
refs/heads/master | <file_sep>const enemyImage = new Image();
enemyImage.src = './images/0_Golem_Walking_000.png';
enemyImage.id = 'enemy';
class Enemy {
constructor(game, x, y) {
this.game = game;
this.x = x;
this.y = y;
this.enemyAlive = true;
}
runLogic() {
this.x = this.x - 0.7;
}
checkIntersection(element) {
//check if enemy has overlapping coordinates with player
return (
element.x >= this.x &&
element.x <= this.x + 50 &&
element.y >= this.y &&
element.y - 50 <= this.y
);
}
paint() {
const context = this.game.context;
context.save();
context.drawImage(enemyImage, game.enemy.x, game.enemy.y, 100, 100);
context.restore();
}
}
<file_sep>const wallMap = [
[
0,
0,
0,
0,
'leftUpperCorner',
'middle',
'middle',
'middle',
'rightUpperCorner',
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[0, 0, 0, 0, 'sides', 1, 1, 1, 'sides', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 'sides', 'B', 1, 1, 'sides', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[
0,
0,
'leftUpperCorner',
'middle',
'rightLowerCorner',
1,
1,
'B',
'leftLowerCorner',
'rightUpperCorner',
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[0, 0, 'sides', 1, 1, 'B', 1, 'B', 1, 'sides', 0, 0, 0, 0, 0, 0, 0, 0, 0],
[
'leftUpperCorner',
'middle',
'rightLowerCorner',
1,
'upperCorner',
1,
'leftUpperCorner',
'rightUpperCorner',
1,
'sides',
0,
0,
0,
'leftUpperCorner',
'middle',
'middle',
'middle',
'middle',
'rightUpperCorner'
],
[
'sides',
1,
1,
1,
'lowerCorner',
1,
'leftLowerCorner',
'rightLowerCorner',
1,
'leftLowerCorner',
'middle',
'middle',
'middle',
'rightLowerCorner',
1,
1,
'G',
'G',
'sides'
],
['sides', 1, 'B', 1, 1, 'B', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 'G', 'G', 'sides'],
[
'leftLowerCorner',
'middle',
'middle',
'middle',
'rightUpperCorner',
1,
'left',
'middle',
'right',
1,
'upperCorner',
1,
'leftUpperCorner',
'rightUpperCorner',
1,
1,
'G',
'G',
'sides'
],
[
0,
0,
0,
0,
'sides',
1,
1,
1,
1,
1,
'leftSide',
'middle',
'lowerLeft',
'lower',
'middle',
'middle',
'middle',
'middle',
'rightLowerCorner'
],
[
0,
0,
0,
0,
'leftLowerCorner',
'middle',
'middle',
'middle',
'middle',
'middle',
'rightLowerCorner',
0,
0,
0,
0,
0,
0,
0,
0
]
];
class Game {
constructor(canvas, screens) {
this.canvas = canvas;
this.context = canvas.getContext('2d');
this.screens = screens;
this.running = false;
this.enableControls();
}
/*drawGrid() {
for (let x = 0; x <= 950; x += 50) {
for (let y = 0; y <= 550; y += 50) {
this.context.beginPath();
this.context.moveTo(x, 0);
this.context.lineTo(x, 550);
this.context.strokeStyle = 'black';
this.context.stroke();
this.context.closePath();
this.context.beginPath();
this.context.moveTo(0, y);
this.context.lineTo(950, y);
this.context.strokeStyle = 'black';
this.context.stroke();
this.context.closePath();
}
}
}*/
drawMap() {
for (const wall of this.walls) {
wall.draw();
}
for (const background of this.backgrounds) {
background.draw();
}
const backgroundImg = new Image();
backgroundImg.src = './images/Tile_12.png';
this.context.drawImage(backgroundImg, 50 * 5, 50 * 2, 50, 50);
this.context.drawImage(backgroundImg, 50 * 7, 50 * 3, 50, 50);
this.context.drawImage(backgroundImg, 50 * 5, 50 * 4, 50, 50);
this.context.drawImage(backgroundImg, 50 * 7, 50 * 4, 50, 50);
this.context.drawImage(backgroundImg, 50 * 2, 50 * 7, 50, 50);
this.context.drawImage(backgroundImg, 50 * 5, 50 * 7, 50, 50);
this.context.drawImage(backgroundImg, 50 * 16, 50 * 8, 50, 50);
this.context.drawImage(backgroundImg, 50 * 16, 50 * 7, 50, 50);
this.context.drawImage(backgroundImg, 50 * 17, 50 * 7, 50, 50);
this.context.drawImage(backgroundImg, 50 * 16, 50 * 6, 50, 50);
this.context.drawImage(backgroundImg, 50 * 17, 50 * 6, 50, 50);
this.context.drawImage(backgroundImg, 50 * 17, 50 * 8, 50, 50);
this.context.fillStyle = '#6a9423';
this.context.beginPath();
this.context.arc(50 * 16 + 25, 50 * 8 + 25, 10, 0, 2 * Math.PI);
this.context.fill();
this.context.closePath();
this.context.beginPath();
this.context.arc(50 * 17 + 25, 50 * 8 + 25, 10, 0, 2 * Math.PI);
this.context.fill();
this.context.closePath();
this.context.beginPath();
this.context.arc(50 * 16 + 25, 50 * 7 + 25, 10, 0, 2 * Math.PI);
this.context.fill();
this.context.closePath();
this.context.beginPath();
this.context.arc(50 * 17 + 25, 50 * 7 + 25, 10, 0, 2 * Math.PI);
this.context.fill();
this.context.closePath();
this.context.beginPath();
this.context.arc(50 * 16 + 25, 50 * 6 + 25, 10, 0, 2 * Math.PI);
this.context.fill();
this.context.closePath();
this.context.beginPath();
this.context.arc(50 * 17 + 25, 50 * 6 + 25, 10, 0, 2 * Math.PI);
this.context.fill();
this.context.closePath();
}
drawBoxes() {
for (const box of this.boxes) {
box.draw();
}
}
addMapBorders() {
this.walls = [];
const GRID_SIZE = 50;
for (let row = 0; row < wallMap.length; row++) {
for (let column = 0; column < wallMap[row].length; column++) {
const value = wallMap[row][column];
if (value !== 0 && value !== 1 && value !== 'G' && value !== 'B') {
const wall = new Wall(
this,
column * GRID_SIZE,
row * GRID_SIZE,
value
);
this.walls.push(wall);
}
}
}
}
addBackground() {
this.backgrounds = [];
const GRID_SIZE = 50;
for (let row = 0; row < wallMap.length; row++) {
for (let column = 0; column < wallMap[row].length; column++) {
const value = wallMap[row][column];
if (value === 1) {
const background = new Wall(
this,
column * GRID_SIZE,
row * GRID_SIZE,
'background'
);
this.backgrounds.push(background);
}
}
}
}
addBoxes() {
this.boxes = [];
const GRID_SIZE = 50;
for (let row = 0; row < wallMap.length; row++) {
for (let column = 0; column < wallMap[row].length; column++) {
const value = wallMap[row][column];
if (value === 'B') {
const box = new Box(this, column * GRID_SIZE, row * GRID_SIZE, 'box');
this.boxes.push(box);
}
}
}
}
addGoals() {
this.goals = [];
const GRID_SIZE = 50;
for (let row = 0; row < wallMap.length; row++) {
for (let column = 0; column < wallMap[row].length; column++) {
const value = wallMap[row][column];
if (value === 'G') {
const goal = new Wall(
this,
column * GRID_SIZE,
row * GRID_SIZE,
'background'
);
this.goals.push(goal);
}
}
}
}
displayScreen(name) {
const screenThatShouldBeDisplayed = this.screens[name];
const screensThatShouldBeHidden = Object.values(this.screens).filter(
(screen) => screen !== screenThatShouldBeDisplayed
);
screenThatShouldBeDisplayed.style.display = '';
for (const screen of screensThatShouldBeHidden)
screen.style.display = 'none';
}
start() {
this.running = true;
this.addMapBorders();
this.addBoxes();
this.addBackground();
this.addGoals();
this.player = new Player(this, 550, 400);
this.enemy = new Enemy(this, 700, 320);
this.paint();
this.loop();
this.displayScreen('playing');
}
runLogic() {
this.player.playerEnemyIntersect();
this.enemy.runLogic();
for (let m = 0; m < this.boxes.length; m++) {
//if any box is in a corner spot
if (
(this.boxes[m].x === 50 && this.boxes[m].y === 300) ||
(this.boxes[m].x === 50 && this.boxes[m].y === 350) ||
(this.boxes[m].x === 150 && this.boxes[m].y === 200) ||
(this.boxes[m].x === 250 && this.boxes[m].y === 50) ||
(this.boxes[m].x === 350 && this.boxes[m].y === 50) ||
(this.boxes[m].x === 400 && this.boxes[m].y === 200) ||
(this.boxes[m].x === 450 && this.boxes[m].y === 450) ||
(this.boxes[m].x === 250 && this.boxes[m].y === 450) ||
(this.boxes[m].x === 700 && this.boxes[m].y === 300) ||
(this.boxes[m].x === 700 && this.boxes[m].y === 400)
) {
this.lose();
}
}
//if all boxes are on all circles, game won
this.boxesongoal = [];
for (const box of this.boxes) {
for (const goal of this.goals) {
if (box.x === goal.x && box.y === goal.y) {
this.boxesongoal.push(box);
}
}
}
if (this.boxesongoal.length === 6) {
this.win();
}
}
loop() {
if (this.running) {
this.runLogic();
this.paint();
window.requestAnimationFrame(() => {
this.loop();
});
}
}
enableControls() {
window.addEventListener('keydown', (event) => {
const key = event.code;
switch (key) {
case 'ArrowUp':
this.player.move('up');
console.log('up');
console.log(this.player.x, this.player.y);
break;
case 'ArrowDown':
this.player.move('down');
console.log('down');
console.log(this.player.x, this.player.y);
break;
case 'ArrowRight':
this.player.move('right');
console.log('right');
console.log(this.player.x, this.player.y);
break;
case 'ArrowLeft':
this.player.move('left');
console.log('left');
console.log(this.player.x, this.player.y);
break;
case 'Space':
this.player.move('space');
console.log('attack');
console.log(this.player.x, this.player.y);
break;
}
});
}
clearScreen() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
paint() {
this.clearScreen();
//this.drawGrid();
this.drawMap();
this.drawBoxes();
this.player.paint();
if (this.enemy.enemyAlive) {
this.enemy.paint();
}
}
win() {
this.running = false;
this.displayScreen('gameWon');
}
lose() {
this.running = false;
this.displayScreen('gameOver');
}
}
<file_sep>const attackImage = new Image();
attackImage.src = './images/Woodcutter_attack1.png';
const pushImage = new Image();
pushImage.src = './images/Woodcutter_push.png';
const playerImage = new Image();
playerImage.src = './images/Woodcutter.png';
class Player {
constructor(game, x, y) {
this.game = game;
this.x = x;
this.y = y;
this.frame = 0;
this.paintPlayer = true;
}
move(direction) {
let newX = this.x;
let newY = this.y;
switch (direction) {
case 'up':
this.paintPlayer = true;
this.direction = 'up';
newY -= 50;
break;
case 'down':
this.paintPlayer = true;
this.direction = 'down';
newY += 50;
break;
case 'right':
this.paintPlayer = true;
this.direction = 'right';
newX += 50;
break;
case 'left':
this.paintPlayer = true;
this.direction = 'left';
newX -= 50;
break;
case 'space':
this.paintPlayer = false;
if (this.x < this.game.enemy.x && this.x + 20 >= this.game.enemy.x) {
this.game.enemy.enemyAlive = false;
}
if (this.game.enemy.x < this.x && this.x - 100 <= this.game.enemy.x) {
this.game.enemy.enemyAlive = false;
}
if (!this.game.enemy.enemyAlive) {
this.game.enemy.x = 0;
this.game.enemy.y = 0;
}
break;
}
let playerCanMove = true;
for (const wall of this.game.walls) {
const playerAndWallIntersect = wall.checkIntersection({
x: newX,
y: newY
});
if (playerAndWallIntersect) {
playerCanMove = false;
}
}
const boxes = this.game.boxes;
for (const box of boxes) {
const playerAndBoxIntersect = box.checkIntersection({ x: newX, y: newY });
if (playerAndBoxIntersect) {
const boxMoved = box.move(direction);
if (!boxMoved) {
playerCanMove = false;
}
}
}
if (playerCanMove) {
this.x = newX;
this.y = newY;
}
}
playerBoxIntersect() {
const boxes = this.game.boxes;
for (const box of boxes) {
const playerAndBoxIntersect = box.checkIntersection(this);
if (playerAndBoxIntersect) {
switch (this.direction) {
case 'up':
box.y -= 50;
break;
case 'down':
box.y += 50;
break;
case 'right':
box.x += 50;
break;
case 'left':
box.x -= 50;
break;
}
}
}
}
playerEnemyIntersect() {
if (this.game.enemy.checkIntersection(this)) {
this.game.lose();
}
}
paintAttack() {
const context = this.game.context;
context.save();
context.drawImage(
attackImage,
0 + 49 * Math.round(this.frame / 10),
6,
49,
43,
this.x,
this.y,
50,
50
);
context.restore();
this.frame++;
this.frame %= 50;
}
paint() {
if (this.paintPlayer) {
const context = this.game.context;
context.save();
context.drawImage(playerImage, 0, 12, 40, 37, this.x, this.y, 50, 50);
context.restore();
} else {
this.paintAttack();
}
}
}
<file_sep>const boxImg = new Image();
boxImg.src = './images/2.png';
class Box {
constructor(game, x, y) {
this.game = game;
this.x = x;
this.y = y;
this.boxCanMoveUp = true;
this.boxCanMoveDown = true;
this.boxCanMoveLeft = true;
this.boxCanMoveRight = true;
}
draw() {
this.game.context.drawImage(boxImg, this.x, this.y, 50, 50);
}
checkIntersection(element) {
return (
element.x >= this.x &&
element.x <= this.x + 49 &&
element.y >= this.y &&
element.y <= this.y + 49
);
}
move(direction) {
let intersects = false;
let newX = this.x;
let newY = this.y;
switch (direction) {
case 'up':
newY -= 50;
break;
case 'down':
newY += 50;
break;
case 'right':
newX += 50;
break;
case 'left':
newX -= 50;
break;
}
for (const box of this.game.boxes) {
if (box.checkIntersection({ x: newX, y: newY })) {
intersects = true;
}
}
for (const wall of this.game.walls) {
if (wall.checkIntersection({ x: newX, y: newY })) {
intersects = true;
}
}
if (intersects) {
return false;
} else {
this.x = newX;
this.y = newY;
return true;
}
}
}
<file_sep>const leftUpperCornerImage = new Image();
leftUpperCornerImage.src = './images/Tile_01.png';
const rightUpperCornerImage = new Image();
rightUpperCornerImage.src = './images/Tile_03.png';
const leftLowerCornerImage = new Image();
leftLowerCornerImage.src = './images/Tile_21.png';
const rightLowerCornerImage = new Image();
rightLowerCornerImage.src = './images/Tile_23.png';
const rightEdgeImage = new Image();
rightEdgeImage.src = './images/Tile_13.png';
const leftImage = new Image();
leftImage.src = './images/Tile_32.png';
const middleImage = new Image();
middleImage.src = './images/Tile_33.png';
const rightImage = new Image();
rightImage.src = './images/Tile_34.png';
const upperCornerImage = new Image();
upperCornerImage.src = './images/Tile_54.png';
const lowerCornerImage = new Image();
lowerCornerImage.src = './images/Tile_56.png';
const sidesImage = new Image();
sidesImage.src = './images/Tile_55.png';
const lowerImage = new Image();
lowerImage.src = './images/Tile_53.png';
const lowerLeftImage = new Image();
lowerLeftImage.src = './images/Tile_51.png';
const leftSideImage = new Image();
leftSideImage.src = './images/Tile_37.png';
const backgroundImg = new Image();
backgroundImg.src = './images/Tile_12.png';
const allImages = {
leftUpperCorner: leftUpperCornerImage,
rightUpperCorner: rightUpperCornerImage,
leftLowerCorner: leftLowerCornerImage,
rightLowerCorner: rightLowerCornerImage,
rightEdge: rightEdgeImage,
left: leftImage,
middle: middleImage,
right: rightImage,
upperCorner: upperCornerImage,
lowerCorner: lowerCornerImage,
sides: sidesImage,
lower: lowerImage,
lowerLeft: lowerLeftImage,
leftSide: leftSideImage,
background: backgroundImg,
box: boxImg
};
class Wall {
constructor(game, x, y, imageName) {
this.game = game;
this.x = x;
this.y = y;
this.imageName = imageName;
}
draw() {
const imageName = this.imageName;
const image = allImages[imageName];
this.game.context.drawImage(image, this.x, this.y, 50, 50);
}
checkIntersection(element) {
return (
element.x + 49 >= this.x &&
//disable moving right
element.x <= this.x + 49 &&
//disable moving left
element.y + 49 >= this.y &&
//disable moving down
element.y <= this.y + 49
//disable moving up
);
}
}
| 9ae3e7a72df6134d4621407c2bd363ef361d98c4 | [
"JavaScript"
] | 5 | JavaScript | leavonoldenburg/project-sokoban | ff989e9c3e9e4112fd0dc99781e0cb74ec67f4ad | cf3ef4514f703188fb32f23cc86ee2931c11a0d3 | |
refs/heads/master | <repo_name>vishwasmj/NEWBEE<file_sep>/Erosion.hpp
#ifndef EROSION_H_
#define EROSION_H_
#include "Action.hpp"
#pragma once
using namespace cv;
class Erosion: public Action {
public:
int erosion_type;
int erosion_elem = 0;
int erosion_size = 0;
int const max_elem = 2;
int const max_kernel_size = 21;
virtual void run();
};
#endif
| a703faea12593a72721d470f084d2630a5199b7a | [
"C++"
] | 1 | C++ | vishwasmj/NEWBEE | 879854175a7e5db551a28edf57caa3c02187baf1 | eefaa6d4f0d329bb8ebc17c7e301c616b7272cbc | |
refs/heads/master | <repo_name>CatibogDotNet/impacctsolutions.com<file_sep>/contactform.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<title>Contact Form</title>
<link rel="stylesheet" type="text/css" href="styles/impacct.css">
<script src="script/rotateLogo.js"></script>
</head>
<body>
<noscript>
For full functionality of this site it is necessary to enable JavaScript.
Here are the <a href="http://www.enable-javascript.com/" target="_blank">
instructions how to enable JavaScript in your web browser</a>.
</noscript>
<div id="header">
<div id="logo">
<img width="100", height="100", id="img" src="images/logoa.png">
</div>
<div id="menublock">
<div id="menu" >
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="aboutus.html">About Us</a></li>
<li><a href="contactus.html">Contact Us</a></li>
</ul>
</div>
<div id="title">Contact Form Processor</div>
</div>
<div class="clear"></div>
<hr />
<?php
$okay = false;
if ($_POST["submit"]) {
echo "<p style='font-size:20px; font-type:Arial'>These are the data you entered: </p>";
if ($_POST["firstname"]) {
echo "<p style='font-size:20px; font-type:Arial'>Your first name is ".$_POST["firstname"]."</p>";
if ($_POST["lastname"]) {
echo "<p style='font-size:20px; font-type:Arial'>Your last name is ".$_POST["lastname"]."</p>";
if ($_POST["email"]) {
echo "<p style='font-size:20px; font-type:Arial'>Your email is ".$_POST["email"]."</p>";
$okay=true;
} else {
echo "<p style='font-size:20px; font-type:Arial'>Please enter a valid email address</p>";}
} else {
echo "<p style='font-size:20px; font-type:Arial'>You must enter your last name</p>";}
} else {
echo "<p style='font-size:20px; font-type:Arial'>You must enter your first name</p>";
}
}
if ($okay==true){
$emailTo="<EMAIL>";
$subject=$_POST["email"]." ".$_POST["firstname"]." ".$_POST["lastname"];
$body=$_POST["comments"];
$headers="From: ".$_POST["email"];
if (mail($emailTo, $subject, $body, $headers)) {
echo "<p style='font-size:20px; font-type:Arial'>Thank you. Your email was sent successfully!</p>";
} else {
echo "<p style='font-size:20px; font-type:Arial'>Mail was not sent!</p>";
}
} else {
echo "<p style='font-size:20px; font-type:Arial'>Please re-enter your message!</p>";
}
?>
<script>startTimer()</script>
</body>
</html><file_sep>/ITA.php
<?php include ("includes/header1.php"); ?>
<title> IMPACCT Solutions - Income Tax Act</title>
<?php include ("includes/header2.php"); ?>
<?php include ("includes/menuhome.php"); ?>
<div class="clear"></div>
<hr />
<div id="title">INCOME TAX ACT 2014</div><br /><br />
<br />
<<p><a href="http://laws-lois.justice.gc.ca/PDF/I-3.3.pdf"><strong>Pdf copy of the Income Tax Act</strong></a>
</p>
<?php include ("includes/footer.php"); ?><file_sep>/onLinePayroll.php
<?php include ("includes/header.php"); ?>
<?php include ("includes/menuhome.php"); ?>
<div class="clear"></div>
<hr />
<div id="title">On Line Payroll</div><br /><br />
<h2>This page is under construction</h2>
<?php include ("includes/footer.php"); ?><file_sep>/script/rotateLogo.js
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
document.getElementById("img2").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 1000);
}
var images = [], x = -1;
images[0] = "images/logoa.png";
images[1] = "images/logob.png";
images[2] = "images/logoc.png";
images[3] = "images/logod.png";
images[4] = "images/logoe.png";
images[5] = "images/logof.png";
<file_sep>/Compilation.php
<?php include ("includes/header.php"); ?>
<?php include ("includes/menuhome.php"); ?>
<div class="clear"></div>
<hr />
<div id="title">Compilation by CPA</div><br /><br />
<h2>Compiled by Chartered Professional Accountant</h2>
<p> “Measurement is the first step that leads to control and eventually to improvement. If you can’t measure something, you can’t understand it.
If you can’t understand it, you can’t control it. If you can’t control it, you can’t improve it.” ― <NAME></p>
<p> Those who want to increase revenue and/or reduce costs need to measure them. Let us help you "improve" your finances.</p>
<p> We will compile the following financial statements from your submitted data:</p>
<ul>
<li> the statement of financial position</li>
<li> the income statement</li>
<li> the statement of cash flow</li>
<li> the equity statement</li>
<li> notes</li>
</ul>
<br />
<p> Prepared by a Chartered Professional Accountant, the financial statements are acceptable to bankers, investors, creditors, clients, and others.
Compilation steps include validating the balances in the asset, liability, and equity accounts such as:</p>
<ul>
<li>Cash and Cash equivalents</li>
<li>Accounts Receivable</li>
<li>Inventory</li>
<li>Accounts Payable and Accrued Liabilities</li>
<li>Capital Assets</li>
</ul>
<p> No audit is performed and all reports are based on your management's data submissions.</p>
<?php include ("includes/footer.php"); ?><file_sep>/Accounting.php
<?php include ("includes/header.php"); ?>
<?php include ("includes/menuhome.php"); ?>
<div class="clear"></div>
<hr />
<div id="title">Accounting (Bookkeeping) Services</div><br /><br />
<h2>Minimize your accounting costs by:</h2>
<ul>
<li>Automating processes that are frequently repeated.</li>
<li>Defining step-by-step procedure for creating accounting records and removing unnecessary steps.</li>
<li>Aligning bookkeeping activities with the compilation activities.     See the <a href="Compilation.php">Compilation</a> section of this website.</li>
</ul>
<h2>We can help with: </h2>
<ul>
<li>Bank reconciliation</li>
<li>Accounts Receivable trial balance preparation</li>
<li>Inventory summary and listings preparation</li>
<li>Accounts Payable trial balance preparation</li>
<li>Prepare capital asset schedules</li>
<li>Other accounts reconciliation</li>
<li>Recording revenues and expenses</li>
</ul>
<?php include ("includes/footer.php"); ?><file_sep>/software.php
<?php include ("includes/header.php"); ?>
<div id="menublock">
<div id="menu" >
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="aboutus.php">About Us</a></li>
<li><a href="contactus.php">Contact Us</a></li>
<li><a href="disclaimer.php">Downloads</a></li>
</ul>
</div>
</div>
<div class="clear"></div>
<hr />
<div id="title">Software Development</div><br /><br />
<br />
<h2>Accounting Software Tailored to Your Needs</h2>
<div class="details">
<p> We are currently working on payroll tools. Stay tuned for further developments.</p>
</div>
<?php include ("includes/footer.php"); ?><file_sep>/aboutus.php
<?php include ("includes/header1.php"); ?>
<title> IMPACCT Solutions - Chartered Professional Accountant and Payroll Manager</title>
<?php include ("includes/header2.php"); ?>
<?php include ("includes/menuhome.php")?>
<div class="clear"></div>
<hr />
<div id="title">About Us</div><br /><br />
<hr />
<h2>Chartered Professional Accountant</h2>
<p>
<span><NAME>, CPA, CMA<br></span>
<span>General Manager and Chief Accounting Officer<br></span>
<span>Email: <EMAIL><br></span>
<span>Specializes in Project Accounting with over 20 years of experience in accounting.</span>
</p>
<?php include ("includes/footer.php"); ?><file_sep>/disclaimer.php
<?php include ("includes/header.php"); ?>
<div id="menublock">
<div id="menu" >
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="aboutus.php">About Us</a></li>
<li><a href="contactus.php">Contact Us</a></li>
<li><a href="software.php">Software</a></li>
<li><a href="disclaimer.php">Downloads</a></li>
</ul>
</div>
</div>
<div class="clear"></div>
<hr />
<div id="title">Downloads</div><br /><br />
<hr />
<p> Simple excel payroll calculator is ready for testing. By downloading <a href="SimpleOntPayrollCalc2015.xlsm"> this, </a>
you attest that you have read and agree with disclaimer below and that "this" is called "software".
    Please note that this is for ONTARIO and year 2015 only. Please, please send us feedback so we can correct bugs.</p>
<p> Instructions for use: </p>
<ol>
<li> Click on "Exit Macro" (you can re-run the macro by pressing ctrl-A)</li>
<li> Enter your company information in sheet called "Company"</li>
<li> Enter your employee information in sheet called "EmpData" (you will need each employee's completed TD1 form, name,
address, and benefits, if any.)     Please delete the "dummy" employees listed as they do not pertain
to your company.</li>
<li> Save the file as "SimpleOntPayrollCalc2015.xlsm"</li>
<li> Press ctrl-A to run the payroll data entry macro.</li>
<li> The required data are the paydate, and employee number. All others are optional except for benefits. No entry
is required for benefits.</li>
<li> Always click on "Validate" before clicking on "Calculate and Record Pay"</li>
<li> Each time "Calculate and Record Pay" is clicked, an entry is made on sheet called "PayrollData"</li>
<li> "PayrollData" contains data that could be used to fill the T4 and related reports. Lines could be manually added, edited or
deleted from this sheet should the need arise (possibly from bugs). (Just make sure you exit the macro first.) You may be able to cut and
paste these data to future versions of this excel spreadsheet.</li>
<li> I hope you find this tool useful and give us feedback so we can improve it. We are continually updating this file as we
correct found bugs.</li>
</ol>
<p>Thank you!!!</p>
<h1>Disclaimer</h1>
<hr />
<div>
<p> ALL SOFTWARE IN THIS WEBSITE SHALL BE CALLED THE "SOFTWARE".
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
</p>
</div>
<?php include ("includes/footer.php"); ?><file_sep>/index.php
<?php include ("includes/header1.php"); ?>
<title> IMPACCT Solutions </title>
<?php include ("includes/header2.php"); ?>
<?php include ("includes/menuhome.php"); ?>
<div class="clear"></div>
<hr />
<div id="title">Chartered Professional Accountant Ready to serve You</div><br /><br />
<hr />
<div>
<p>We are motivated to assist small businesses in the Greater Toronto Area to become more efficient in terms of their accounting activities and reduce costs in the process.</p>
<h2>Services offered:</h2>
<p><a href="Compilation.php"><strong>Compilation: </strong></a>Performed by a Chartered Professional Accountant in compliance with Canadian GAAP or IFRS.
The resulting financial statements are unaudited but these are acceptable to most users. We also will not express an opinion on these financial statements.
<i>The Financial Statements are acceptable to bankers, investors, suppliers, creditors, and others ... and will cost less.</i>
<a href="Compilation.php">...more</a>
</p>
<p><a href="TaxAndTemp.php"><strong>Tax Services: </strong></a>Personal and Corporate. <i>CRA acceptable software used</i>
<a href="TaxAndTemp.php">...more</a>
</p>
<p><a href="Payroll.php"><strong>Payroll Services: </strong></a> CRA compliant to avoid penalties
<a href="Payroll.php">...more</a>
</p>
<p><a href="Accounting.php"><strong>Accounting (Bookkeeping): </strong></a> Concentrate on growing your business by letting us do the bookkeeping for you at reasonable prices.     You can further reduce costs by
<a href="Accounting.php">...more</a>
</p>
</div>
<?php include ("includes/footer.php"); ?><file_sep>/includes/contactform.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<title>Contact Us</title>
<link rel="stylesheet" type="text/css" href="../styles/impacct.css">
<script src="../script/rotateLogo.js"></script>
</head>
<body>
<a name="top" />
<noscript>
For full functionality of this site it is necessary to enable JavaScript.
Here are the <a href="http://www.enable-javascript.com/" target="_blank">
instructions how to enable JavaScript in your web browser</a>.
</noscript>
<div class="header">
<div class="floatleft" style='width:100px; height:100px' >
<img width="100", height="100", id="img" src="images/logoa.png">
</div>
<div class="floatleft" style='height:100px; width:1000px'>
<div class="floatleft" id="menu" >
<ul style='style-list-type:none; font-size:16px'>
<li><a href="index.html">Home</a></li>
<li><a href="aboutus.html">About Us</a></li>
<li><a href="contactus.html">Contact Us</a></li>
</ul>
</div>
</div>
<div class="clear"></div>
<hr />
<?php
if ($_POST["submit"]) {
if ($_POST["firstname"]) {
echo "Your first name is ".$_POST["firstname"];
}
if ($_POST["lastname"]) {
echo "Your last name is ".$_POST["lastname"];
}
}
$emailTo="<EMAIL>";
$subject="Sent by: ".$_POST["email"];
$body=$_POST["comments"];
$headers="From: impacctsolutions.com";
if (mail($emailTo, $subject, $body, $headers)) {
echo "Thank you. Your email was sent successfully!";
} else {
echo "Mail was not sent!";
}
?>
<script>startTimer()</script>
</body>
</html><file_sep>/payrollChecklist.php
<?php include ("includes/header.php"); ?>
<?php include ("includes/menupayhome.php"); ?>
<div class="clear"></div>
<hr />
<div id="title">Checklist to Help Minimize Payroll Penalties</div><br /><br />
<h2>Checklist to help minimize payroll penalties</h2>
<p> 1. Do you have a business number and has it been activated for payroll? If not, please read <a href="http://www.cra-arc.gc.ca/E/pub/tg/rc2/rc2-13e.pdf">
this. </a>You will need the business number to open a payroll account with the CRA. Click
<a href="http://www.cra-arc.gc.ca/tx/bsnss/tpcs/bn-ne/rgstr/menu-eng.html">here </a> to see how to register with the CRA.<br>
2. Get the employee's social insurance number and validate it.<br>
3. Have the employee complete the Federal and Provincial/Territorial TD1 forms.<br>
4. Make sure to deduct CPP, EI, and income taxes. Failure to deduct carries a first time penalty of 10% of the amount not deducted.
20% for subsequent infractions in the same calendar year.<br>
5. Make sure to remit employee deductions and employer portions on time. Failure to remit and late remittances carry penalties.<br>
6. Make sure to maintain adequate records. <br>
7. When an employee has an interruption in earnings, you have to complete a Record of Employment (ROE) for EI purposes.<br>
8. The above list is by no means complete. Please check <a href="http://www.cra-arc.gc.ca/tx/bsnss/tpcs/pyrll/hwpyrllwrks/pnlty/menu-eng.html">this </a>
out for a more complete list of items that the CRA could use to penalize you.
</p>
<?php include ("includes/footer.php"); ?><file_sep>/CRALinks.php
<?php include ("includes/header.php"); ?>
<?php include ("includes/menupayhome.php"); ?>
<div class="clear"></div>
<hr />
<div id="title">CRA & Government of Canada Useful Links</div><br /><br />
<h2>Click on desired information</h2>
<p>
<a href="http://www.cra-arc.gc.ca/tx/bsnss/tpcs/pyrll/bnfts/bnchrt-eng.html">Benefits and Allowances Chart</a><br />
<a href="http://www.cra-arc.gc.ca/tx/bsnss/tpcs/pyrll/hwpyrllwrks/pnlty/menu-eng.html">Penalties, Interest, And Other Consequences</a><br />
<a href="http://www.cra-arc.gc.ca/esrvc-srvce/rf/t4-wbfrms/menu-eng.html">Web forms</a><br />
<a href="http://www.cra-arc.gc.ca/E/pbg/tf/rc18/rc18-14e.pdf">Automobile benefit form</a><br />
<a href="http://www.fin.gc.ca/n14/14-120-eng.asp">Small Business Job Credit</a><br />
<a href="http://news.gc.ca/web/article-en.do?mthd=index&crtr.page=1&nid=899339">CPP 2015 MPE</a><br />
<a href="http://news.gc.ca/web/article-en.do?&nid=875529">Severe Penalties for using ESS</a><br />
<a href="http://www.cra-arc.gc.ca/E/pub/tg/t4130/t4130-13e.pdf">Taxable Benefits and Allowances Guide</a><br />
<a href="http://www.budget.gc.ca/2014/docs/plan/anx1-eng.html">Canada's Debt Management Strategy for 2014–15</a><br />
<a href="http://www.fin.gc.ca/n14/14-167-eng.asp">Canada Issues More Ultra-Long Bonds</a><br />
</p>
<?php include ("includes/footer.php"); ?><file_sep>/TaxAndTemp.php
<?php include ("includes/header1.php"); ?>
<title> IMPACCT Solutions - Accounting Software Solutions</title>
<?php include ("includes/header2.php"); ?>
<?php include ("includes/menuhome.php"); ?>
<div class="clear"></div>
<hr />
<div id="title">Tax Services</div><br /><br />
<br />
<h2>Personal and Corporate Tax Return Preparations are done with CRA approved software. E-file service available. </h2>
<p>
</p>
<?php include ("includes/footer.php"); ?><file_sep>/contactus.php
<?php include ("includes/header.php"); ?>
<?php include ("includes/menuhome.php"); ?>
<div class="clear"></div>
<hr />
<div id="title">Contact Us</div><br /><br />
<hr />
<div class="floatleft">
<p> Please send us a message by submitting your info: </p>
<form name="contactform" method="post" action="contactform.php" style='font-size:16px'>
First Name: <br /><input type="text" name="firstname" size="78"/> <br />
Last Name: <br /><input type="text" name="lastname" size="78" /><br />
email address: <br /><input type="email" name="email" size="78"/><br />
Comments (max 255 chars): <br /><textarea type="text" name="comments" style='height:150px; width:494px' ></textarea><br />
<input type="submit" name = "submit" value="Submit" /><br /><br />
</form>
</div>
<div class="floatleft">
<ul>
<p id="contact">
<span>Or contact us by other means at:<br></span>
<span><br><NAME></span>
<span><br>IMPACCT Solutions - Business Development</span>
<span><br>37 Albright Crescent, Richmond Hill, ON L4E 4Z4</span>
<span><br>Email: <EMAIL></span>
<span><br>Tel: 289-809-1732</span>
<span><br>Cell: 416-458-0640<br></span>
<span><br>We appreciate your business!!!</span>
</p>
</ul>
</div>
<div>
<span style='position:relative; left:0px;top:0px;width:600px;height:450px'>
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2873.8115502313717!2d-79.45410890000002!3d43.92187550000001!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x882ad5ee0dbf470f%3A0x1223736ccc6ca4a9!2s37+Albright+Crescent%2C+Richmond+Hill%2C+ON+L4E!5e0!3m2!1sen!2sca!4v1414757608524"
width="600" height="450" frameborder="0" style="border:0" align="center">
</iframe>
</span>
</div>
<?php include ("includes/footer.php"); ?><file_sep>/Payroll.php
<?php include ("includes/header1.php"); ?>
<title> IMPACCT Solutions - Accounting Software Solutions</title>
<?php include ("includes/header2.php"); ?>
<?php include ("includes/menuhome.php"); ?>
<div class="clear"></div>
<hr />
<div id="title">Payroll</div><br /><br />
<br />
<h2>Call Us For Your Payroll Needs</h2>
<p> What if your employees didn’t receive their pay cheque on time? IMPACCT Solutions can help make sure it does not happen.
Our services include HR Setup, Payroll Processing and Reporting; we make sure that salaries & wages, with CRA acceptable
deductions, get paid to your employees accurately and on time.
</p>
<?php include ("includes/footer.php"); ?> | b2adeebc4fba1b49383c5a603e4f212b6eae4a17 | [
"JavaScript",
"PHP"
] | 16 | PHP | CatibogDotNet/impacctsolutions.com | 52baa8488ad028cd2528c0667c0bc29eb067c27f | 4f6aefff1d8feedc4cb0f4217f8bdf190072cdea | |
refs/heads/master | <repo_name>ChadGatling/Sand-Dune<file_sep>/Sand Dune/Assets/MyAssets/Scripts/Rudder.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rudder : DriveComponent {
public MoveShip ship;
LeverAction throttle;
void Start () {
throttle = transform.Find("Rudder/LeverArm").GetComponent<LeverAction>();
}
void Update () {
ship.turn = throttle.howActive;
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/ObjectData.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectData : MonoBehaviour {
private static float leverAngle;
private static bool handsOnly;
public virtual bool GetHandsOnly()
{
return handsOnly;
}
public virtual void SetHandsOnly(bool value)
{
handsOnly = value;
}
public static float GetLeverAngle()
{
return leverAngle;
}
public static void SetLeverAngle(float value)
{
leverAngle = value;
}
}
<file_sep>/README.md
# Sand-Dune
A game about survival on land-ships in a post post-apocalyptic desert sea.
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/MoveShip.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class WheelComponent {
public WheelCollider wheel;
/// <summary>
/// Is this wheel attached to motor?
/// </summary>
public bool isPowered;
/// <summary>
/// Does this wheel apply steer angle?
/// </summary>
public bool isSteerable;
/// <summary>
/// Is this a front wheel?
/// </summary>
public bool isFore;
/// <summary>
/// Is this a starboard wheel?
/// </summary>
public bool isStarboard;
}
public class MoveShip : DriveComponent {
Rigidbody shipPhysics;
[SerializeField] private float Knots;
// [Range(0f, 30f)] // make the high end the same as maxRPG
float wheelRPM;
// [SerializeField] float maxRPM;
[HideInInspector] public float[] turnRange = {-1f, 1f};
// [HideInInspector] public float[] throttleRange = {0f, 1f};
// [HideInInspector] public float[] clutchRange = {0f, 1f};
[HideInInspector] public float[] brakingRange = {0f, 1f};
[Range(-1f, 1f)] public float turn;
// [Range(0f, 1f)] public float throttle;
// [Range(0f, 1f)] public float clutch;
[Range(0, 1f)] public float braking;
[SerializeField] bool reverse;
[SerializeField] List<WheelComponent> wheels; // the information about each individual wheel
// [SerializeField] float maxMotorTorque; // maximum torque the motor can apply to wheel
[SerializeField] float maxSteeringAngle; // maximum steer angle the wheel can have
// [SerializeField] float maxBraking; // maximum steer angle the wheel can have
[SerializeField] DriveComponent fuelSide;
[SerializeField] AnimationCurve frictionCurve;
void Start () {
shipPhysics = GetComponent<Rigidbody>();
}
void FixedUpdate () {
// input = fuelSide.downStream;
turn = Mathf.Clamp(turn, turnRange[0], turnRange[1]);
// throttle = Mathf.Clamp(throttle, throttleRange[0], throttleRange[1]);
// clutch = Mathf.Clamp(clutch, clutchRange[0], clutchRange[1]);
braking = Mathf.Clamp(braking, brakingRange[0], brakingRange[1]);
torqueCurrent = upStream.torqueCurrent;
float steering = maxSteeringAngle * turn;
// float brake = 100f;
int reversing = reverse ? -1 : 1;
wheelRPM = 0;
float sprungMass = 0;
foreach (WheelComponent wheelUnit in wheels) {
float frictionTorque = frictionCurve.Evaluate(wheelUnit.wheel.rpm);
wheelRPM += wheelUnit.wheel.rpm;
sprungMass = wheelUnit.wheel.sprungMass;
if (wheelUnit.isSteerable) {
if (wheelUnit.isFore) {
wheelUnit.wheel.steerAngle = steering;
} else {
wheelUnit.wheel.steerAngle = -steering;
}
}
if (wheelUnit.isPowered)
if (torqueCurrent >= 0){
wheelUnit.wheel.motorTorque = torqueCurrent;
wheelUnit.wheel.brakeTorque = frictionTorque;
} else {
wheelUnit.wheel.motorTorque = 0;
wheelUnit.wheel.brakeTorque = -torqueCurrent + frictionTorque;
}
ApplyLocalPositionToVisuals(wheelUnit.wheel);
}
rpmCurrent = wheelRPM / wheels.Count;
sprungMass = sprungMass / wheels.Count;
// fuelSide.currentRpm = ;
Knots = Mathf.Round(shipPhysics.velocity.magnitude * 1.943844f * 100) / 100;
}
public void ApplyLocalPositionToVisuals(WheelCollider collider)
{
if (collider.transform.childCount == 0) {
return;
}
Transform visualWheel = collider.transform.GetChild(0);
Vector3 position;
Quaternion rotation;
collider.GetWorldPose(out position, out rotation);
visualWheel.transform.position = position;
visualWheel.transform.rotation = rotation;
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/AttatchToShip.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AttatchToShip : MonoBehaviour {
[SerializeField]GameObject player;
void OnTriggerEnter(Collider col) {
if (col.gameObject == player) {
player.GetComponent<PlayerMove>().hasParent = true;
player.transform.parent = transform;
}
}
void OnTriggerExit(Collider col) {
if (col.gameObject == player)
player.GetComponent<PlayerMove>().hasParent = false;
player.transform.parent = null;
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/ObjectAction.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectAction : MonoBehaviour {
public bool isActive = false;
public float howActive = 0;
[HideInInspector] public static float rangeMax;
[HideInInspector] public float rangeMin;
public float angleMax;
public virtual void Action (RaycastHit hit) {
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/PlayerLook.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerLook : MonoBehaviour {
public float mouseSensitivity;
public Transform playerBody;
private float mouseX = 0f, mouseY = 0f;
public bool inspectView = false;
private void Update() {
CameraRotation();
LookMode();
}
private void LookMode() {
if (inspectView && (Mathf.Abs(Input.GetAxis("Vertical")) >= .9f || Mathf.Abs(Input.GetAxis("Horizontal")) >= .9f)) {
inspectView = false;
}
if (Input.GetButtonDown("Look Mode")) {
inspectView = !inspectView;
}
}
private void CameraRotation() {
// if (Input.GetButton("Build"))
// return;
if (inspectView) {
Cursor.lockState = CursorLockMode.None;
} else {
mouseX += Input.GetAxis("Mouse X") * mouseSensitivity;
mouseY += -Input.GetAxis("Mouse Y") * mouseSensitivity;
mouseY = Mathf.Clamp(mouseY, -90f, 90f);
Cursor.lockState = CursorLockMode.Locked; // seems take up a good amount of cpu time. Replace this with a UI reticle.
transform.eulerAngles = new Vector3(mouseY, transform.eulerAngles.y, 0);
}
playerBody.eulerAngles = new Vector3(0, mouseX, 0); // I think this is the one that needs to be active for the player to ride on the ship
#if UNITY_EDITOR
Cursor.visible = true;
#else
Cursor.visible = false;
#endif
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/Clutch.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Clutch : DriveComponent {
LeverAction clutch;
void Start () {
clutch = transform.Find("Clutch/LeverArm").GetComponent<LeverAction>();
}
void Update () {
torqueCurrent = upStream.torqueCurrent * clutch.howActive;
isRunning = upStream.isRunning;
rpmCurrent = Mathf.Lerp(upStream.rpmCurrent, downStream.rpmCurrent, clutch.howActive);
if (downStream) {
torqueToTurnMax = torqueToTurnCurve.Evaluate(rpmCurrent) - downStream.torqueToTurnMax;
} else {
torqueToTurnMax = torqueToTurnCurve.Evaluate(rpmCurrent);
}
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/PlayerWorldClick.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerWorldClick : MonoBehaviour {
[SerializeField] float raylength;
private LayerMask LayerMask;
void Start () {
LayerMask = LayerMask.GetMask("Action" ,"Default");
}
void Update () {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
bool raycast = Physics.Raycast(ray, out hit, raylength, LayerMask);
if (raycast && hit.collider.tag == "Interactable") {
hit.collider.GetComponent<ObjectAction>().Action(hit);
}
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/Engine.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Engine : DriveComponent {
[SerializeField] float torqueMax;
[SerializeField] float torqueStart;
[SerializeField] AnimationCurve torqueCurve;
[SerializeField] float rpmMax;
[SerializeField] float rpmMin;
// [SerializeField] AnimationCurve rpmCurve;
[SerializeField] float preasure;
LeverAction throttle;
ButtonAction ignition;
PushPullAction choke;
ParticleSystem exhaust;
[SerializeField] float temperature = 70;
float startTime;
void Start () {
throttle = transform.Find("Throttle/LeverArm").GetComponent<LeverAction>();
ignition = transform.Find("Ignition").GetComponent<ButtonAction>();
choke = transform.Find("Choke").GetComponent<PushPullAction>();
exhaust = GetComponent<ParticleSystem>();
SetOutput();
}
void FixedUpdate () {
if (isRunning) {
IncreaseTemperature();
SetRpm();
Stall();
SetTorque();
} else {
rpmCurrent = 0;
Ignition();
DecreaseTemperature();
}
SetOutput();
}
void IncreaseTemperature() {
if (temperature < 250) {
temperature += Time.fixedDeltaTime;
temperature = Mathf.Clamp(temperature, 70, 250);
}
}
void DecreaseTemperature() {
if (temperature > 70) {
temperature -= Time.fixedDeltaTime;
temperature = Mathf.Clamp(temperature, 70, 250);
}
}
void SetTorque() {
var rpmRatio = rpmCurrent/rpmMax;
// var torqueMaxThisRpm = Utility.EvaluateCurve(torqueCurve, rpmRatio, torqueMax);
// float engineBrakeTorque = torqueMaxThisRpm - torqueMaxThisRpm * throttle.howActive;
float torqueGross = Utility.EvaluateCurve(torqueCurve, rpmRatio, torqueMax) * throttle.howActive;
torqueCurrent = (torqueGross) - Utility.EvaluateCurve(torqueToTurnCurve, rpmRatio, torqueToTurnMax) - 1; // add torque to turn friction as the unit wears
if (downStream != null) {
float clutchHowActive = downStream.transform.Find("Clutch/LeverArm").GetComponent<LeverAction>().howActive;
torqueCurrent -= downStream.torqueToTurnMax * clutchHowActive;
}
if (torqueCurrent < 0)
torqueCurrent *= 3; // might be as good as I can get for now. Meant to simulate engine brake.
if (!isRunning)
torqueCurrent *= 5;
#if UNITY_EDITOR
if (torqueCurrent > torqueMax) { // Remove after some time when it is shown that it will not happen.
Debug.Break();
Debug.Log("torqueCurrent has exceded torqueMax");
torqueCurrent = torqueMax;
};
#endif
}
void SetRpm() {
if (downStream != null) {
float clutchHowActive = downStream.transform.Find("Clutch/LeverArm").GetComponent<LeverAction>().howActive;
rpmCurrent = Mathf.Lerp(rpmCurrent + torqueCurrent * Time.fixedDeltaTime * 20, downStream.rpmCurrent, clutchHowActive);
} else
rpmCurrent += torqueCurrent * Time.fixedDeltaTime;
rpmCurrent = Mathf.Clamp(rpmCurrent, 0, rpmMax);
ParticleSystem.EmissionModule emission = exhaust.emission;
emission.rateOverTime = rpmCurrent / 60;
}
void Ignition() {
if (!ignition.isActive) {
// torqueCurrent = 0;
startTime = 0;
return;
}
if (startTime <= 0.5) {
startTime += Time.fixedDeltaTime;
torqueCurrent += torqueStart * Time.fixedDeltaTime * 2;
torqueCurrent = Mathf.Clamp(torqueCurrent, 0, torqueStart);
}
SetRpm();
if (choke.isActive && rpmCurrent >= rpmMin) {
isRunning = true;
exhaust.Play();
}
}
void Stall() {
if (rpmCurrent <= 0 || throttle.howActive <= 0) {
isRunning = false;
exhaust.Stop();
}
}
void SetOutput() {
}
}<file_sep>/Sand Dune/Assets/MyAssets/Scripts/PushPullAction.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PushPullAction : ObjectAction {
void Start () {
}
void Update () {
}
public override void Action(RaycastHit hit) {
bool onClick = Input.GetButtonDown("Action");
if (onClick) {
isActive = !isActive;
Vector3 move = new Vector3(0, isActive ? .25f : -.25f, 0);
transform.Translate(move);
}
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/LeverAction.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeverAction : ObjectAction {
// [SerializeField] string control;
// System.Reflection.FieldInfo controlField;
// MoveShip moveShip;
[SerializeField] bool allowNegative;
public void Start() {
// moveShip = transform.root.GetComponent<MoveShip>();
// System.Reflection.FieldInfo rangeField = moveShip.GetType().GetField(control + "Range");
// float[] range = (float[])rangeField.GetValue(moveShip);
rangeMin = allowNegative ? -1 : 0;
rangeMax = 1;
// controlField = moveShip.GetType().GetField(control);
}
void Update() {
transform.parent.localEulerAngles = new Vector3(howActive * 60, 0, 90);
}
public override void Action(RaycastHit hit) {
float mouseScroll = Input.GetAxis("Mouse ScrollWheel");
bool onClick = Input.GetButtonDown("Action");
bool onHold = Input.GetButton("Action");
// if (mouseScroll != 0) {
// // controlField = moveShip.GetType().GetField(control);
// // float controlValue = Mathf.Clamp((float)controlField.GetValue(moveShip) + mouseScroll, rangeMin, rangeMax);
// // controlField.SetValue(moveShip, controlValue);
// howActive += mouseScroll;
// howActive = Mathf.Clamp(howActive, rangeMin, rangeMax);
// transform.parent.localEulerAngles = new Vector3(howActive * 60, 0, 90);
// }
if (onHold) {
Plane axlePlane = new Plane(transform.parent.up, hit.point);
Vector3 localPoint = axlePlane.ClosestPointOnPlane(hit.point);
float angle;
// angle = Vector3.Angle(Vector3.up, localPoint - axlePlane.ClosestPointOnPlane(transform.parent.position));
angle = Vector3.SignedAngle(Vector3.up, localPoint - axlePlane.ClosestPointOnPlane(transform.parent.position), -transform.up);
Debug.Log(angle);
howActive = Mathf.Clamp(angle/angleMax, rangeMin, rangeMax);
transform.parent.localEulerAngles = new Vector3(howActive * angleMax, 0, 90);
}
// if (onClick) {
// // controlField.SetValue(moveShip, 0);
// howActive = 0;
// transform.parent.localEulerAngles = new Vector3(howActive * 60, 0, 90);
// }
}
// float GetAngle() {
// }
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/ButtonAction.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonAction : ObjectAction {
void Update() {
}
public override void Action(RaycastHit hit) {
isActive = Input.GetButton("Action");
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/Utility.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Custom utility functions.
/// </summary>
public class Utility {
/// <summary>Computes and returns the value of a given ratio on a given curve.</summary>
/// <param name ="curve">The curve on which the ratio will be computed.</param>
/// <param name="ratio">The value to compute on the curve. Usually a float between 0 and 1.</param>
/// <returns>Returns the Y-value of the curve at the given X-value as a float.</returns>
public static float EvaluateCurve(AnimationCurve curve, float ratio) {
return curve.Evaluate(ratio);
}
/// <summary>Computes and returns the value of a given ratio on a given curve applied to a given maximum.</summary>
/// <param name ="curve">The curve on which the ratio will be computed.</param>
/// <param name="ratio">The value to compute on the curve. Usually a float between 0 and 1.</param>
/// <param name="multiplier">The maximum value that should be returned. Return value will be relative to multiplier.</param>
/// <returns>Returns the Y-value of the curve at the given X-value as a float multiplied by the constant multiplier.</returns>
public static float EvaluateCurve(AnimationCurve curve, float ratio, float multiplier) {
return curve.Evaluate(ratio) * multiplier;
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/PlayerMove.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour {
private CharacterController charController;
private bool isJumping;
[HideInInspector] public bool hasParent;
public float movementSpeed;
public AnimationCurve jumpFallOff;
public float jumpMultiplier;
[SerializeField] Rigidbody shipPhysics;
Vector3 moveDirection;
void Awake () {
charController = GetComponent<CharacterController>();
}
void Update() {
JumpInput();
}
void FixedUpdate() {
PlayerMovement();
}
void PlayerMovement() {
bool isGrounded = charController.isGrounded;
if (isGrounded) {
float vertInput = Input.GetAxis("Vertical");
float horInput = Input.GetAxis("Horizontal");
Vector3 forwardMovement = transform.forward * vertInput;
Vector3 rightMovement = transform.right * horInput;
moveDirection = rightMovement + forwardMovement;
moveDirection *= movementSpeed;
} else {
moveDirection.y -= 20 * Time.fixedDeltaTime;
}
// if (Input.GetButton("Vertical") || Input.GetButton("Horizontal") || !isGrounded) // still need to figure out how to move the player with the ship at all times.
charController.Move(moveDirection * Time.fixedDeltaTime);
}
void JumpInput() {
if (Input.GetButtonDown("Jump")) {
if (!isJumping){
isJumping = true;
StartCoroutine(JumpEvent());
}
}
}
IEnumerator JumpEvent() {
charController.slopeLimit = 90.0f;
float timeInAir = 0.0f;
do {
float jumpForce = jumpFallOff.Evaluate(timeInAir);
charController.Move(Vector3.up * jumpForce * jumpMultiplier * Time.deltaTime);
timeInAir += Time.deltaTime;
yield return null;
} while (!charController.isGrounded && charController.collisionFlags != CollisionFlags.Above);
charController.slopeLimit = 45.0f;
isJumping = false;
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/UserInterface.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UserInterface : MonoBehaviour {
void Start () {
// Cursor.lockState = CursorLockMode.Locked;
}
void Update () {
if (Input.GetButtonDown("Cancel")){
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#elif UNITY_WEBPLAYER
Application.OpenURL(webplayerQuitURL);
#else
Application.Quit();
#endif
}
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/Weather.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weather : MonoBehaviour {
ParticleSystem precipitation;
void Start () {
precipitation = GetComponent<ParticleSystem>();
}
void Update () {
ParticleSystem.EmissionModule emission = precipitation.emission;
emission.rateOverTime = Time.timeSinceLevelLoad;
}
}
<file_sep>/Sand Dune/Assets/MyAssets/Scripts/DriveComponent.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DriveComponent : MonoBehaviour {
[HideInInspector] public bool isRunning;
public DriveComponent downStream;
public DriveComponent upStream;
public float rpmCurrent;
public float torqueCurrent;
public float torqueToTurnMax;
public AnimationCurve torqueToTurnCurve;
}
// [System.Serializable]
// public class DriveData {
// public float rpm;
// public float torque;
// } | 6a1feb30a3fa46b84dcffb3fa2ccbb69765ca356 | [
"Markdown",
"C#"
] | 18 | C# | ChadGatling/Sand-Dune | f2ff722932b1340ef201665b66f0f01b6c049c78 | a212df28823a76f5214e19b9946379d5625cb70b | |
refs/heads/master | <repo_name>boom1234/GitTest<file_sep>/first.php
<?php
echo "first";
echo "second";
echo "third";
echo "fourth";
echo "fifth";
echo "jape"; | 83ed0b5b9f0b13b57a591c4fda5ecdb769796a1f | [
"PHP"
] | 1 | PHP | boom1234/GitTest | 13fa1574e3d7fd02ff45ef03513d768f0e207674 | 6941a096b43d3fc63126476ffc4b3825da3b1cdc | |
refs/heads/master | <repo_name>frank-schoenheit-red6es/geminabox-release<file_sep>/lib/geminabox-release/version.rb
module GeminaboxRelease
# Version 1.0.0
# bundler >= 1.0.14 actually is a dependency
# Version 0.2.0
# * @hilli added support for https with optional veriy_none mode
VERSION = "1.1.0"
end
| 4d007dcad736f7a231862df09ca9135f8355bc18 | [
"Ruby"
] | 1 | Ruby | frank-schoenheit-red6es/geminabox-release | 90ba7e7d14905b5e47ddd7e6409d4765209d67a3 | f9b37bcfd62f430fa2ad592cd153ab64b0c920d1 | |
refs/heads/master | <repo_name>Teissere/chrome-manifest-iconify<file_sep>/README.md
# chrome-manifest-iconify
[](https://www.npmjs.com/package/chrome-manifest-iconify)
[](https://www.npmjs.com/package/chrome-manifest-iconify)
[](https://travis-ci.org/Steven-Roberts/chrome-manifest-iconify)
[](https://david-dm.org/Steven-Roberts/chrome-manifest-iconify)
[](https://david-dm.org/Steven-Roberts/chrome-manifest-iconify?type=dev)
[](https://codeclimate.com/github/Steven-Roberts/chrome-manifest-iconify/coverage)
[](https://codeclimate.com/github/Steven-Roberts/chrome-manifest-iconify)
When creating a Chrome extension or app, you need to provide a set of icons for
context menus, browser actions, page actions, and the Chrome Web Store. Usually,
these are just resized versions of the same image. The goal of
chrome-manifest-iconify is to intelligently handle the tedious process of
generated all these resized clones. All you need to do is provide it a master
icon and [v2 manifest](https://developer.chrome.com/extensions/manifest) file.
It will parse the manifest to determine the sizes, names, types, and paths of
the icons it needs to generate. You can choose from several resizing algorithms
as provide by [JIMP](https://github.com/oliver-moran/jimp) so your entire icon
set looks awesome.
## Installation
```shell
npm install --save-dev chrome-manifest-iconify
```
## Gulp
Instead of directly using this API, you might find it easier to use the
[Gulp](https://github.com/gulpjs/gulp) plugin
[gulp-chrome-manifest-iconify](https://github.com/Steven-Roberts/gulp-chrome-manifest-iconify)
for your project.
## API
<!-- Disable linting for the markdown generated by jsdoc-to-markdown -->
<!-- markdownlint-disable-->
<a name="module_chrome-manifest-iconify"></a>
### chrome-manifest-iconify
The chrome-manifest-iconify module
**Example**
```js
const chromeManifestIconify = require('chrome-manifest-iconify');
chromeManifestIconify.async({
manifest: 'src/manifest.json',
masterIcon: 'master.png',
resizeMode: chromeManifestIconify.ResizeMode.HERMITE
}).then((icons) => {
// Do stuff with icons
icons.forEach((i) => console.log(i.toString()));
}).catch((err) => {
// Oh, no! Something bad happened
console.log(err);
});
```
* [chrome-manifest-iconify](#module_chrome-manifest-iconify)
* [.Icon](#module_chrome-manifest-iconify.Icon)
* [new Icon(size, path, jimpData, contents)](#new_module_chrome-manifest-iconify.Icon_new)
* [.size](#module_chrome-manifest-iconify.Icon.Icon+size) : <code>number</code>
* [.path](#module_chrome-manifest-iconify.Icon.Icon+path) : <code>string</code>
* [.contents](#module_chrome-manifest-iconify.Icon.Icon+contents) : <code>Buffer</code>
* [.mimeType](#module_chrome-manifest-iconify.Icon+mimeType) : <code>string</code>
* [.toString()](#module_chrome-manifest-iconify.Icon+toString) ⇒ <code>string</code>
* [.ResizeMode](#module_chrome-manifest-iconify.ResizeMode)
* [.async(options)](#module_chrome-manifest-iconify.async) ⇒ [<code>Promise.<Icon></code>](#module_chrome-manifest-iconify.Icon)
<a name="module_chrome-manifest-iconify.Icon"></a>
#### chrome-manifest-iconify.Icon
Class representing a Chrome extension or app icon
**Kind**: static class of [<code>chrome-manifest-iconify</code>](#module_chrome-manifest-iconify)
* [.Icon](#module_chrome-manifest-iconify.Icon)
* [new Icon(size, path, jimpData, contents)](#new_module_chrome-manifest-iconify.Icon_new)
* [.size](#module_chrome-manifest-iconify.Icon.Icon+size) : <code>number</code>
* [.path](#module_chrome-manifest-iconify.Icon.Icon+path) : <code>string</code>
* [.contents](#module_chrome-manifest-iconify.Icon.Icon+contents) : <code>Buffer</code>
* [.mimeType](#module_chrome-manifest-iconify.Icon+mimeType) : <code>string</code>
* [.toString()](#module_chrome-manifest-iconify.Icon+toString) ⇒ <code>string</code>
<a name="new_module_chrome-manifest-iconify.Icon_new"></a>
##### new Icon(size, path, jimpData, contents)
Create an Icon
| Param | Type | Description |
| --- | --- | --- |
| size | <code>string</code> \| <code>number</code> | The size of the Icon in pixels |
| path | <code>string</code> | The file path to the Icon |
| jimpData | <code>object</code> | The JIMP image data |
| contents | <code>Buffer</code> | A Buffer of the Icon data |
<a name="module_chrome-manifest-iconify.Icon.Icon+size"></a>
##### icon.size : <code>number</code>
The size of the Icon in pixels
**Kind**: instance property of [<code>Icon</code>](#module_chrome-manifest-iconify.Icon)
**Read only**: true
<a name="module_chrome-manifest-iconify.Icon.Icon+path"></a>
##### icon.path : <code>string</code>
The file path to the Icon
**Kind**: instance property of [<code>Icon</code>](#module_chrome-manifest-iconify.Icon)
**Read only**: true
<a name="module_chrome-manifest-iconify.Icon.Icon+contents"></a>
##### icon.contents : <code>Buffer</code>
A Buffer of the Icon data
**Kind**: instance property of [<code>Icon</code>](#module_chrome-manifest-iconify.Icon)
**Read only**: true
<a name="module_chrome-manifest-iconify.Icon+mimeType"></a>
##### icon.mimeType : <code>string</code>
Gets the MIME type of the Icon
**Kind**: instance property of [<code>Icon</code>](#module_chrome-manifest-iconify.Icon)
<a name="module_chrome-manifest-iconify.Icon+toString"></a>
##### icon.toString() ⇒ <code>string</code>
Gets a human-friendly string representation of the Icon
**Kind**: instance method of [<code>Icon</code>](#module_chrome-manifest-iconify.Icon)
**Returns**: <code>string</code> - A string representation of the Icon
<a name="module_chrome-manifest-iconify.ResizeMode"></a>
#### chrome-manifest-iconify.ResizeMode
Enum for resize algorithms
**Kind**: static enum of [<code>chrome-manifest-iconify</code>](#module_chrome-manifest-iconify)
**Read only**: true
**Properties**
| Name | Default |
| --- | --- |
| NEAREST_NEIGHBOR | <code>jimp.RESIZE_NEAREST_NEIGHBOR</code> |
| BILINEAR | <code>jimp.RESIZE_BILINEAR</code> |
| BICUBIC | <code>jimp.RESIZE_BICUBIC</code> |
| HERMITE | <code>jimp.RESIZE_HERMITE</code> |
| BEZIER | <code>jimp.RESIZE_BEZIER</code> |
<a name="module_chrome-manifest-iconify.async"></a>
#### chrome-manifest-iconify.async(options) ⇒ [<code>Promise.<Icon></code>](#module_chrome-manifest-iconify.Icon)
Generates icon set for a Chrome extension or app by parsing the v2 manifest.
Note that this function does not actually write the files.
**Kind**: static method of [<code>chrome-manifest-iconify</code>](#module_chrome-manifest-iconify)
**Returns**: [<code>Promise.<Icon></code>](#module_chrome-manifest-iconify.Icon) - A promise that
resolves with the generated Icons
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| options | <code>object</code> | | The options for generating the Icons |
| options.manifest | <code>string</code> | | The path to the v2 manifest.json |
| options.masterIcon | <code>string</code> \| <code>Buffer</code> | | Either a path or Buffer of the master icon from which all the generated icons will be reseized |
| [options.resizeMode] | [<code>ResizeMode</code>](#module_chrome-manifest-iconify.ResizeMode) | <code>ResizeMode.BILINEAR</code> | The algorithm for resizing the master Icon |
<!-- markdownlint-enable-->
<file_sep>/index.js
'use strict';
/**
* The chrome-manifest-iconify module
* @module chrome-manifest-iconify
* @example
* const chromeManifestIconify = require('chrome-manifest-iconify');
*
* chromeManifestIconify.async({
* manifest: 'src/manifest.json',
* masterIcon: 'master.png',
* resizeMode: chromeManifestIconify.ResizeMode.HERMITE
* }).then((icons) => {
* // Do stuff with icons
* icons.forEach((i) => console.log(i.toString()));
* }).catch((err) => {
* // Oh, no! Something bad happened
* console.log(err);
* });
*/
// Local imports
const Manifest = require('./lib/manifest');
const Icon = require('./lib/icon');
const ResizeMode = require('./lib/resizeMode');
// Node imports
const Promise = require('bluebird');
const _ = require('lodash');
exports.Icon = Icon;
exports.ResizeMode = ResizeMode;
/**
* Generates icon set for a Chrome extension or app by parsing the v2 manifest.
* Note that this function does not actually write the files.
* @param {object} options - The options for generating the Icons
* @param {string} options.manifest - The path to the v2 manifest.json
* @param {string|Buffer} options.masterIcon - Either a path or Buffer of the
* master icon from which all the generated icons will be reseized
* @param {module:chrome-manifest-iconify.ResizeMode}
* [options.resizeMode=ResizeMode.BILINEAR] - The algorithm for resizing the
* master Icon
* @returns {Promise<module:chrome-manifest-iconify.Icon>} A promise that
* resolves with the generated Icons
*/
exports.async = (options) => {
// Validate options object
if (!_.isObject(options)) {
throw new TypeError('Options must be an object');
}
// Return a promise of the Icons
return Promise.join(
Manifest.load(options.manifest),
Icon.load(options.masterIcon),
(manifest, masterIcon) =>
manifest.getIcons(masterIcon, options.resizeMode)
);
};
<file_sep>/test/test.js
'use strict';
const chromeManifestIconify = require('../');
const Promise = require('bluebird');
const readFile = Promise.promisify(require('fs').readFile);
const path = require('path');
const jimp = require('jimp');
// <NAME>
const chai = require('chai');
chai.use(require('chai-as-promised'));
chai.use(require('chai-string'));
chai.should();
const getPath = path.join.bind(null, __dirname);
const getIconPath = getPath.bind(null, 'icons');
const getManifestPath = getPath.bind(null, 'manifests');
describe('chrome-manifest-iconify', () => {
describe('#async', () => {
const async = chromeManifestIconify.async;
it(
'should require an options object',
() => {
async.should.throw(TypeError, 'Options must be an object');
}
);
it(
'should not fail for valid resize mode',
() => {
const fn = () => async({
manifest: getManifestPath('minimal.json'),
masterIcon: getIconPath('test-icon.png'),
resizeMode: chromeManifestIconify.ResizeMode.HERMITE
});
fn.should.not.throw(Error);
}
);
it(
'should require a manifest path be provided in options',
() => {
const fn = () => async({
masterIcon: getIconPath('test-icon.png')
});
fn.should.throw(Error, 'The manifest path must be a string');
}
);
it(
'should require a master icon be provided in options',
() => {
const fn = () => async({
manifest: getManifestPath('minimal.json')
});
fn.should.throw(Error,
'The icon must be a file path or Buffer');
}
);
it(
'should reject promise when the manifest does not exist',
() => async({
manifest: getManifestPath('does-not-exist.json'),
masterIcon: getIconPath('test-icon.png')
}).should.eventually.be.rejectedWith(Error, new RegExp('ENOENT: ' +
'no such file or directory, open \'.*does-not-exist.json\''))
);
it(
'should reject promise when the master icon does not exist',
() => async({
manifest: getManifestPath('minimal.json'),
masterIcon: getIconPath('does-not-exist.jpg')
}).should.eventually.be.rejectedWith(Error, new RegExp('ENOENT: ' +
'no such file or directory, open \'.*does-not-exist.jpg\''))
);
it(
'should reject promise when the master icon is not square',
() => async({
manifest: getManifestPath('minimal.json'),
masterIcon: getIconPath('not-square.png')
}).should.eventually.be.rejectedWith(Error,
'The icon has size 128x64 which is not square')
);
it(
'should resolve promise when the master icon is a valid buffer',
() => readFile(getIconPath('test-icon.png'))
.then((masterIconBuffer) => async({
manifest: getManifestPath('minimal.json'),
masterIcon: masterIconBuffer
}))
.should.eventually.be.fulfilled
);
it(
'should reject promise when the manifest contains malformed JSON',
() => async({
manifest: getManifestPath('malformed.json'),
masterIcon: getIconPath('test-icon.png')
}).should.eventually.be.rejectedWith(SyntaxError,
'Unexpected token')
);
it(
'should reject promise when the manifest contains an invalid ' +
'icon extension',
() => async({
manifest: getManifestPath('invalid-extension.json'),
masterIcon: getIconPath('test-icon.png')
}).should.eventually.be.rejectedWith(Error,
'icon-128.invalid has no MIME type')
);
it(
'should reject promise when the manifest has a non-positve icon' +
'size',
() => async({
manifest: getManifestPath('negative-size.json'),
masterIcon: getIconPath('test-icon.png')
}).should.eventually.be.rejectedWith(Error,
'The icon size -42 is not a positive integer')
);
it(
'should reject promise when the manifest has a NaN icon size',
() => async({
manifest: getManifestPath('nan-size.json'),
masterIcon: getIconPath('test-icon.png')
}).should.eventually.be.rejectedWith(Error,
'The icon size abc is not a positive integer')
);
it(
'should reject promise when the manifest has an invalid icon path',
() => async({
manifest: getManifestPath('invalid-path.json'),
masterIcon: getIconPath('test-icon.png')
}).should.eventually.be.rejectedWith(Error,
'Path must be a string. Received 3.14')
);
it(
'should reject promise when the manifest has two icons with the ' +
'same path but different sizes',
() => async({
manifest: getManifestPath('same-path-different-size.json'),
masterIcon: getIconPath('test-icon.png')
}).should.eventually.be.rejectedWith(Error, 'The manifest ' +
'contains icons with sizes 128 and 16 from the same path ' +
'icon.png')
);
it(
'should resolve promise with icons for a valid manifest',
() => async({
manifest: getManifestPath('manifest.json'),
masterIcon: getIconPath('test-icon.png')
})
.then((icons) => {
icons.should.be.an('array').with.length(4);
icons.forEach((i) => i.should.have.property('contents')
.that.has.length.at.least(0));
icons[0].toString().should.startWith(`Icon \
${getManifestPath('icon-16.png')} of size 16x16 with data `);
icons[1].toString().should.startWith(`Icon \
${getManifestPath('icon-128.bmp')} of size 128x128 with data `);
icons[2].toString().should.startWith(`Icon \
${getManifestPath('a', 'icon-19.png')} of size 19x19 with data `);
icons[3].toString().should.startWith(`Icon \
${getManifestPath('img.jpg')} of size 38x38 with data `);
return Promise.map(icons, (i) => jimp.read(i.contents));
})
.then((icons) => {
icons[0].bitmap.width.should.equal(16);
icons[0].bitmap.height.should.equal(16);
icons[0].getMIME().should.equal('image/png');
icons[1].bitmap.width.should.equal(128);
icons[1].bitmap.height.should.equal(128);
icons[1].getMIME().should.equal('image/bmp');
icons[2].bitmap.width.should.equal(19);
icons[2].bitmap.height.should.equal(19);
icons[2].getMIME().should.equal('image/png');
icons[3].bitmap.width.should.equal(38);
icons[3].bitmap.height.should.equal(38);
icons[3].getMIME().should.equal('image/jpeg');
})
);
it(
'should resolve promise when manifest has duplicate icon',
() => async({
manifest: getManifestPath('duplicate-icon.json'),
masterIcon: getIconPath('test-icon.png'),
resizeMode: chromeManifestIconify.ResizeMode.NEAREST_NEIGHBOR
})
.then((icons) => {
icons.should.be.an('array').with.length(1);
icons[0].toString().should.startWith(`Icon \
${getManifestPath('icon.png')} of size 19x19 with data `);
return jimp.read(icons[0].contents);
})
.then((icon) => {
icon.bitmap.width.should.equal(19);
icon.bitmap.height.should.equal(19);
icon.getMIME().should.equal('image/png');
})
);
});
});
<file_sep>/lib/manifest.js
'use strict';
const Promise = require('bluebird');
const readFile = Promise.promisify(require('fs').readFile);
const _ = require('lodash');
const pathUtil = require('path');
const iconManifestPaths = [
'icons',
'browser_action.default_icon',
'page_action.default_icon'
];
/**
* Class representing a Chrome extension manifest file
*/
class Manifest {
/**
* A static helper function that loads a Manifest from a file
* @param {string} path The path from which to load the Manifest
* @returns {Promise} A Promise that resolves when the Manifest loads
*/
static load (path) {
if (!_.isString(path)) {
throw new TypeError('The manifest path must be a string');
}
return readFile(path)
.then((data) => new Manifest(path, JSON.parse(data)));
}
/**
* Create a Manifest
* @param {string} path The path at which the Manifest is located
* @param {object} content - The Manifest data
*/
constructor (path, content) {
this.path = path;
this.content = content;
}
/**
* Generated properly resized icons by parsing the Manifest contents
* @param {module:chrome-manifest-iconify.Icon} masterIcon The Icon from
* which the others will be generated
* @param {module:chrome-manifest-iconify.ResizeMode}
* [resizeMode=ResizeMode.BILINEAR] - The algorithm for resizing the master
* Icon
* @returns {Promise<Icon>} A promise that resolves when the Icons are
* created
*/
getIcons (masterIcon, resizeMode) {
const icons = _(iconManifestPaths)
.flatMap((manifestPath) => _.map(_.get(this.content, manifestPath),
(path, size) => ({
path,
size
})))
.uniqWith((i1, i2) => {
const samePath = i1.path === i2.path;
const sameSize = i1.size === i2.size;
if (samePath && !sameSize) {
throw Error(`The manifest contains icons with sizes \
${i1.size} and ${i2.size} from the same path ${i1.path}`);
}
return samePath && sameSize;
})
.map((i) => masterIcon.resize(
i.size,
pathUtil.join(pathUtil.dirname(this.path), i.path),
resizeMode
))
.value();
return Promise.all(icons);
}
}
module.exports = Manifest;
<file_sep>/lib/resizeMode.js
'use strict';
const jimp = require('jimp');
/**
* Enum for resize algorithms
* @readonly
* @enum
* @memberof module:chrome-manifest-iconify
*/
const ResizeMode = {
NEAREST_NEIGHBOR: jimp.RESIZE_NEAREST_NEIGHBOR,
BILINEAR: jimp.RESIZE_BILINEAR,
BICUBIC: jimp.RESIZE_BICUBIC,
HERMITE: jimp.RESIZE_HERMITE,
BEZIER: jimp.RESIZE_BEZIER
};
module.exports = Object.freeze(ResizeMode);
<file_sep>/lib/icon.js
'use strict';
const mimeTypes = require('mime-types');
const Promise = require('bluebird');
const jimp = require('jimp');
const _ = require('lodash');
const nodePath = require('path');
/**
* Class representing a Chrome extension or app icon
* @memberof module:chrome-manifest-iconify
*/
class Icon {
/**
* Create an Icon
* @ignore
* @private
* @param {string|number} size - The size of the Icon in pixels
* @param {string} path - The file path to the Icon
* @param {object} jimpData - The JIMP image data
* @param {Buffer} contents - A Buffer of the Icon data
*/
constructor (size, path, jimpData, contents) {
// Assign the params as class properties
/**
* The size of the Icon in pixels
* @readonly
* @type {number}
*/
this.size = parseInt(size, 10);
if (isNaN(this.size) || this.size <= 0) {
throw new Error(`The icon size ${size} is not a positive integer`);
}
/**
* The file path to the Icon
* @readonly
* @type {string}
*/
this.path = path;
/**
* @private
* The JIMP image data
* @readonly
* @type {object}
*/
this.jimpData = jimpData;
/**
* A Buffer of the Icon data
* @readonly
* @type {Buffer}
*/
this.contents = contents;
}
/**
* A static helper function that loads an Icon from a file
* @private
* @param {string|Buffer} file - Either a path or Buffer of the Icon
* @returns {Promise<Icon>} A promise that resolves when the Icon loads
*/
static load (file) {
let path = '';
let contents = null;
if (_.isString(file)) {
path = file;
} else if (Buffer.isBuffer(file)) {
contents = file;
} else {
throw new TypeError('The icon must be a file path or Buffer');
}
return jimp.read(file)
.then((jimpData) => {
const width = jimpData.bitmap.width;
const height = jimpData.bitmap.height;
if (width !== height) {
throw new Error(`The icon has size ${width}x${height} \
which is not square`);
}
return new Icon(width, path, jimpData, contents);
});
}
/**
* Gets the MIME type of the Icon
* @type {string}
*/
get mimeType () {
const mimeType = mimeTypes.lookup(this.path);
if (!mimeType) {
throw new Error(`${nodePath.basename(this.path)} has no MIME type`);
}
return mimeType;
}
/**
* Create a new Icon that is a resized version of this Icon
* @private
* @param {string|number} size - The size of the new Icon in pixels
* @param {string} path - The file path to the new Icon
* @param {module:chrome-manifest-iconify.ResizeMode}
* [resizeMode=ResizeMode.BILINEAR] - The algorithm for resizing the master
* Icon
* @returns {Promise<Icon>} A promise that resolves when the Icon is resized
*/
resize (size, path, resizeMode) {
const resizedIcon = new Icon(size, path);
const resizedJimpData = this.jimpData.clone()
.resize(resizedIcon.size, resizedIcon.size, resizeMode);
resizedIcon.jimpData = resizedJimpData;
return Promise.fromCallback(
(cb) => resizedJimpData.getBuffer(resizedIcon.mimeType, cb)
).then((resizedContents) => {
resizedIcon.contents = resizedContents;
return resizedIcon;
});
}
/**
* Gets a human-friendly string representation of the Icon
* @returns {string} A string representation of the Icon
*/
toString () {
return `Icon ${this.path} of size ${this.size}x${this.size} with data \
${this.contents}`;
}
}
module.exports = Icon;
| f6d83e9764f437f56dfcf6cf0a1a5f59fd141d7b | [
"Markdown",
"JavaScript"
] | 6 | Markdown | Teissere/chrome-manifest-iconify | 6baf9eead597d50ec437cf3d7f47fd56e225ecbc | 863371feda6f7a6077a80b0a4387357207df8796 | |
refs/heads/main | <repo_name>Zain-mir24/Webscrapper<file_sep>/public/js/index.js
const request = require("request-promise")
const cheerio = require("cheerio")
const json2csv = require("json2csv").Parser
const fs= require("fs")
const movie="https://www.imdb.com/title/tt2560140/?ref_=hm_fanfav_tt_9_pd_fp1";
(async()=> {
let imdbdata=[];
const response = await request({
method: 'POST',
uri: movie,
gzip:true,
headers: {
accept:
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-CA,en-GB;q=0.9,en-US;q=0.8,en;q=0.7",
}
});
let $ = cheerio.load(response);
const title =$('div[class="title_wrapper"]>h1').text().trim() //getting title from the website
const rating=$('div[class="ratingValue"]').text().trim() //getting the rating
const summary=$('div[class="summary_text"]').text().trim()
imdbdata.push({
title:title, //webscraper workings
rating: rating,
summmary:summary
});
const j2csv = new json2csv()
const csv =j2csv.parse(imdbdata) //using j2csv
fs.writeFileSync("./imdb.csv",csv,"utf-8");
})();
process.on('unhandledRejection', (reason, promise) => { //making promises
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
// Application specific logging, throwing an error, or other logic here
});
| 178229e8e489d87841b36ef16a28d4ecb1468b38 | [
"JavaScript"
] | 1 | JavaScript | Zain-mir24/Webscrapper | 8f866acaf99fa4bc9934111f151afffcfdd05ff5 | f6c8e1343f859395885aaa8822f0ca172239f583 | |
refs/heads/main | <repo_name>morrowc/goog_addressing<file_sep>/simple.py
#!/usr/bin/env python3
#
# Simple digest and return netblocks from goog/cloud.json
# https://www.gstatic.com/ipranges/goog.json
# https://www.gstatic.com/ipranges/cloud.json
import ipaddress
import json
import urllib.request
import sys
URLS = {
"goog": "https://www.gstatic.com/ipranges/goog.json",
"cloud":"https://www.gstatic.com/ipranges/cloud.json",
}
def get_file(name):
"""Download a single file, return that as a string.
Args:
name: a string, the URL to download.
Returns:
a string, which is the content downloaded, or zero length if err.
"""
res = ""
with urllib.request.urlopen(name) as f:
res = f.read().decode('utf-8')
return res
def decode_json(r):
"""Decode the json content, return a list of ipaddress.IPNetworks.
Args:
r: a string of json to decode.
Returns:
a set([]) of ipaddress.IPNetwork objects.
"""
res4 = set([])
res6 = set([])
j = json.loads(r)
for i in j['prefixes']:
if 'ipv4Prefix' in i:
n = i['ipv4Prefix']
res4.add(ipaddress.ip_network(n))
else:
n = i['ipv6Prefix']
res6.add(ipaddress.ip_network(n))
# collapse where possible in this set.
t = set([])
for r in res4:
t = set([i for i in ipaddress.collapse_addresses(list(res4))])
res4 = t
for r in res6:
t = set([i for i in ipaddress.collapse_addresses(list(res6))])
res6 = t
res4.update(res6)
return res4
def main(argv):
"""Slurp up the json files, do set math."""
sets = {}
for d in URLS:
r = get_file(URLS[d])
if r == "":
print("failed to get %s" %URLS[d])
l = decode_json(r)
sets[d] = l
print("Goog - Cloud")
f = sets["goog"] - sets["cloud"]
for p in f:
print("%s" % p)
if __name__ == '__main__':
main(sys.argv)
<file_sep>/README.md
# goog_addressing
Simple tool to parse and output results of the json files of google/cloud address blocks
| 7a79ffe34f30a6b6bb99d18b463a500a70f4433c | [
"Markdown",
"Python"
] | 2 | Python | morrowc/goog_addressing | 3d9bd9f4ae144e4f29373b9e130ba254fbdb6fa0 | 4bc8d6f8404610bd229df5c6d176196615d14974 | |
refs/heads/master | <file_sep>//global variable that will keep track of all dogs
var allDogs = [];
document.addEventListener("DOMContentLoaded", () => {
console.log('connected')
fetch('http://localhost:3000/pups')
.then(response => response.json())
.then(function(dogs){
dogs.forEach(function(dog){
renderDogSpan(dog);
allDogs.push(dog); //pushes all dogs into the global array;
})
});
const filterButton = document.getElementById('good-dog-filter');
filterButton.addEventListener('click', filterGoodDogs);
})
function renderDogSpan(dog){
const dogBar = document.querySelector('#dog-bar'); //container for the spans
let dogSpan = document.createElement('span') //creating span for individual dog
dogSpan.innerText = dog.name //adding the dog name to the spans inner text
dogSpan.id = `dog-${dog.id}` //adding ID incase I need to use it later on
dogSpan.addEventListener('click', renderDogInfo)
dogBar.appendChild(dogSpan); //appending the span to the container
}
function renderDogInfo(event){
const allDogContainer = document.querySelector('#dog-info');
allDogContainer.innerText = "" // <---- acts as resetting the body of the page
const dogContainer = document.createElement('div')
dogContainer.classList.add('card', 'blue-grey', 'darken-1');
dogContainer.id = this.id //setting a unique id for every card for better use.
let dogImg = document.createElement('img');
let dogName = document.createElement('h2');
dogName.classList.add('card-title');
let dogButton = document.createElement('button');
dogButton.classList.add('waves-effect', 'waves-light', 'btn', 'button-style');
dogButton.addEventListener('click', changeDogStatus);
const dogID = this.id.split("-")[1];
//setting the info for all the attributes created. And fetching the information.
fetch(`http://localhost:3000/pups/${dogID}`)
.then(response => response.json())
.then(function(dog){
dogImg.srcset = dog.image;
dogName.innerText = dog.name;
dogButton.innerText = goodOrBad(dog.isGoodDog);
});
//appending everything to the dog container;
dogContainer.appendChild(dogImg);
dogContainer.appendChild(dogName);
dogContainer.appendChild(dogButton)
allDogContainer.appendChild(dogContainer);
}
function goodOrBad(dogStatus){
console.log(dogStatus);
if (dogStatus) {
return 'Good Dog!'
} else {
return 'Bad Dog!'
}
}
function changeDogStatus(){
let dogToUpate = this.parentElement.id.split("-")[1];
fetch(`http://localhost:3000/pups/${dogToUpate}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify({
isGoodDog: switchBehavior(this.innerText)
})
})
.then(response => response.json())
.then(function(dog){
updateDogDom(dog);
});
}
function switchBehavior(dogStatus){
if (dogStatus === "GOOD DOG!") {
return false;
} else if (dogStatus === "BAD DOG!") {
return true;
}
}
function updateDogDom(dog){
let dogCard = document.querySelector(`.btn`);
if (dogCard.innerText === "GOOD DOG!"){
dogCard.innerText = "BAD DOG!"
} else if (dogCard.innerText === "BAD DOG!"){
dogCard.innerText = "GOOD DOG!"
}
}
function filterGoodDogs(){
console.log('filtered button hit')
let filterOption = event.target.innerText.split(':')[1]
const dogBar = document.querySelector('#dog-bar');
if (filterOption === " OFF"){
event.target.innerText = "Filter good dogs: ON"
let goodDogArray = allDogs.filter(function(dog){
return dog.isGoodDog === true;
})
dogBar.innerText = "" //reset the span
goodDogArray.forEach(function(dog){
renderDogSpan(dog)
});
} else {
event.target.innerText = "Filter good dogs: OFF"
filterAllDogs();
}
}
function filterAllDogs(){
const dogBar = document.querySelector('#dog-bar');
dogBar.innerText = "" //reset the span
allDogs.forEach(function(dog){
renderDogSpan(dog);
})
} | 6cc29b1c88c74c92ba860b8e60a0bfc840a116e6 | [
"JavaScript"
] | 1 | JavaScript | Nihaprezz/woof-woof-js-practice-dc-web-091619 | abce023b29dc2720036690b9a18cdbe1ff789ca3 | 78b9a53c2309e792c1cf358f4d8c803248f0521c | |
refs/heads/master | <repo_name>juusolonen/project<file_sep>/main.js
const express = require('express');
const app = express();
//oma moduuli
const admin = require('./models/admin');
const bodyParser = require('body-parser');
const session = require('express-session');
const crypto = require('crypto');
//oma moduuli
const mailer = require('./models/mailer');
const portti = 3113;
//sessio asetukset
app.use(session({
secret : 'TamaOnkinTosiHankalaArvata1DLolOnpas111Hauskss7',
resave : false,
saveUninitialized : false }))
//bodyparser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended' : true}));
//ejs
app.set('views', './views');
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/', (req, res) => {
res.render('index', {'kayttaja' : req.session.kayttaja});
})
app.get('/blogi', (req, res) => {
admin.haeBlogitekstit((tekstit) => {
res.render('blogi', {'kayttaja' : req.session.kayttaja, 'tekstit' : tekstit, 'virhe' : null});
})
})
//tähän ei ole sivustolla suoraa linkkiä koska vain adminin käyttöön
app.get('/yllapito', (req, res) => { //olisi voinut nimetä varmaan myös loginiksi..
if(!req.session.loggedIn) { //sessiomuuttujalla tarkistetaan onko kirjautuneena kukaan
res.render('yllapito', {'virhe' : null});
}else{
res.redirect('/adminpage');
}
})
app.post('/login', (req, res) => {
//haetaan kannasta
admin.haeKayttaja(req.body.tunnus, (tunnus) => {
//annettu salasana hashiksi
let hash = crypto.createHash("SHA512").update(req.body.salasana).digest("hex");
if(tunnus[0]) { //mysql query palauttaa aina arrayn, vaikka tyhjän
if (hash == tunnus[0].salasana) {
console.log("Salasana oikein")
req.session.loggedIn = true; //asetetaan kirjautuminen voimaan
req.session.kayttaja = req.body.tunnus; //kirjautuneen käyttäjän tunnus talteen
res.redirect('/adminpage');
}else{
req.session.loggedIn = false;
res.render('yllapito', {'virhe' : 'Virheellinen käyttäjätunnus tai salasana'});
}
}else {
res.render('yllapito', {'virhe' : 'Virheellinen käyttäjätunnus tai salasana'});
}
})
})
app.get('/logout', (req, res) => {
req.session.loggedIn = false;
req.session.kayttaja = null;
res.redirect('/');
})
app.get('/lisaauusi', (req, res) => {
if(!req.session.kayttaja) {
res.redirect('/');
} else {
res.render('lisaauusi', {'kayttaja' : req.session.kayttaja, 'virhe' : null});
}
})
app.post('/lisaauusi', (req, res) => {
admin.lisaaBlogiTeksti(req.body, (virhe) => {
if (virhe) {
res.render('lisaauusi', {'kayttaja' : req.session.kayttaja, 'virhe' : virhe});
} else {
res.redirect('/blogi');
}
})
})
app.get('/adminpage', (req, res) => {
if(!req.session.loggedIn) { //jos kukaan ei ole kirjautuneen, ohjataan login-ruutuun
res.redirect('/yllapito');
} else {
res.render('adminpage', {'kayttaja' : req.session.kayttaja})
}
})
app.get('/lomake', (req, res) => {
res.render('lomake', {'kayttaja' : null, 'ilmoitus' : null})
})
app.post('/lomake', (req, res) => {
mailer.lahetaEmail(req.body, (ilmoitus) => {
res.render('lomake', {'kayttaja' : null, 'ilmoitus' : ilmoitus})
})
})
app.listen(portti, () => {
console.log(`Palvelin käynnissä portissa ${portti}`);
})<file_sep>/README.txt
Kotisivuprojektini vanha/alkuperäinen koodipohja. Nykyinen versio nähtävissä osoitteessa jsolo.net
Näin käynnistät tämän localhostissa:
SQL-dumppi löytyy /models/harkkasivu.sql
Luo kanta ja taulut dumpin avulla.
Avaa komentorivi projektikansioon -> node main -> enter
Toimii localhostissa portissa 3113
<file_sep>/models/mailer.js
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
host : 'smtp.office365.com',
port : 587,
secure : false,
auth : {
user: "oma sähköposti", //muuta
pass: "<PASSWORD>" //muuta
},
tls : {
rejectUnauthorized : false
},
requireTLS : true
},
{
from: "lähettäjä = oma sähköposti", //muuta
to: "vastaanottaja", //muuta
subject: "Yhteydenotto verkkosivulta",
})
module.exports = {
'lahetaEmail' : (lomaketiedot, callback) => {
let viesti = `
${lomaketiedot.nimi} </br>
${lomaketiedot.organisaatio} </br>
${lomaketiedot.email} </br>
${lomaketiedot.puh} </br> </br> </br>
${lomaketiedot.viesti}
`;
var message = {
text: viesti,
html: viesti,
replyTo: lomaketiedot.email,
headers : {date: new Date()}
};
transporter.sendMail(message, (err) => {
if (err) {
console.log(err)
callback('Viestiä ei saatu lähetettyä!')
} else {
callback('Viesti lähetetty onnistuneesti!')
}
});
}
}<file_sep>/models/harkkasivu.sql
-- phpMyAdmin SQL Dump
-- version 4.8.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: 08.01.2020 klo 16:25
-- Palvelimen versio: 10.1.37-MariaDB
-- PHP Version: 7.3.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `harkkasivu`
--
CREATE DATABASE IF NOT EXISTS `harkkasivu` DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci;
USE `harkkasivu`;
-- --------------------------------------------------------
--
-- Rakenne taululle `blogi`
--
CREATE TABLE `blogi` (
`id` int(11) NOT NULL,
`otsikko` text COLLATE utf8_swedish_ci NOT NULL,
`sisalto` text COLLATE utf8_swedish_ci NOT NULL,
`pvm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci;
--
-- Vedos taulusta `blogi`
--
INSERT INTO `blogi` (`id`, `otsikko`, `sisalto`, `pvm`) VALUES
(1, 'Tämä onkin testipostaus!', 'Tähän vaikka Lorem ipsumia:\r\n\r\n\r\nLorem ipsum\r\nLorem ipsum\r\nLorem ipsum\r\nLorem ipsum\r\nLorem ipsum\r\nLorem ipsum\r\nLorem ipsum\r\nLorem ipsum\r\nLorem ipsum\r\nLorem ipsum', '2020-01-04 13:39:55'),
(2, 'Tämäpä onkin toinen samanmoinen', '\r\nHiiohoi ja hopsikopsis \r\nHiiohoi ja hopsikopsis \r\nHiiohoi ja hopsikopsis ', '2020-01-07 19:35:24'),
(19, 'asffasafsfas', '<p>asafafsfasfas</p>', '2020-01-07 20:50:48'),
(22, 'Juuso lähtee nukkumaan', '<ol><li><strong>Voihan </strong><em>Perjantai</em></li><li><em>Tai </em><strong>Torstai</strong></li><li><strong><em>KESKIVIIKKO</em></strong></li></ol>', '2020-01-07 20:55:43'),
;
-- --------------------------------------------------------
--
-- Rakenne taululle `tunnukset`
--
CREATE TABLE `tunnukset` (
`id` int(11) NOT NULL,
`tunnus` varchar(12) COLLATE utf8_swedish_ci NOT NULL,
`salasana` text COLLATE utf8_swedish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci;
--
-- Vedos taulusta `tunnukset`
--
INSERT INTO `tunnukset` (`id`, `tunnus`, `salasana`) VALUES
(2, 'testitunnus', '0b006251c563ea80622891f5ba2a4cd90d3fcb40bd9937541876a1effbc49293fb36e742e27365b21026afcf66<KEY>');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `blogi`
--
ALTER TABLE `blogi`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `tunnukset`
--
ALTER TABLE `tunnukset`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `blogi`
--
ALTER TABLE `blogi`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27;
--
-- AUTO_INCREMENT for table `tunnukset`
--
ALTER TABLE `tunnukset`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 8245d4689866acde4d5538ba724862a0eda10848 | [
"JavaScript",
"SQL",
"Text"
] | 4 | JavaScript | juusolonen/project | 78f85a7e23d0c58ca3efe2b5f0f56fc4dccc60f4 | ffcfb1f49d005f02bb3dc7841ed0ff2f19ab0b72 | |
refs/heads/master | <repo_name>wadadones/ET<file_sep>/1108_R/Operator/Operator.cpp
// Operator.cpp
#include "Operator.hpp"
//�J�E���g�A�b�v����
#define COUNT_TIME 4
//�^�X�N���~����
#define SLEEP_TIME 3
//�R���X�g���N�^
Operator::Operator(EV3* ev3, Balancer* balancer, Schedule* schedule)
{
this->ev3 = ev3;
this->balancer = balancer;
this->schedule = schedule;
}
void Operator::run()
{
//���s���t�F�[�Y�̃|�C���^
Phase* currentPhase;
//�e�t�F�[�Y�̌o�ߎ���
int time;
//�Z���T�����̓���
int32_t motor_ang_l;
int32_t motor_ang_r;
int color;
int gyro;
int sonic;
int volt;
//���[�^�ւ̏o��
signed char pwm_L;
signed char pwm_R;
signed int ang_T;
//EV3�̐ݒ�
ev3->setUpEV3();
//�X�^�[�g�w���҂�
ev3->waitForStart();
//�Z���T�̃��Z�b�g
ev3->resetSensorValue();
//�|�����s���C�u�����̏�����
balancer->init();
while(schedule->isEmpty()){
//���̃t�F�[�Y�������o��
currentPhase = schedule->popPhase();
//�t�F�[�Y�̏�������
currentPhase->initialize();
//�^�C�}�[�̃��Z�b�g
time = 0;
//�X�^�[�g�ʒm
ev3->playTone();
do{
//�Z���T�������͂��Ⴄ
ev3->getSensorValue(&motor_ang_l, &motor_ang_r, &color, &gyro, &sonic, &volt);
//���͒l�����o�͒l���t�F�[�Y���Ƃ̕��@�ŎZ�o
currentPhase->calculate(time, motor_ang_l, motor_ang_r, color, gyro, sonic, volt, &pwm_L, &pwm_R, &ang_T);
//���[�^�ɏo�͂��n��
ev3->setMotorValue(pwm_L, pwm_R, ang_T);
//���₷��
ev3->sleep(SLEEP_TIME);
//�^�C�}�[�̃C���N�������g
time += COUNT_TIME;
//�����̃{�^���ŏI��
if(ev3->buttonIsPressed()) break;
}while(!currentPhase->isFinished(time, motor_ang_l, motor_ang_r, color, gyro, sonic, volt, pwm_L, pwm_R, ang_T));
//�����̃{�^����ry
if(ev3->buttonIsPressed()) break;
}
//�I���ʒm
ev3->playTone();
//EV3�̏I������
ev3->shutDownEV3();
return;
}
<file_sep>/1108_L/EV3/EV3.cpp
// EV3.cpp
#include "EV3.hpp"
/*?Z???T?[?????????`?????*/
static const sensor_port_t
touch_sensor = EV3_PORT_1,
sonar_sensor = EV3_PORT_2,
color_sensor = EV3_PORT_3,
gyro_sensor = EV3_PORT_4;
/*???[?^?????????`?????*/
static const motor_port_t
left_motor = EV3_PORT_C,
right_motor = EV3_PORT_B,
tail_motor = EV3_PORT_A;
/* LCD?t?H???g?T?C?Y */
#define CALIB_FONT (EV3_FONT_SMALL)
#define CALIB_FONT_WIDTH (6/*TODO: magic number*/)
#define CALIB_FONT_HEIGHT (8/*TODO: magic number*/)
/* ???S???~????p?x[?x] */
#define TAIL_ANGLE_STAND_UP 98
/* ???S???~?p???[?^?????????W?? */
#define P_GAIN 2.5F
/* ???S???~?p???[?^????PWM???????l */
#define PWM_ABS_MAX 60
/* ?g?[??????? */
#define TONE_F 500
/* ?g?[??????? */
#define TONE_T 1000
/* Bluetooth?t?@?C???n???h?? */
static FILE *bt = NULL;
/* Bluetooth?R?}???h 1:?????[?g?X?^?[?g */
static int bt_cmd = 0;
void EV3::setUpEV3()
{
/* ?Z???T?[????|?[?g???? */
ev3_sensor_config(sonar_sensor, ULTRASONIC_SENSOR);
ev3_sensor_config(color_sensor, COLOR_SENSOR);
ev3_color_sensor_get_reflect(color_sensor); /* ????????[?h */
ev3_sensor_config(touch_sensor, TOUCH_SENSOR);
ev3_sensor_config(gyro_sensor, GYRO_SENSOR);
/* ???[?^?[?o??|?[?g???? */
ev3_motor_config(left_motor, LARGE_MOTOR);
ev3_motor_config(right_motor, LARGE_MOTOR);
ev3_motor_config(tail_motor, LARGE_MOTOR);
ev3_motor_set_power(tail_motor, -30);
tslp_tsk(1000);
ev3_motor_reset_counts(tail_motor);
/* LCD????\?? */
ev3_lcd_fill_rect(0, 0, EV3_LCD_WIDTH, EV3_LCD_HEIGHT, EV3_LCD_WHITE);
int mv = ev3_battery_voltage_mV();
if(mv >= 9000){
ev3_lcd_draw_string("over 9000", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 8900){
ev3_lcd_draw_string("over 8900", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 8800){
ev3_lcd_draw_string("over 8800", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 8700){
ev3_lcd_draw_string("over 8700", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 8600){
ev3_lcd_draw_string("over 8600", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 8500){
ev3_lcd_draw_string("over 8500", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 8400){
ev3_lcd_draw_string("over 8400", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 8300){
ev3_lcd_draw_string("over 8300", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 8200){
ev3_lcd_draw_string("over 8200", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 8100){
ev3_lcd_draw_string("over 8100", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 8000){
ev3_lcd_draw_string("over 8000", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 7900){
ev3_lcd_draw_string("over 7900", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 7800){
ev3_lcd_draw_string("over 7800", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 7700){
ev3_lcd_draw_string("over 7700", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 7600){
ev3_lcd_draw_string("over 7600", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 7500){
ev3_lcd_draw_string("over 7500", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 7400){
ev3_lcd_draw_string("over 7400", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 7300){
ev3_lcd_draw_string("over 7300", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 7200){
ev3_lcd_draw_string("over 7200", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 7100){
ev3_lcd_draw_string("over 7100", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 7000){
ev3_lcd_draw_string("over 7000", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 6900){
ev3_lcd_draw_string("over 6900", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 6800){
ev3_lcd_draw_string("over 6800", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 6700){
ev3_lcd_draw_string("over 6700", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 6600){
ev3_lcd_draw_string("over 6600", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 6500){
ev3_lcd_draw_string("over 6500", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 6400){
ev3_lcd_draw_string("over 6400", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 6300){
ev3_lcd_draw_string("over 6300", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 6200){
ev3_lcd_draw_string("over 6200", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 6100){
ev3_lcd_draw_string("over 6100", 0, CALIB_FONT_HEIGHT*1);
}else if(mv >= 6000){
ev3_lcd_draw_string("over 6000", 0, CALIB_FONT_HEIGHT*1);
} else {
ev3_lcd_draw_string("under 6000", 0, CALIB_FONT_HEIGHT*1);
}
/* Open Bluetooth file */
bt = ev3_serial_open_file(EV3_SERIAL_BT);
assert(bt != NULL);
/* Bluetooth??M?^?X?N??N?? */
act_tsk(BT_TASK);
/* ????????????m */
ev3_led_set_color(LED_ORANGE);
}
void EV3::waitForStart()
{
/* ?X?^?[?g??@ */
int i = TAIL_ANGLE_STAND_UP;
//int flag = 0;
while(1){
ev3_tail_set_angle(i); /* ???S???~?p?p?x????? */
if(ev3_button_is_pressed(UP_BUTTON)){
i--;
while(1){
if(!ev3_button_is_pressed(UP_BUTTON)) break;
}
}
if(ev3_button_is_pressed(DOWN_BUTTON)){
i++;
while(1){
if(!ev3_button_is_pressed(DOWN_BUTTON)) break;
}
}
if (bt_cmd == 1){
break; /* ?????[?g?X?^?[?g */
}
if (ev3_touch_sensor_is_pressed(touch_sensor) == 1){
break; /* ?^?b?`?Z???T???????? */
}
tslp_tsk(10); /* 10msec?E?F?C?g */
}
/* ?X?^?[?g??m */
ev3_led_set_color(LED_GREEN);
}
void EV3::resetSensorValue()
{
/* ???s???[?^?[?G???R?[?_?[???Z?b?g */
ev3_motor_reset_counts(left_motor);
ev3_motor_reset_counts(right_motor);
/* ?W???C???Z???T?[???Z?b?g */
ev3_gyro_sensor_reset(gyro_sensor);
}
void EV3::playTone()
{
ev3_speaker_play_tone(TONE_F, TONE_T);
}
void EV3::getSensorValue(int32_t* motor_ang_l, int32_t* motor_ang_r, int* color, int* gyro, int* sonic, int *volt)
{
*motor_ang_l = ev3_motor_get_counts(left_motor);
*motor_ang_r = ev3_motor_get_counts(right_motor);
*color = ev3_color_sensor_get_reflect(color_sensor);
*gyro = ev3_gyro_sensor_get_rate(gyro_sensor);
*sonic = ev3_ultrasonic_sensor_get_distance(sonar_sensor);
*volt = ev3_battery_voltage_mV();
}
void EV3::setMotorValue(signed char pwm_L, signed char pwm_R, signed int ang_T)
{
if (pwm_L == 0){
ev3_motor_stop(left_motor, true);
}else{
ev3_motor_set_power(left_motor, (int)pwm_L);
}
if (pwm_R == 0){
ev3_motor_stop(right_motor, true);
}else{
ev3_motor_set_power(right_motor, (int)pwm_R);
}
ev3_tail_set_angle(ang_T);
}
void EV3::sleep(int sleep_sec)
{
tslp_tsk(sleep_sec);
}
bool EV3::buttonIsPressed()
{
return ev3_button_is_pressed(BACK_BUTTON);
}
void EV3::shutDownEV3()
{
ev3_motor_stop(left_motor, false);
ev3_motor_stop(right_motor, false);
ter_tsk(BT_TASK);
fclose(bt);
}
void EV3::ev3_tail_set_angle(signed int angle)
{
/* ?????? */
float pwm = (float)(angle - ev3_motor_get_counts(tail_motor))*P_GAIN;
/* PWM?o??O?a???? */
if (pwm > PWM_ABS_MAX){
pwm = PWM_ABS_MAX;
}
else if (pwm < -PWM_ABS_MAX){
pwm = -PWM_ABS_MAX;
}
if (pwm == 0){
ev3_motor_stop(tail_motor, true);
}
else{
ev3_motor_set_power(tail_motor, (signed char)pwm);
}
}
FILE* EV3::getBT()
{
return bt;
}
void EV3::setBTcmd(int cmd)
{
bt_cmd = cmd;
}<file_sep>/1108_L/Phase/GaragePhase/GaragePhase.hpp
// GaragePhase.hpp
#ifndef GARAGE_PHASE_H
#define GARAGE_PHASE_H
#include "../Phase.hpp"
#include "ev3api.h"
#include <string>
class GaragePhase: public Phase {
public:
int diff_prev=20;
int forwardl=60;
int forwardr=60;
int gyrooffset=0;
int offset=0;
int tailangle=3;
int boundary=11;
int boundary2=26;
int cnt=0;
int cnt2=0;
int tim2=0;
int pflag=0;
int endtime;
float Kp = 1.5;
float Kd = 12.00;
int mcntl=0;
int mcntr=0;
int LIGHT_WHITE=30;
int LIGHT_BLACK=0;
int data[300];
int mcntlval;
int mcntrval;
int stoptime;
FILE *fp;
GaragePhase(std::string name, Balancer* balancer);
GaragePhase(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset,int turnoffset,float ikp,float ikd,int itailangle, int setmcntl, int setmcntr, int setstoptime);
void initialize();
void calc_param(int time,int* forward,signed char* turn,int color);
void calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T);
bool isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T);
};
#endif
<file_sep>/1108_L/app.cpp
// app.cpp
#include "ev3api.h"
#include "app.hpp"
#include "app_sub.hpp"
#include "EV3/EV3.hpp"
#include "Balancer/balancer.h"
#include "Balancer/BalancerCPP.hpp"
#include "Operator/Operator.hpp"
#include "Schedule/Schedule.hpp"
#include "Phase/Phase.hpp"
#include "Phase/StartPhase/StartPhase.hpp"
#include "Phase/StraightPhase/StraightPhase.hpp"
#include "Phase/CurvePhase/CurvePhase.hpp"
#include "Phase/DetectGoal/DetectGoal.hpp"
#include "Phase/AfterGoal/AfterGoal.hpp"
#include "Phase/DetectNansho/DetectNansho.hpp"
#include "Phase/LookUpGateHandler/LookUpGateHandler.hpp"
#include "Phase/GaragePhase/GaragePhase.hpp"
#include "Phase/StairPhase/StairPhase.hpp"
#include "Phase/StairPhase2/StairPhase2.hpp"
#include "Phase/StairPhase3/StairPhase3.hpp"
#include "Phase/BeforeStair/BeforeStair.hpp"
#include "Phase/ImmediatePhase/ImmediatePhase.hpp"
//インスタンス作成
EV3 ev3;
Balancer balancer;
Schedule schedule;
Operator ope(&ev3, &balancer, &schedule);
StartPhase st("StartPhase", &balancer, 104);
/*---- stable tuning -----*/
StraightPhase sp1("StraightPhase", &balancer, 50, 70, 1000, 0);
StraightPhase sp3("StraightPhase", &balancer, 70, 70, 2800, 0); //2000 //3000
CurvePhase cp1("CurvePhase", &balancer, 60, 60, 6400, 0, 0, 1.5, 20.0); //2600
CurvePhase cp2("CurvePhase", &balancer, 70, 70, 9400, 0, 0, 1.2, 14.0); //3800
CurvePhase cp3("CurvePhase", &balancer, 55, 55, 11200, 0, 0, 2.0, 20.0);
CurvePhase cp4("CurvePhase", &balancer, 60, 60, 12200, 0, 0, 1.3, 15.0);
StraightPhase spEnd("StraightPhase", &balancer, 70, 70, 14200, 0); //2000
/*------------------------*/
//Stair
AfterGoal ags("AfterGoal", &balancer, 50, 20, 5600, 0, -2, 1.2, 15.0, 3, 92, 3000);
AfterGoal ags2("AfterGoal", &balancer, 20, 0, 1000, 0, -2, 1.2, 15.0, 92, 92, 0);
ImmediatePhase ip("ImmediatePhase", &balancer, 12, 600, 92);
GaragePhase gp2("GaragePhase", &balancer, 30, 30, 114514, 0, 0, 1.7, 0, 92, 3200, 3200, 250);
BeforeStair bs("BeforeStair", &balancer, 85);
StairPhase stair("StairPhase", &balancer);
StairPhase2 stair2("StairPhase", &balancer);
StairPhase3 stair3("StairPhase", &balancer);
//空のスケジュールにPhaseインスタンスをプッシュ
void createSchedule()
{
schedule.pushPhase(&st);
schedule.pushPhase(&sp1);
schedule.pushPhase(&sp3);
schedule.pushPhase(&cp1);
schedule.pushPhase(&cp2);
schedule.pushPhase(&cp3);
schedule.pushPhase(&cp4);
schedule.pushPhase(&spEnd);
schedule.pushPhase(&ags);
schedule.pushPhase(&ags2);
schedule.pushPhase(&ip);
schedule.pushPhase(&gp2);
schedule.pushPhase(&bs);
schedule.pushPhase(&stair);
schedule.pushPhase(&stair2);
schedule.pushPhase(&stair3);
}
/* メインタスク */
void main_task(intptr_t unused)
{
//スケジュールを作って
createSchedule();
//オペレータを走らせて
ope.run();
//おわり
ext_tsk();
}
/*BlueTooth*タスク*/
void bt_task(intptr_t unused)
{
while(1)
{
uint8_t c = fgetc(ev3.getBT()); /* 受信 */
switch(c)
{
case '1':
ev3.setBTcmd(1);
break;
default:
break;
}
fputc(c, ev3.getBT()); /* エコーバック */
}
}
<file_sep>/1108_R/app.hpp
/*
* TOPPERS/ASP Kernel
* Toyohashi Open Platform for Embedded Real-Time Systems/
* Advanced Standard Profile Kernel
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2010 by Embedded and Real-Time Systems Laboratory
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)?(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: sample1.h 2416 2012-09-07 08:06:20Z ertl-hiro $
*/
/*
* サンプルプログラム(1)のヘッダファイル
*/
#ifdef __cplusplus
extern "C" {
#endif
/*
* ターゲット依存の定義
*/
#include "target_test.h"
/*
* 各タスクの優先度の定義
*/
#define MAIN_PRIORITY 5 /* メインタスクの優先度 */
/* HIGH_PRIORITYより高くすること */
#define HIGH_PRIORITY 9 /* 並行実行されるタスクの優先度 */
#define MID_PRIORITY 10
#define LOW_PRIORITY 11
/*
* ターゲットに依存する可能性のある定数の定義
*/
#ifndef TASK_PORTID
#define TASK_PORTID 1 /* 文字入力するシリアルポートID */
#endif /* TASK_PORTID */
#ifndef STACK_SIZE
#define STACK_SIZE 4096 /* タスクのスタックサイズ */
#endif /* STACK_SIZE */
/*
* 関数のプロトタイプ宣言
*/
#ifndef TOPPERS_MACRO_ONLY
extern void main_task(intptr_t exinf);
extern void bt_task(intptr_t exinf);
#endif /* TOPPERS_MACRO_ONLY */
#ifdef __cplusplus
}
#endif
<file_sep>/1108_R/Phase/AfterGoal/AfterGoal.cpp
// AfterGoal.cpp
#include "AfterGoal.hpp"
#define LIGHT_WHITE 40
#define LIGHT_BLACK 0
#define TAIL_ANGLE_DRIVE 15
AfterGoal::AfterGoal(std::string name, Balancer* balancer) : Phase(name, balancer)
{
}
AfterGoal::AfterGoal(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset,int turnoffset,float ikp,float ikd,int setangle1, int setangle2, int setgraytime) : Phase(name, balancer)
{
forwardl=setforwardl;
forwardr=setforwardr;
endtime=setending;
gyrooffset=gyoffset;
offset=turnoffset;
Kp = ikp;
Kd = ikd;
beforeangle=setangle1;
afterangle=setangle2;
graytime = setgraytime;
}
void AfterGoal::initialize()
{
fp=fopen("aftergoal.csv","w");
if(fp==NULL){
printf("failed\n");
return;
}
fprintf(fp,"time,color,turn,gyro,volt,mtL,mtR\n");
balancer->change_offset(gyrooffset);
}
void AfterGoal::calc_param(int time,int* forward,signed char* turn,int color){
int diff_p = 0;
if(time <= graytime){
diff_p = std::min(color,LIGHT_WHITE)-(LIGHT_WHITE+15)/2;
}else{
diff_p = std::min(color,LIGHT_WHITE)-(LIGHT_WHITE+0)/2;
}
int diff_d = diff_p-(diff_prev);
diff_prev=diff_p;
int val=(Kp*diff_p+diff_d*Kd)/2;
if(time==0)val=(Kp*diff_p)/2;
(*turn)=(signed char)val;
(*turn)+=offset;
if(*turn<-50)
*turn=-50;
if(*turn>50)
*turn=50;
}
void AfterGoal::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
int forward=forwardl+(forwardr-forwardl)*time/endtime;
signed char turn;
calc_param(time,&forward,&turn,color);
balancer->setCommand((signed char)forward, turn);
balancer->update(gyro, motor_ang_r, motor_ang_l, volt);
*pwm_L = balancer->getPwmLeft();
*pwm_R = balancer->getPwmRight();
*ang_T = beforeangle + (afterangle - beforeangle)*time/endtime;
fprintf(fp,"%d,%d,%d,%d,%d,%d,%d\n",time,color,(int)turn,gyro,volt,(int)*pwm_L,(int)*pwm_R);
}
bool AfterGoal::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
if (endtime==-1 && sonic<33 && sonic>=0)return true;
if(endtime>=0 && endtime<=time)return true;
return false;
}
<file_sep>/1108_L/Phase/Phase.cpp
// Phase.cpp
#include "Phase.hpp"
Phase::Phase(std::string name, Balancer* balancer)
{
this->name = name;
this->balancer = balancer;
}
std::string Phase::getName()
{
return name;
}
<file_sep>/1108_R/Makefile.inc
mkfile_path := $(dir $(lastword $(MAKEFILE_LIST)))
# Add o.file written in C
APPL_COBJS += \
balancer.o \
balancer_param.o \
# Add o.file written in C++
APPL_CXXOBJS += \
BalancerCPP.o \
Operator.o \
EV3.o \
Schedule.o \
Phase.o \
StartPhase.o \
StraightPhase.o \
CurvePhase.o \
DetectGoal.o \
DetectNansho.o \
LookUpGateHandler.o \
StairPhase.o \
StairPhase2.o \
StairPhase3.o \
AfterGoal.o \
GaragePhase.o \
SRCLANG := c++
ifdef CONFIG_EV3RT_APPLICATION
# Include libraries
include $(EV3RT_SDK_LIB_DIR)/libcpp-ev3/Makefile
endif
# Add directory has .c or .cpp files
APPL_DIR += \
$(mkfile_path)Balancer \
$(mkfile_path)Operator \
$(mkfile_path)EV3 \
$(mkfile_path)Schedule \
$(mkfile_path)Phase \
$(mkfile_path)Phase/StartPhase \
$(mkfile_path)Phase/StraightPhase \
$(mkfile_path)Phase/CurvePhase \
$(mkfile_path)Phase/DetectGoal \
$(mkfile_path)Phase/DetectNansho \
$(mkfile_path)Phase/LookUpGateHandler \
$(mkfile_path)Phase/StairPhase \
$(mkfile_path)Phase/StairPhase2 \
$(mkfile_path)Phase/StairPhase3 \
$(mkfile_path)Phase/AfterGoal \
$(mkfile_path)Phase/GaragePhase \
# Add directory has .h or .hpp files
INCLUDES += \
-I$(mkfile_path)Balancer \
-I$(mkfile_path)Operator \
-I$(mkfile_path)EV3 \
-I$(mkfile_path)Schedule \
-I$(mkfile_path)Phase \
-I$(mkfile_path)Phase/StartPhase \
-I$(mkfile_path)Phase/StraightPhase \
-I$(mkfile_path)Phase/CurvePhase \
-I$(mkfile_path)Phase/DetectGoal \
-I$(mkfile_path)Phase/DetectNansho \
-I$(mkfile_path)Phase/LookUpGateHandler \
-I$(mkfile_path)Phase/StairPhase \
-I$(mkfile_path)Phase/StairPhase2 \
-I$(mkfile_path)Phase/StairPhase3 \
-I$(mkfile_path)Phase/AfterGoal \
-I$(mkfile_path)Phase/GaragePhase \
<file_sep>/1108_R/Phase/StartPhase/StartPhase.hpp
// /*TemplatePhase*/.hpp
#ifndef START_PAHSE
#define START_PHASE
#include "../Phase.hpp"
#include <string>
class StartPhase: public Phase {
public:
StartPhase(std::string name, Balancer* balancer);
StartPhase(std::string name, Balancer* balancer,int angle);
void initialize();
void calc_param(signed char* forward,signed char* turn,int color);
void calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T);
bool isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T);
private:
int ang;
};
#endif
<file_sep>/1108_R/Phase/LookUpGateHandler/LookUpGateHandler.hpp
// /*TemplatePhase*/.hpp
#ifndef LOOK_UP_GATE_HANDLER_H
#define LOOK_UP_GATE_HANDLER_H
#include "../Phase.hpp"
#include <string>
#include <array>
#include "ev3api.h"
class LookUpGateHandler: public Phase {
public:
LookUpGateHandler(std::string name, Balancer* balancer);
void initialize();
void calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T);
bool isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T);
};
#endif
<file_sep>/1108_R/Phase/StairPhase2/StairPhase2.hpp
// StairPhase2.hpp
#ifndef STAIR_PHASE2_H
#define STAIR_PHASE2_H
#include "../Phase.hpp"
#include <string>
class StairPhase2: public Phase {
public:
int diff_prev=20;
int forwardl=60;
int forwardr=60;
int gyrooffset=0;
int endtime=5000;
StairPhase2(std::string name, Balancer* balancer);
StairPhase2(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset);
void initialize();
void calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T);
bool isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T);
};
#endif<file_sep>/1108_L/Phase/ImmediatePhase/ImmediatePhase.cpp
// ImmediatePhase.cpp
#include "ImmediatePhase.hpp"
ImmediatePhase::ImmediatePhase(std::string name, Balancer* balancer) : Phase(name, balancer)
{
/*�R���X�g���N�^*/;
}
ImmediatePhase::ImmediatePhase(std::string name, Balancer* balancer, int setforward, int settime, int setangle) : Phase(name, balancer)
{
forward = setforward;
endtime = settime;
angle = setangle;
}
void ImmediatePhase::initialize()
{
/*��������*/;
}
void ImmediatePhase::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
/*�Z���T�����̓��͂����ƂɃ��[�^�ւ̏o�͂��v�Z����*/
*pwm_L = forward;
*pwm_R = forward;
*ang_T = angle;
}
bool ImmediatePhase::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
/*�I������������true,�������Ȃ�����false*/
if(time <= endtime)
return false;
else
return true;
}
<file_sep>/1108_R/Phase/CurvePhase/CurvePhase.hpp
// StraightPhase.hpp
#ifndef CURVE_PHASE_H
#define CURVE_PHASE_H
#include "../Phase.hpp"
#include <string>
class CurvePhase: public Phase {
public:
int diff_prev=20;
int forwardl=60;
int forwardr=60;
int gyrooffset=0;
int offset=0;
int endtime=5000;
float Kp = 1.5;
float Kd = 12.00;
//FILE *fp;
CurvePhase(std::string name, Balancer* balancer);
CurvePhase(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset,int turnoffset,float ikp,float ikd);
void initialize();
void calc_param(int time,int* forward,signed char* turn,int color);
void calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T);
bool isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T);
};
#endif
<file_sep>/1108_L/Phase/StartPhase/StartPhase.cpp
// /*TemplatePhase*/.cpp
#include "StartPhase.hpp"
#define LIGHT_WHITE 40
#define LIGHT_BLACK 0
StartPhase::StartPhase(std::string name, Balancer* balancer) : Phase(name, balancer)
{
}
StartPhase::StartPhase(std::string name, Balancer* balancer,int angle) : Phase(name, balancer)
{
ang=angle;
}
void StartPhase::initialize()
{
balancer->change_offset(0);
}
void StartPhase::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
*pwm_L = 0;
*pwm_R = 0;
*ang_T = ang;
}
bool StartPhase::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
/*?I??????? ?????true,?????????????false*/
if(time <= 200)
return false;
else
return true;
}
<file_sep>/1108_L/Phase/Phase.hpp
// Phase.h
#ifndef PHASE_H
#define PHASE_H
#include "../Balancer/BalancerCPP.hpp"
#include <string>
class Phase {
protected:
std::string name;
Balancer* balancer;
public:
Phase(std::string name, Balancer* balancer);
std::string getName();
virtual void initialize() = 0;
virtual void calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T) = 0;
virtual bool isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T) = 0;
};
#endif
<file_sep>/1108_R/Phase/DetectGoal/DetectGoal.hpp
// DetectGoal.hpp
#ifndef DETECTGOAL_H
#define DETECTGOAL_H
#include "../Phase.hpp"
#include <string>
class DetectGoal: public Phase {
public:
int cnt;
int diff_prev=20;
int forwardl=60;
int forwardr=60;
int gyrooffset=0;
int mxsptime=5000;
int data[100];
FILE *fp;
DetectGoal(std::string name, Balancer* balancer);
DetectGoal(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int maxspeedtime,int gyoffset);
void initialize();
void calc_param(int time,int* forward,signed char* turn,int color);
void calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T);
bool isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T);
};
#endif
<file_sep>/1108_L/Phase/StairPhase3/StairPhase3.cpp
// StairPhase3.cpp
#include "StairPhase3.hpp"
StairPhase3::StairPhase3(std::string name, Balancer* balancer) : Phase(name, balancer)
{
}
void StairPhase3::initialize()
{
balancer->change_offset(0);
}
StairPhase3::StairPhase3(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset) : Phase(name, balancer)
{
forwardl=setforwardl;
forwardr=setforwardr;
endtime=setending;
gyrooffset=gyoffset;
}
void StairPhase3::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
if(time <= 500){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 78;
}else if(time <= 1500){
*pwm_L = 8;
*pwm_R = 8;
*ang_T = 78;
}else if(time <= 2000){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 82;
}else if(time <= 3000){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 82;
}else if(time<10000){
*pwm_L = 25;
*pwm_R = 25;
*ang_T =78;
}
}
bool StairPhase3::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
if (time <= 10800)
return false;
else
return true;
}<file_sep>/1108_R/Phase/StairPhase3/StairPhase3.cpp
// StairPhase3.cpp
#include "StairPhase3.hpp"
StairPhase3::StairPhase3(std::string name, Balancer* balancer) : Phase(name, balancer)
{
}
void StairPhase3::initialize()
{
balancer->change_offset(0);
}
StairPhase3::StairPhase3(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset) : Phase(name, balancer)
{
forwardl=setforwardl;
forwardr=setforwardr;
endtime=setending;
gyrooffset=gyoffset;
}
void StairPhase3::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
if(time <= 1000){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 78;
}else if(time <= 2000){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 88;
}else if(time <= 3000){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 91;
}else if(time <= 4000){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 94;
}else if(time <= 5000){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 96;
}else if(time <= 6000){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 98;
}else if(time <= 7000){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 100;
}else if(time <= 30000){
balancer->setCommand(15, 0);
balancer->update(gyro, motor_ang_r, motor_ang_l, volt);
*pwm_L = balancer->getPwmRight();
*pwm_R = balancer->getPwmLeft();
*ang_T = 30;
}
}
bool StairPhase3::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
/*終了条件を満たせばtrue,満たさなければfalse*/
if (time <= 30000)
return false;
else
return true;
}
<file_sep>/1108_L/Phase/DetectNansho/DetectNansho.cpp
// /*DetectNansho*/.cpp
// setting-> offset: +10, CMD_MAX=60
#include "DetectNansho.hpp"
#define LIGHT_WHITE 40
#define LIGHT_BLACK 0
#define TAIL_ANGLE_DRIVE 3
DetectNansho::DetectNansho(std::string name, Balancer* balancer) : Phase(name, balancer)
{
}
void DetectNansho::initialize()
{
balancer->change_offset(0);
fp=fopen("log.csv","w");
if(fp==NULL){
printf("failed\n");
return;
}
fprintf(fp,"time,color\n");
cnt=0;
for(int i=0;i<100;i++){
data[i]=0;
}
}
void DetectNansho::calc_param(signed char* forward,signed char* turn,int color){
if(color>=(LIGHT_WHITE+LIGHT_BLACK)/2*1.7){
*turn = 10;
}else if(color>=(LIGHT_WHITE+LIGHT_BLACK)/2){
*turn=2;
}else{
*turn=-2;
}
}
void DetectNansho::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
signed char forward;
signed char turn;
if(time<500)forward=45;
else forward=25;
calc_param(&forward,&turn,color);
fprintf(fp,"%d,%d,%d,%d\n",time,color,(int)forward,(int)turn);
balancer->setCommand(forward, turn);
balancer->update(gyro, motor_ang_r, motor_ang_l, volt);
*pwm_L = balancer->getPwmRight();
*pwm_R = balancer->getPwmLeft();
*ang_T = 80;
}
bool DetectNansho::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
int Graymin=17;
int Graymax=27;
int tim=time/4;
if(tim>=1000){
if(tim>=1100){
cnt-=(data[tim%100]>=Graymin && data[tim%100]<=Graymax)?1:0;
}
data[tim%100]=color;
cnt+=(data[tim%100]>=Graymin && data[tim%100]<=Graymax)?1:0;
if(tim>=1100 && cnt>=50){
return true;
}
}
return false;
}
<file_sep>/1108_L/Phase/ImmediatePhase/ImmediatePhase.hpp
// ImmediatePhase.hpp
#ifndef IMMEDIATE_PHASE_H
#define IMMEDIATE_PHASE_H
#include "../Phase.hpp"
#include <string>
class ImmediatePhase: public Phase {
public:
int forward;
int endtime;
int angle;
ImmediatePhase(std::string name, Balancer* balancer);
ImmediatePhase(std::string name, Balancer* balancer, int setforward, int settime, int setangle);
void initialize();
void calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T);
bool isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T);
};
#endif
<file_sep>/1108_R/Phase/TightCurve/TightCurve.cpp
// TightCurve.cpp
#include "TightCurve.hpp"
#define LIGHT_WHITE 40
/* 黒色の光センサ値 */
#define LIGHT_BLACK 0
/* バランス走行時の角度[度] */
#define TAIL_ANGLE_DRIVE 3
TightCurve::TightCurve(std::string name, Balancer* balancer) : Phase(name, balancer)
{
}
void TightCurve::initialize()
{
fp=fopen("tightcurvelog.csv","w");
if(fp==NULL){
printf("failed\n");
return;
}
fprintf(fp,"time,color,turn,gyro,volt,mtL,mtR\n");
balancer->change_offset(gyrooffset);
}
TightCurve::TightCurve(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset) : Phase(name, balancer)
{
forwardl=setforwardl;
forwardr=setforwardr;
endtime=setending;
gyrooffset=gyoffset;
}
void TightCurve::calc_param(int time,int* forward,signed char* turn,int color){
const float Kp = 1.13;
const float Kd = 10.00;
int offset=-2;
int diff_p = std::min(color,LIGHT_WHITE)-(LIGHT_WHITE+LIGHT_BLACK)/2;
int diff_d = diff_p-(diff_prev);
diff_prev=diff_p;
int val=(Kp*diff_p+diff_d*Kd)/2;
if(time==0)val=(Kp*diff_p)/2;
(*turn)=(signed char)val;
(*turn)+=offset;
(*turn)*=-1;
if(*turn<-12){
*turn=-12;
}
if(*turn>12){
*turn=12;
}
}
void TightCurve::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
/*センサからの入力をもとにモータへの出力を計算する*/
/*turn = 1の2値制御*/
int forward=forwardl+(forwardr-forwardl)*time/endtime;
signed char turn;
calc_param(time,&forward,&turn,color);
balancer->setCommand((signed char)forward, turn);
balancer->update(gyro, motor_ang_r, motor_ang_l, volt);
*pwm_L = balancer->getPwmRight();
*pwm_R = balancer->getPwmLeft();
*ang_T = TAIL_ANGLE_DRIVE;
fprintf(fp,"%d,%d,%d,%d,%d,%d,%d\n",time,color,(int)turn,gyro,volt,(int)*pwm_L,(int)*pwm_R);
}
bool TightCurve::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
/*終了条件を満たせばtrue,満たさなければfalse*/
if (time <= endtime)
return false;
else
return true;
}
<file_sep>/1108_L/Phase/_TemplatePhase/TemplatePhase.cpp
// /*TemplatePhase*/.cpp
#include "/*TemplatePhase*/.hpp"
/*TemplatePhase*/::/*TemplatePhase*/(std::string name, Balancer* balancer) : Phase(name, balancer)
{
/*コンストラクタ*/;
}
void /*TemplatePhase*/::initialize()
{
/*初期処理*/;
}
void /*TemplatePhase*/::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
/*センサからの入力をもとにモータへの出力を計算する*/
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 0;
}
bool /*TemplatePhase*/::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
/*終了条件を満たせばtrue,満たさなければfalse*/
if(1)
return false;
else
return true;
}
<file_sep>/1108_R/EV3/EV3.hpp
// EV3.h
#ifndef EV3_H
#define EV3_H
#include "ev3api.h"
class EV3 {
private:
void ev3_tail_set_angle(signed int angle);
public:
void setUpEV3();
void waitForStart();
void resetSensorValue();
void playTone();
void getSensorValue(int32_t* motor_ang_l, int32_t* motor_ang_r, int* color, int* gyro, int* sonic, int* volt);
void setMotorValue(signed char pwm_L, signed char pwm_R, signed int ang_T);
void sleep(int sleep_sec);
bool buttonIsPressed();
void shutDownEV3();
FILE* getBT();
void setBTcmd(int cmd);
};
#endif
<file_sep>/1108_L/Operator/Operator.hpp
// Operator.h
#ifndef OPERATOR_H
#define OPERATOR_H
#include "../EV3/EV3.hpp"
#include "../Balancer/BalancerCPP.hpp"
#include "../Schedule/Schedule.hpp"
#include "../Phase/Phase.hpp"
class Operator {
private:
EV3* ev3;
Balancer* balancer;
Schedule* schedule;
public:
Operator(EV3* ev3, Balancer* balancer, Schedule* schedule);
void run();
};
#endif
<file_sep>/1108_R/Schedule/Schedule.cpp
// Schedule.cpp
#include "Schedule.hpp"
void Schedule::pushPhase(Phase* phase)
{
queue.push(phase);
}
Phase* Schedule::popPhase()
{
Phase* phase = queue.front();
queue.pop();
return phase;
}
bool Schedule::isEmpty()
{
return !queue.empty();
}
<file_sep>/1108_R/Schedule/Schedule.hpp
// Schedule.h
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include "../Phase/Phase.hpp"
#include <queue>
class Schedule {
private:
std::queue<Phase*> queue;
public:
void pushPhase(Phase* phase);
Phase* popPhase();
bool isEmpty();
};
#endif
<file_sep>/1108_L/Phase/LookUpGateHandler/LookUpGateHandler.cpp
#include "LookUpGateHandler.hpp"
#define TAIL_ANGLE_STAND_UP 93
#define TAIL_ANGLE_DRIVE 15
#define TAIL_ANGLE_LUG 70
#define MOTOR_FORWARD 7
#define MOTOR_STOP 0
#define MOTOR_FORWARD_SLOW 2
#define MOTOR_BACKWARD_SLOW -2
#define TIME_SECTION 5175
#define LINE_TRACE 4
#define LIGHT_WHITE 6
#define LIGHT_BLACK 0
#define MUSIC_DURATION 500
#define MUSIC_ELEMENT 16
std::array<int, 9> tail_down{93, 90, 87, 84, 81, 78, 75, 72, 70};
std::array<int, 6> tail_up{70, 75, 80, 85, 89, 92};
double tone_array[MUSIC_ELEMENT] = {NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4, NOTE_G4, NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4, NOTE_C4};
LookUpGateHandler::LookUpGateHandler(std::string name, Balancer* balancer) : Phase(name, balancer)
{
}
void LookUpGateHandler::initialize()
{
}
//修正前 ~1:前進小, ~2.0:前進大, ~3.0:回転, ~5.0:前進, ~6.0:回転, ~8.0:前進
void LookUpGateHandler::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
if(time < 0.2 * TIME_SECTION){
*pwm_L = MOTOR_FORWARD + 3;
*pwm_R = MOTOR_FORWARD + 3;
//*ang_T = tail_down[time / (TIME_SECTION / DIVISION)];
}else if(time < 1 * TIME_SECTION){
*pwm_L = MOTOR_FORWARD_SLOW;
*pwm_R = MOTOR_FORWARD_SLOW;
*ang_T = tail_down[time / (TIME_SECTION / tail_down.size())]; //DIVISION
}else if(time < 20*TIME_SECTION/10){
*pwm_L = MOTOR_FORWARD;
*pwm_R = MOTOR_FORWARD;
if(color > 2 * (LIGHT_WHITE + LIGHT_BLACK) / 3){
*pwm_R = *pwm_R - LINE_TRACE;
}else if(color < 1 * (LIGHT_WHITE + LIGHT_BLACK) / 3){
*pwm_L = *pwm_L - LINE_TRACE;
}
*ang_T = TAIL_ANGLE_LUG;
}else if(time < 30 * TIME_SECTION/10){
*pwm_L = 6;
*pwm_R = -6;
*ang_T = TAIL_ANGLE_LUG;
}else if(time < 50 * TIME_SECTION/10){
*pwm_L = MOTOR_FORWARD;
*pwm_R = MOTOR_FORWARD;
if(color > 2 * (LIGHT_WHITE + LIGHT_BLACK) / 3){
*pwm_L = *pwm_L - LINE_TRACE;
}else if(color < 1 * (LIGHT_WHITE + LIGHT_BLACK) / 3){
*pwm_R = *pwm_R - LINE_TRACE;
}
*ang_T = TAIL_ANGLE_LUG;
}else if(time < 60 * TIME_SECTION/10){
*pwm_L = 6;
*pwm_R = -6;
*ang_T = TAIL_ANGLE_LUG;
}else if(time < 80 * TIME_SECTION/10){
*pwm_L = MOTOR_FORWARD;
*pwm_R = MOTOR_FORWARD;
if(color > 2 * (LIGHT_WHITE + LIGHT_BLACK) / 3){
*pwm_R = *pwm_R - LINE_TRACE;
}else if(color < 1 * (LIGHT_WHITE + LIGHT_BLACK) / 3){
*pwm_L = *pwm_L - LINE_TRACE;
}
*ang_T = TAIL_ANGLE_LUG;
}else{
*pwm_L = MOTOR_BACKWARD_SLOW;
*pwm_R = MOTOR_BACKWARD_SLOW;
*ang_T = tail_up[(time - 80 * TIME_SECTION/10) / (TIME_SECTION / tail_up.size())]; // DIVISION
}
//if(time % MUSIC_DURATION == 0) ev3_speaker_play_tone(tone_array[(time / MUSIC_DURATION) % MUSIC_ELEMENT], MUSIC_DURATION);
}
bool LookUpGateHandler::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
if(time < 90 * TIME_SECTION/10) return false;
else return true;
}
<file_sep>/1108_L/Phase/StraightPhase/StraightPhase.cpp
// StraightPhase.cpp
#include "StraightPhase.hpp"
#define LIGHT_WHITE 40
/* ???F????Z???T?l */
#define LIGHT_BLACK 0
/* ?o?????X???s????p?x[?x] */
#define TAIL_ANGLE_DRIVE 15
StraightPhase::StraightPhase(std::string name, Balancer* balancer) : Phase(name, balancer)
{
}
StraightPhase::StraightPhase(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset) : Phase(name, balancer)
{
forwardl=setforwardl;
forwardr=setforwardr;
endtime=setending;
gyrooffset=gyoffset;
}
void StraightPhase::initialize()
{
fp=fopen("straightlog.csv","w");
if(fp==NULL){
printf("failed\n");
return;
}
fprintf(fp,"time,color,turn,gyro,volt,mtL,mtR\n");
balancer->change_offset(gyrooffset);
for(int i = 0; i < 50; i++){
pwm_L_list[i] = 0;
pwm_R_list[i] = 0;
}
}
void StraightPhase::calc_param(int time,int* forward,signed char* turn,int color){
const float Kp = 1.1;
const float Kd = 10.00;
int diff_p = std::min(color,LIGHT_WHITE)-(LIGHT_WHITE+LIGHT_BLACK)/2;
/*
if(time>=200){
int va=0;
for(int i=0;i<4;i++){
va+=colordi[i];
}
va/=50;
colordi[(time/4)%50]=diff_p;
diff_p=va;
}
*/
int diff_d = diff_p-(diff_prev);
diff_prev=diff_p;
int val=(Kp*diff_p+diff_d*Kd)/2;
if (time == 0) val = (Kp * diff_p) / 2;
(*turn)=(signed char)val;
if(*turn >= 50)
*turn = 50;
if(*turn <= -50)
*turn = -50;
}
void StraightPhase::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
int forward=forwardl+(forwardr-forwardl)*motor_ang_l/endtime;
signed char turn;
calc_param(time,&forward,&turn,color);
balancer->setCommand((signed char)forward, turn);
balancer->update(gyro, motor_ang_r, motor_ang_l, volt);
*pwm_L = balancer->getPwmLeft();
*pwm_R = balancer->getPwmRight();
*ang_T = TAIL_ANGLE_DRIVE;
fprintf(fp,"%d,%d,%d,%d,%d,%d,%d\n",time,color,(int)turn,gyro,volt, (int)motor_ang_l,(int)motor_ang_r);
}
bool StraightPhase::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
pwm_L_list[(time/4)%20] = pwm_L;
pwm_R_list[(time/4)%20] = pwm_R;
int counts = 0;
for(int i = 0; i < 20; i++){
if(pwm_L_list[i] - pwm_R_list[i] >= 20)
counts++;
}
// if (time > endtime){
// return true;
// }else if(time >= 3000 && counts >= 19){
// return true;
// }else {
// return false;
// }
if (motor_ang_l > endtime){
return true;
} else {
return false;
}
}
<file_sep>/1108_R/app_sub.hpp
#if defined(BUILD_MODULE)
#include "module_cfg.h"
#else
#include "kernel_cfg.h"
#endif
#define DEBUG
#ifdef DEBUG
#define _debug(x) (x)
#else
#define _debug(x)
#endif
<file_sep>/1108_L/Phase/GaragePhase/GaragePhase.cpp
// GaragePhase.cpp
#include "GaragePhase.hpp"
#define TIME_BAND 250
#define TAIL_ANGLE_DRIVE 15
GaragePhase::GaragePhase(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset,int turnoffset,float ikp,float ikd,int itailangle, int setmcntl, int setmcntr, int setstoptime) : Phase(name, balancer)
{
forwardl=setforwardl;
forwardr=setforwardr;
endtime=setending;
gyrooffset=gyoffset;
offset=turnoffset;
Kp = ikp;
Kd = ikd;
tailangle=itailangle;
mcntlval=setmcntl;
mcntrval=setmcntr;
stoptime=setstoptime;
}
void GaragePhase::initialize()
{
fp=fopen("garagephase.csv","w");
if(fp==NULL){
printf("failed\n");
return;
}
fprintf(fp,"time,color,turn,gyro,volt,mtL,mtR,flag,mcntl,mcntr\n");
balancer->change_offset(gyrooffset);
}
void GaragePhase::calc_param(int time,int* forward,signed char* turn,int color){
int diff_p = std::min(color,LIGHT_WHITE)-(LIGHT_WHITE+LIGHT_BLACK/*+offset*/)/2;
int diff_d = diff_p-(diff_prev);
diff_prev=diff_p;
int val=(Kp*diff_p+diff_d*Kd)/2;
if(time==0)val=(Kp*diff_p)/2;
(*turn)=(signed char)val;
if(*turn<=-2){
*turn=-2;
}
if(*turn>=2){
*turn=2;
}
}
void GaragePhase::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
int forward=forwardl+(forwardr-forwardl)*time/endtime;
signed char turn;
calc_param(time,&forward,&turn,color);
*pwm_L = 7;
*pwm_R = 7;
if(turn>0)*pwm_R-=turn;
if(turn<0)*pwm_L+=turn;
*ang_T = tailangle;
if(pflag==2){
*pwm_R=0;
*pwm_L=0;
}
fprintf(fp,"%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n",time,color,(int)turn,gyro,volt,(int)*pwm_L,(int)*pwm_R,pflag,mcntl,mcntr);
}
bool GaragePhase::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
int tim = time / 4;
if (time >= 2500) {
int idx = tim % TIME_BAND;
if (time >= 3500 && data[idx] <= boundary) {
cnt--;
}
data[idx] = color;
if (data[idx] <= boundary) cnt++;
}
if(time>=3500 && cnt>210 && pflag==0){
pflag=1;
ev3_speaker_play_tone(50, 1000);
}
if(time>=6500 && pflag==0){
int val=0;
for(int i=0;i<5;i++){
val+=data[(tim-i+TIME_BAND)%TIME_BAND];
val-=data[(tim+i+1)%TIME_BAND];
}
if(val>=40)pflag=1;
}
if(pflag>=1){
mcntl+=(int)pwm_L;
mcntr+=(int)pwm_R;
}
if(pflag==1 && mcntl>=mcntlval && mcntr>=mcntrval){//Garage:mcntlval=5200, mcntrval=5200
pflag=2;
ev3_speaker_play_tone(70, 1000);
}
if(pflag==2)tim2++;
if(tim2>=stoptime)return true;//Garage:stoptime=2000
return false;
}
<file_sep>/1108_R/app.cpp
// app.cpp
#include "ev3api.h"
#include "app.hpp"
#include "app_sub.hpp"
#include "EV3/EV3.hpp"
#include "Balancer/balancer.h"
#include "Balancer/BalancerCPP.hpp"
#include "Operator/Operator.hpp"
#include "Schedule/Schedule.hpp"
#include "Phase/Phase.hpp"
#include "Phase/StartPhase/StartPhase.hpp"
#include "Phase/StraightPhase/StraightPhase.hpp"
#include "Phase/CurvePhase/CurvePhase.hpp"
#include "Phase/DetectGoal/DetectGoal.hpp"
#include "Phase/AfterGoal/AfterGoal.hpp"
#include "Phase/DetectNansho/DetectNansho.hpp"
#include "Phase/LookUpGateHandler/LookUpGateHandler.hpp"
#include "Phase/StairPhase/StairPhase.hpp"
#include "Phase/StairPhase2/StairPhase2.hpp"
#include "Phase/StairPhase3/StairPhase3.hpp"
#include "Phase/GaragePhase/GaragePhase.hpp"
//インスタンス作成
EV3 ev3;
Balancer balancer;
Schedule schedule;
Operator ope(&ev3, &balancer, &schedule);
StartPhase st("StartPhase", &balancer, 106);
/*---- stable tuning -----*/
StraightPhase sp1("StraightPhase", &balancer, 50, 70, 1000, 0);
StraightPhase sp3("StraightPhase", &balancer, 70, 70, 2500, 0); //1500
//CurvePhase cp1("CurvePhase", &balancer, 70, 70, 7500, 0, 0, 1.6, 18.0); //4500
CurvePhase cp1("CurvePhase", &balancer, 70, 70, 9000, 0, 0, 1.4, 15.0); //5200
CurvePhase cp2("CurvePhase", &balancer, 60, 60, 10300, 0, 0, 1.8, 20.0); //2600
CurvePhase cp3("CurvePhase", &balancer, 70, 70, 12500, 0, 0, 1.4, 16.0); //1600
StraightPhase spEnd("StraightPhase", &balancer, 70, 70, 14500, 0); //2600
/*------------------------*/
DetectGoal dg("DetectGoal", &balancer,70, 75,1300,0);
AfterGoal ag("AfterGoal", &balancer, 45, 30, 5800, 0, -2, 1.2, 15.0, 3, 3, 3000);
AfterGoal ag2("AfterGoal", &balancer, 30, 30, -1, 0, -2, 1.2, 15.0, 3, 3, 114514);
AfterGoal ag3("AfterGoal", &balancer, 30, 0, 1000, 0, 5, 1.2, 15.0, 3, 93, 0);
AfterGoal ag4("AfterGoal", &balancer, 0, 0, 1000, 0, 5, 1.2, 15.0, 93, 93, 0);
LookUpGateHandler lug("LookUpGateHandler", &balancer);
//GaragePhase gp("GaragePhase", &balancer,30,30,114514,0,0,1.7,0,92);
GaragePhase gp("GaragePhase", &balancer, 30, 30, 114514, 0, 0, 1.7, 0, 92, 5200, 5200, 2000);
//空のスケジュールにPhaseインスタンスをプッシュ
void createSchedule()
{
schedule.pushPhase(&st);
schedule.pushPhase(&sp1);
schedule.pushPhase(&sp3);
schedule.pushPhase(&cp1);
schedule.pushPhase(&cp2);
schedule.pushPhase(&cp3);
schedule.pushPhase(&spEnd);
// schedule.pushPhase(&dg);
schedule.pushPhase(&ag);
schedule.pushPhase(&ag2);
schedule.pushPhase(&ag3);
schedule.pushPhase(&ag4);
schedule.pushPhase(&lug);
schedule.pushPhase(&gp);
}
/* メインタスク */
void main_task(intptr_t unused)
{
//スケジュールを作って
createSchedule();
//オペレータを走らせて
ope.run();
//おわり
ext_tsk();
}
/*BlueTooth*タスク*/
void bt_task(intptr_t unused)
{
while(1)
{
uint8_t c = fgetc(ev3.getBT()); /* 受信 */
switch(c)
{
case '1':
ev3.setBTcmd(1);
break;
default:
break;
}
fputc(c, ev3.getBT()); /* エコーバック */
}
}
<file_sep>/1108_L/Phase/BeforeStair/BeforeStair.hpp
// BeforeStair.hpp
#ifndef BEFORE_STAIR_H
#define BEFORE_STAIR_H
#include "../Phase.hpp"
#include <string>
class BeforeStair: public Phase {
public:
int angle;
FILE *fp;
BeforeStair(std::string name, Balancer* balancer);
BeforeStair(std::string name, Balancer* balancer,int tailangle);
void initialize();
void calc_param(int time,int* forward,signed char* turn,int color);
void calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T);
bool isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T);
};
#endif
<file_sep>/1108_L/Phase/BeforeStair/BeforeStair.cpp
// BeforeStair.cpp
#include "BeforeStair.hpp"
#define LIGHT_WHITE 25
#define LIGHT_BLACK 0
#define TURN_MAX 7
BeforeStair::BeforeStair(std::string name, Balancer* balancer) : Phase(name, balancer)
{
/*�R���X�g���N�^*/;
}
BeforeStair::BeforeStair(std::string name, Balancer* balancer, int tailangle) : Phase(name, balancer)
{
angle = tailangle;
}
void BeforeStair::initialize()
{
/*��������*/
fp = fopen("BeforeStair.csv", "w");
if (fp == NULL) {
printf("failed\n");
return;
}
fprintf(fp, "time,color,mtL,mtR\n");
}
void BeforeStair::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
//�ҋ@
if (time <= 3000) {
*pwm_L = 0;
*pwm_R = 0;
*ang_T = angle;
//���]���Č��������ɂȂ�
} else if (time <= (5125 + 3000)) {
*pwm_L = 6;
*pwm_R = -6;
*ang_T = angle;
} else if (time <= (5125 + 5000)) {
*pwm_L = 0;
*pwm_R = 0;
*ang_T = angle;
}
fprintf(fp, "%d,%d,%d,%d\n", time, color, (int)*pwm_L, (int)*pwm_R);
}
bool BeforeStair::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
/*�I������������true,�������Ȃ�����false*/
if (12000 >= time)//17000
return false;
else
return true;
}
<file_sep>/1108_R/Phase/TightCurve/TightCurve.hpp
// StraightPhase.hpp
#ifndef TIGHT_CURVE_H
#define TIGHT_CURVE_H
#include "../Phase.hpp"
#include <string>
#include <cmath>
#include <algorithm>
class TightCurve: public Phase {
public:
int diff_prev=20;
int forwardl=60;
int forwardr=60;
int gyrooffset=0;
int endtime=5000;
FILE *fp;
TightCurve(std::string name, Balancer* balancer);
TightCurve(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset);
void initialize();
void calc_param(int time,int* forward,signed char* turn,int color);
void calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T);
bool isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T);
};
#endif
<file_sep>/1108_L/Phase/StairPhase/StairPhase.cpp
// StairPhase.cpp
#include "StairPhase.hpp"
StairPhase::StairPhase(std::string name, Balancer* balancer) : Phase(name, balancer)
{
}
void StairPhase::initialize()
{
balancer->change_offset(0);
}
StairPhase::StairPhase(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset) : Phase(name, balancer)
{
forwardl=setforwardl;
forwardr=setforwardr;
endtime=setending;
gyrooffset=gyoffset;
}
void StairPhase::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
//EV3��2���ɕ����ĐQ����
if(time <= 2000){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 80;
//�i���ɐڋ�
}else if(time <= 4000){
*pwm_L = -8;
*pwm_R = -8;
*ang_T = 80;
//�K���̉ғ��͈͊m��
}else if(time <= 4600){
*pwm_L = 8;
*pwm_R = 8;
*ang_T = 80;
//EV3���R���ɕ����ė��Ă�
}else if(time <= 6800){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 83;
}else if(time <= 7800){
*pwm_L = 0;
*pwm_R = 0;
if(volt >= 8600){
*ang_T = 83;
}else if(volt >= 8400){
*ang_T = 85;
}else {
*ang_T = 86;
}
//�i��������
}else if(time <= 8000){
*pwm_L = -20;
*pwm_R = -20;
*ang_T = 40+40*((time-7800)/200);
}else if(time <= 9200){
*pwm_L = -20;
*pwm_R = -20;
*ang_T = 80;
}else if(time <= 12000){
*pwm_L = 0;
*pwm_R = 0;
*ang_T = 80;
}else if(time <= 15120){
*pwm_L = 20;
*pwm_R = -20;
*ang_T = 80;
}
}
bool StairPhase::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
/*�I������������true,�������Ȃ�����false*/
if (time <= 15120)
return false;
else
return true;
}
<file_sep>/1108_L/Phase/CurvePhase/CurvePhase.cpp
// CurvePhase.cpp
#include "CurvePhase.hpp"
#define LIGHT_WHITE 40
#define LIGHT_BLACK 0
#define TAIL_ANGLE_DRIVE 15
CurvePhase::CurvePhase(std::string name, Balancer* balancer) : Phase(name, balancer)
{
}
CurvePhase::CurvePhase(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset,int turnoffset,float ikp,float ikd) : Phase(name, balancer)
{
forwardl=setforwardl;
forwardr=setforwardr;
endtime=setending;
gyrooffset=gyoffset;
offset=turnoffset;
Kp = ikp;
Kd = ikd;
}
void CurvePhase::initialize()
{
/*
char fine_name[] = "";
strcat(fine_name, name.c_str());
strcat(fine_name, ".csv");
fp=fopen(fine_name,"w");
if(fp==NULL){
printf("failed\n");
return;
}
fprintf(fp,"time,color,turn,gyro,volt,mtL,mtR\n");
*/
balancer->change_offset(gyrooffset);
}
void CurvePhase::calc_param(int time,int* forward,signed char* turn,int color){
int diff_p = std::min(color,LIGHT_WHITE)-(LIGHT_WHITE+LIGHT_BLACK+offset)/2;
int diff_d = diff_p-(diff_prev);
diff_prev=diff_p;
int val=(Kp*diff_p+diff_d*Kd)/2;
if(time==0)val=(Kp*diff_p)/2;
(*turn)=(signed char)val;
if(*turn >= 60)
*turn = 60;
if(*turn <= -60)
*turn = -60;
}
void CurvePhase::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
/*?Z???T?????????????????[?^???o????v?Z????*/
/*turn = 1??2?l????*/
int forward=forwardl+(forwardr-forwardl)*time/endtime;
signed char turn;
calc_param(time,&forward,&turn,color);
balancer->setCommand((signed char)forward, turn);
balancer->update(gyro, motor_ang_r, motor_ang_l, volt);
*pwm_L = balancer->getPwmLeft();
*pwm_R = balancer->getPwmRight();
*ang_T = TAIL_ANGLE_DRIVE;
//fprintf(fp,"%d,%d,%d,%d,%d,%d,%d\n",time,color,(int)turn,gyro,volt,(int)*pwm_L,(int)*pwm_R);
}
bool CurvePhase::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
if (motor_ang_l > endtime)
return true;
else
return false;
}
<file_sep>/1108_R/Phase/AfterGoal/AfterGoal.hpp
// AfterGaol.hpp
#ifndef AFTER_GOAL_H
#define AFTER_GOAL_H
#include "../Phase.hpp"
#include <string>
class AfterGoal: public Phase {
public:
int diff_prev=20;
int forwardl=60;
int forwardr=60;
int gyrooffset=0;
int offset=0;
//int tailangle=3;
int beforeangle;
int afterangle;
int endtime=5000;
float Kp = 1.5;
float Kd = 12.00;
int graytime = 0;
FILE *fp;
AfterGoal(std::string name, Balancer* balancer);
AfterGoal(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int setending,int gyoffset,int turnoffset,float ikp,float ikd,int setangle1, int setangle2,int setgraytime);
void initialize();
void calc_param(int time,int* forward,signed char* turn,int color);
void calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T);
bool isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T);
};
#endif
<file_sep>/1108_L/Phase/DetectGoal/DetectGoal.cpp
// /*DetectGoal*/.cpp
// setting-> offset: +10, CMD_MAX=60
#include "DetectGoal.hpp"
#define LIGHT_WHITE 40
#define LIGHT_BLACK 0
#define TAIL_ANGLE_DRIVE 3
#define TIME_BAND 36
DetectGoal::DetectGoal(std::string name, Balancer* balancer) : Phase(name, balancer)
{
}
DetectGoal::DetectGoal(std::string name, Balancer* balancer,int setforwardl,int setforwardr,int maxspeedtime,int gyoffset) : Phase(name, balancer)
{
forwardl=setforwardl;
forwardr=setforwardr;
mxsptime=maxspeedtime;
gyrooffset=gyoffset;
}
void DetectGoal::initialize()
{
balancer->change_offset(0);
fp=fopen("detectgoallog.csv","w");
if(fp==NULL){
printf("failed\n");
return;
}
fprintf(fp,"time,color\n");
cnt=0;
for(int i=0;i<100;i++){
data[i]=0;
}
}
void DetectGoal::calc_param(int time,int* forward,signed char* turn,int color){
const float Kp = 1.1;
const float Kd = 10.00;
int diff_p = std::min(color,LIGHT_WHITE)-(LIGHT_WHITE+LIGHT_BLACK)/2;
int diff_d = diff_p-(diff_prev);
diff_prev=diff_p;
int val=(Kp*diff_p+diff_d*Kd)/2;
if (time == 0) val = (Kp * diff_p) / 2;
(*turn)=(signed char)val;
if(*turn<-50)
*turn=-50;
if(*turn>50)
*turn=50;
}
void DetectGoal::calculate(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char* pwm_L, signed char* pwm_R, signed int* ang_T)
{
int forward=forwardl+(forwardr-forwardl)*std::min(time,mxsptime)/mxsptime;
signed char turn;
calc_param(time,&forward,&turn,color);
balancer->setCommand((signed char)forward, turn);
balancer->update(gyro, motor_ang_r, motor_ang_l, volt);
*pwm_L = balancer->getPwmLeft();
*pwm_R = balancer->getPwmRight();
*ang_T = TAIL_ANGLE_DRIVE;
//fprintf(fp,"%d,%d\n",time,color);
}
bool DetectGoal::isFinished(int time, int32_t motor_ang_l, int32_t motor_ang_r, int color, int gyro, int sonic, int volt, signed char pwm_L, signed char pwm_R, signed int ang_T)
{
int tim=time/4;
data[tim%TIME_BAND]=color;
if(time>=3000){
int diff1=0;
int diff2=0;
for(int i=0;i<TIME_BAND/3;i++){
diff1+=data[(tim-i+TIME_BAND)%TIME_BAND];
diff2+=data[(tim+i+1)%TIME_BAND];
}
if(diff1-diff2>=(TIME_BAND/3)*10) return true;
}
// if(time>=10000)return true;
return false;
}
| 7d6f1098deb9e3583147d91614d5c77ba30db606 | [
"Makefile",
"C++"
] | 38 | C++ | wadadones/ET | 855d10984038804cab1aaa653243e4dbd047ff71 | 4de737334a2f6dad675a6bb66a60ba77c0df73fc | |
refs/heads/main | <repo_name>suvelocity/challenge-sequelize-template<file_sep>/index.js
class MySequelize {
constructor(connect, tableName) {
this.connection = connect;
this.table = tableName;
}
async create(obj) {
/*
Model.create({
name: 'test',
email: '<EMAIL>',
password: '<PASSWORD>',
is_admin: false
})
*/
}
async bulkCreate(arr) {
/*
Model.bulkCreate([
{
name: 'test',
email: '<EMAIL>',
password: '<PASSWORD>',
is_admin: false
},
{
name: 'test1',
email: '<EMAIL>',
password: '<PASSWORD>',
is_admin: false
},
{
name: 'test2',
email: '<EMAIL>',
password: '<PASSWORD>',
is_admin: true
},
])
*/
}
async findAll(options) {
/*
Model.findAll({
where: {
is_admin: false
},
order: ['id', 'DESC'],
limit 2
})
*/
/*
Model.findAll({
include:[
{
table: playlists, // table yo want to join
tableForeignKey: "creator", // column reference in the table yo want to join
sourceForeignKey: "id", // base table column reference
}
]
})
*/
/*
Model.findAll({
where: {
[Op.gt]: {
id: 10
}, // both [Op.gt] and [Op.lt] need to work so you can pass the tests
[Op.lt]: {
id: 20
}
})
*/
}
async findByPk(id) {
/*
Model.findByPk(id)
*/
}
async findOne(options) {
/*
Model.findOne({
where: {
is_admin: true
}
})
*/
}
async update(newDetails, options) {
/*
Model.update( { name: 'test6', email: '<EMAIL>' } , {
where: { // first object containing details to update
is_admin: true // second object containing condotion for the query
}
})
*/
}
async destroy({ force, ...options }) {
/*
Model.destroy({
where: {
is_admin: true
},
force: true // will cause hard delete
})
*/
/*
Model.destroy({
where: {
id: 10
},
force: false // will cause soft delete
})
*/
/*
Model.destroy({
where: {
id: 10
}, // will cause soft delete
})
*/
}
async restore(options) {
/*
Model.restore({
where: {
id: 12
}
})
*/
}
}
module.exports = { MySequelize };
<file_sep>/Op/OpSymbols.js
const Op = {}
module.exports = { Op } | 3c05ddd92463b6af8a440dc4fdb760a01059058d | [
"JavaScript"
] | 2 | JavaScript | suvelocity/challenge-sequelize-template | 52e65dfb51e3db53386a81147b2f47d4646daf6b | 3d92840f4cd36b5de93867672f3b798719b047aa | |
refs/heads/master | <repo_name>coreyleveen/moneybird<file_sep>/db/migrate/20140519200256_drop_searchdate_column_from_charts.rb
class DropSearchdateColumnFromCharts < ActiveRecord::Migration
def change
remove_column :charts, :search_date
end
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
has_secure_password
validates :email, presence: true, confirmation: true, uniqueness: true, email: true
validates :terms_of_service, acceptance: true
validates :password, length: {within: 6..20, too_short: "Passwords must be 6 characters or more.", too_long: "That password is too long. Please try one under 20 characters."}
has_many :charts
end
<file_sep>/db/migrate/20140519195629_drop_stock_price_and_tweet_count_columns_from_charts.rb
class DropStockPriceAndTweetCountColumnsFromCharts < ActiveRecord::Migration
def change
remove_column :charts, :stock_price
remove_column :charts, :tweet_count
end
end
<file_sep>/lib/normalizer.rb
module Normalizer
def normalize_tweets(chart)
price_arr = []
chart.share_prices.each {|x| price_arr << x.value }
@price_min = price_arr.min
@price_max = price_arr.max
price_range = @price_max - @price_min
# Proportional array mapping
tweet_count_arr = []
chart.tweet_counts.each {|x| tweet_count_arr << x.value}
tweet_min = tweet_count_arr.min
tweet_max = tweet_count_arr.max
tweet_range = tweet_max - tweet_min
atc_arr = tweet_count_arr.map { |x| x - tweet_min }
tweet_prop_arr = atc_arr.map { |x| x / (tweet_range.to_f) }
tp_to_price = tweet_prop_arr.map { |x| x * price_range }
transformed_tweet_arr = tp_to_price.map { |x| x + @price_min }
chart.tweet_counts.each_with_index { |tc, i| tc.value = transformed_tweet_arr[i] }
end
end
<file_sep>/app/models/tweet_count.rb
class TweetCount < ActiveRecord::Base
belongs_to :charts
end
<file_sep>/Project_plan_deliverables.md
Scope:
I'm going to build Moneybird — a web app that will display a graph of the
past week's daily share price for a particular company overlaid with the daily
number of tweets for the past week containing or hashtagged with the company's
name, or other keyword, with the goal of viewing correlations the company's
share price and number of tweets that week for each day.
Features: Moneybird will feature a search bar in which a company name or ticker
symbol is to be entered. By default, the graph created as a result will feature
the past week of price information for that company, along with the number of
daily tweets for the past week containing or hashtagged with the company's name.
The user will then be able to add and remove keywords from the graph using a
text input and add button. Each added keyword will appear next to the graph and
will have a delete button which will remove it from the graph. Users can also
add more graphs, and will be prompted for a company name/ticker symbol for
each. Users will be able to have multiple graphs at once on a page, each with
its own company name and keywords for Twitter activity. Moneybird will use the
Yahoo Finance and Twitter APIs for data retrieval.
Object models (not sure about this yet):
Human - the person using the application, a user
Company - The company chosen by the user entering a search query
Keyword - The keyword entered to be sent to Twitter to display a Tweet activity
overlay on the company's share price graph.
Human has many companies, company has many keywords.
Resources:
Yahoo Finance API / gem
Twitter API
Rails guides
Instructors
more to come..
Milestones:
* Successfully connect to both Twitter and Yahoo Finance APIs, retrieving
relevant data from both
* Overlay of divs whose height responds correctly to API responses
* Users can create/delete accounts, sign in,
sign out, and edit their account info
* Users can enter company name query into a search bar and get its 7 day
trailing share price info.
* User can enter company name query into a search bar and get its 7 day trailing
share price info on a graph
* User's share price graph is now overlaid with that company's twitter activity
* Users can add multiple graphs for different companies.
* Users can add keywords to a company's graph
* Users can delete graphs
Trello: https://trello.com/b/H3dx6col/moneybird
<file_sep>/config/routes.rb
Rails.application.routes.draw do
# Users
root "users#index"
get 'users/new' => "users#new"
post 'users' => "users#create"
get 'users' => "users#index"
# Charts
get 'charts/new' => "charts#new"
post 'charts' => "charts#create"
post 'charts/:id/' => "charts#update", as: 'update'
delete 'charts/:id' => "charts#destroy", as: 'delete'
# Sessions
get 'sessions/new' => 'sessions#new', as: 'log_in'
post 'sessions' => 'sessions#create'
delete 'sessions' => 'sessions#destroy', as: 'log_out'
get 'profiles' => 'profiles#index'
end
<file_sep>/app/controllers/charts_controller.rb
class ChartsController < ApplicationController
def index
end
def new
@chart = Chart.new
end
def create
chart = Chart.create(chart_params)
current_user.charts << chart
redirect_to root_path
end
def update
Chart.find(params[:id]).tweet_search
Chart.find(params[:id]).price_history
redirect_to root_path
end
def destroy
Chart.delete(params[:id])
redirect_to root_path
end
private
def chart_params
params.require(:chart).permit(:ticker)
end
end
<file_sep>/app/models/chart.rb
class Chart < ActiveRecord::Base
belongs_to :users
has_many :share_prices
has_many :tweet_counts
after_create :tweet_search, :price_history
def tweet_search
config = {
:consumer_key => ENV['TWITTER_KEY'],
:consumer_secret => ENV['TWITTER_SECRET']
}
client = Twitter::REST::Client.new(config)
i = 7
@dates_arr = []
loop do
@dates_arr << Date.today.prev_day(n=i).to_s
i -= 1
break if i < 0
end
n = 0
tweet_count_arr = []
loop do
tweet_count_arr << client.search(self.ticker + " since:#{@dates_arr[n]} until:#{@dates_arr[n+1]}").count
n += 1
break if n > 6
end
self.tweet_counts.delete_all
i = 0
tweet_count_arr.each do |x|
tweet_count = TweetCount.create( { value: x, date: @dates_arr[i] })
self.tweet_counts << tweet_count
i += 1
end
end
def price_history(num_days=7)
num_days_search = num_days + 10
obj_arr = YahooFinance.historical_quotes("#{self.ticker}", Time::now-(24*60*60*num_days_search), Time::now).take(num_days)
price_arr = []
obj_arr.each do |x|
num = x.close.to_f
price_arr << num
end
price_arr.reverse!
self.share_prices.delete_all
price_arr.each_with_index do |x,i|
share_price = SharePrice.create( { value: x, date: @dates_arr[i] })
self.share_prices << share_price
end
end
end
<file_sep>/README.md
# moneybird
__moneybird__ graphs companies' share price history with their Twitter activity for the past week.
### Instructions
1. Sign up for an account
2. Login
3. Make a chart by entering in a stock's ticker symbol from the NYSE
Some sample charts:

This application began as a week-long project as part of my Web Development Immersive course at General Assembly. It's built on Rails and uses the Yahoo Finance and Twitter APIs.
<file_sep>/db/migrate/20140519024951_create_charts.rb
class CreateCharts < ActiveRecord::Migration
def change
create_table :charts do |t|
t.date :search_date
t.string :ticker
t.integer :stock_price
t.integer :tweet_count
t.timestamps
end
end
end
<file_sep>/app/models/share_price.rb
class SharePrice < ActiveRecord::Base
belongs_to :charts
end
| aae63cb59cf9febb4ecf7eedc08a2160290e6d34 | [
"Markdown",
"Ruby"
] | 12 | Ruby | coreyleveen/moneybird | 3b2a309f46c5ae73f0f3ea0031d786d7f1292602 | 2dc1a6aa4778b5bc1cc0a6977939a7b7d2c9399f | |
refs/heads/main | <repo_name>Marrvvelll/Ayaziy<file_sep>/app/src/main/java/com/example/ayaziy/SongsFragment.kt
package com.example.ayaziy
import android.os.Bundle
import android.view.View
import android.widget.Adapter
import androidx.fragment.app.Fragment
import com.example.ayaziy.data.QosiqlarDatabase
import com.example.ayaziy.data.dao.QosiqlarDao
import kotlinx.android.synthetic.main.songs_layout.*
class SongsFragment:Fragment(R.layout.songs_layout) {
var adapter=AdapterSongs()
private lateinit var dao:QosiqlarDao
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerSongs.adapter=adapter
dao=QosiqlarDatabase.getInstance(requireContext()).dao()
adapter.models=dao.getAllQosiqlar()
}
}<file_sep>/app/src/main/java/com/example/ayaziy/data/model/Qosiqlar.kt
package com.example.ayaziy.data.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "qosiqlar")
data class Qosiqlar(
@PrimaryKey val id:Int,
@ColumnInfo(name="name")
val name:String,
@ColumnInfo(name="text")
val text:String,
@ColumnInfo(name="is_favorite")
var favorite:Int,
@ColumnInfo(name="type")
val type:Int
)<file_sep>/app/src/main/java/com/example/ayaziy/data/dao/QosiqlarDao.kt
package com.example.ayaziy.data.dao
import androidx.room.Dao
import androidx.room.Query
import com.example.ayaziy.data.model.Qosiqlar
@Dao
interface QosiqlarDao {
@Query("SELECT * FROM qosiqlar")
fun getAllQosiqlar():List<Qosiqlar>
}<file_sep>/app/src/main/java/com/example/ayaziy/MainActivity.kt
package com.example.ayaziy
import android.os.Bundle
import android.view.Menu
import androidx.appcompat.app.ActionBarDrawerToggle
import com.google.android.material.navigation.NavigationView
import androidx.drawerlayout.widget.DrawerLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
val navView: NavigationView = findViewById(R.id.nav_view)
val toggle= ActionBarDrawerToggle(this,drawerLayout,R.string.navigation_drawer_open,R.string.navigation_drawer_close)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
navView.setNavigationItemSelectedListener {
when(it.itemId){
R.layout.omirlik_joli->{
supportFragmentManager.beginTransaction().replace(R.id.fragment_container,OmirlikJoliFragment()).commit()
return@setNavigationItemSelectedListener true
}
}
return@setNavigationItemSelectedListener false
}
supportFragmentManager.beginTransaction().replace(R.id.fragment_container,HomeFragment()).commit()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
}<file_sep>/app/src/main/java/com/example/ayaziy/HomeFragment.kt
package com.example.ayaziy
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.home.*
class HomeFragment:Fragment(R.layout.home) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
songs.setOnClickListener {
requireActivity().supportFragmentManager.beginTransaction().replace(R.id.fragment_container,SongsFragment()).commit()
}
poems.setOnClickListener {
}
videos.setOnClickListener {
}
fotos.setOnClickListener {
}
}
}<file_sep>/app/src/main/java/com/example/ayaziy/AdapterSongs.kt
package com.example.ayaziy
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Adapter
import androidx.recyclerview.widget.RecyclerView
import com.example.ayaziy.data.model.Qosiqlar
import kotlinx.android.synthetic.main.item_songs.view.*
class AdapterSongs:RecyclerView.Adapter<AdapterSongs.ViewHolderSongs>() {
var models:List<Qosiqlar> = listOf()
set(value) {
field=value
notifyDataSetChanged()
}
inner class ViewHolderSongs(itemView: View):RecyclerView.ViewHolder(itemView){
fun populateModel(qosiq:Qosiqlar){
itemView.itemSongs.text=qosiq.name
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolderSongs {
var itemView=LayoutInflater.from(parent.context).inflate(R.layout.item_songs,parent,false)
return ViewHolderSongs(itemView)
}
override fun getItemCount(): Int {
return models.size
}
override fun onBindViewHolder(holder: ViewHolderSongs, position: Int) {
holder.populateModel(models[position])
}
}<file_sep>/app/src/main/java/com/example/ayaziy/data/QosiqlarDatabase.kt
package com.example.ayaziy.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.ayaziy.data.dao.QosiqlarDao
import com.example.ayaziy.data.model.Qosiqlar
@Database(entities = [Qosiqlar::class],version = 1)
abstract class QosiqlarDatabase:RoomDatabase() {
companion object{
private lateinit var INSTANCE:QosiqlarDatabase
fun getInstance(context: Context):QosiqlarDatabase=
Room.databaseBuilder(
context,
QosiqlarDatabase::class.java,
"database.db"
)
.createFromAsset("database.db")
.allowMainThreadQueries()
.build()
}
abstract fun dao():QosiqlarDao
} | 9af64475d4c59d8d058e72ae4cfed24cccec7fc9 | [
"Kotlin"
] | 7 | Kotlin | Marrvvelll/Ayaziy | 9dfa0bd2ebc3a9f53e3765c2292dc1b39911409b | b8fa59e2210d2be82f689f789549f015ac1640dc | |
refs/heads/master | <repo_name>majiddeh/MyBookStore<file_sep>/app/src/main/java/com/example/mybookstore/Activities/BasketActivity.java
package com.example.mybookstore.Activities;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.mybookstore.Adapters.AdapterBasket;
import com.example.mybookstore.Models.ModelBasket;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.example.mybookstore.Utils.Links;
import com.example.mybookstore.Utils.Put;
import com.example.mybookstore.Utils.UserSharedPrefrences;
import com.pnikosis.materialishprogress.ProgressWheel;
import java.text.DecimalFormat;
import java.util.List;
public class BasketActivity extends AppCompatActivity {
TextView txtTitle,txttotal;
ImageView imgBackButton;
LinearLayout lnrBasket;
CardView cardBasket;
RecyclerView recyclerViewBasket;
ApiServices apiServices = new ApiServices(BasketActivity.this);
ProgressWheel progressWheel;
AdapterBasket adapterBasket;
int totalAllPrice = 0;
String phone,token;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basket);
UserSharedPrefrences userSharedPrefrences = new UserSharedPrefrences(BasketActivity.this);
phone= userSharedPrefrences.getUserName();
token = userSharedPrefrences.getUserToken();
finViews();
initializePage();
onClicks();
}
private void initializePage() {
apiServices.CartReceived(progressWheel,token, new ApiServices.OnCartReceived() {
@Override
public void onReceived(List<ModelBasket> modelBaskets,int totalPrice) {
adapterBasket = new AdapterBasket(BasketActivity.this,modelBaskets);
adapterBasket.setOnloadPrice(new AdapterBasket.OnloadPrice() {
@Override
public void onloadPrice() {
recreate();
}
});
recyclerViewBasket.setLayoutManager(new LinearLayoutManager(BasketActivity.this));
recyclerViewBasket.setAdapter(adapterBasket);
DecimalFormat decimalFormat = new DecimalFormat("###,###");
decimalFormat.format(totalPrice);
txttotal.setText(totalPrice+""+" "+"تومان");
}
});
}
private void onClicks() {
imgBackButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
cardBasket.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(BasketActivity.this,PayConfirmActivity.class);
intent.putExtra(Put.token,token);
startActivity(intent);
}
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse(Links.ZARRINPAL+"?Amount="+"1000"+"&Email="+"<EMAIL>"+"&Description="+"سفارش کتاب"));
// try {
// startActivity(intent);
// }catch (Exception e){
// e.printStackTrace();
// }
//// Intent intent = new Intent(BasketActivity.this,WebGateActivity.class);
//// intent.putExtra(Put.total,totalAllPrice);
//// startActivity(intent);
// }
});
}
private void finViews() {
progressWheel = findViewById(R.id.progress_wheel);
recyclerViewBasket=findViewById(R.id.recyclerbasket);
cardBasket=findViewById(R.id.card_basket);
txtTitle = findViewById(R.id.txt_title_toolbar_second);
txtTitle.setText("سبد خرید شما");
imgBackButton = findViewById(R.id.img_back_second_toolbar);
lnrBasket=findViewById(R.id.lnrbasket);
txttotal=findViewById(R.id.txt_total);
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Models/ModelBasket.java
package com.example.mybookstore.Models;
public class ModelBasket {
private int id;
private String image;
private String number;
private String title;
private String price;
private String allPrice;
public ModelBasket(int id, String image, String number, String title, String price, String allPrice) {
this.id = id;
this.image = image;
this.number = number;
this.title = title;
this.price = price;
this.allPrice = allPrice;
}
public ModelBasket() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getAllPrice() {
return allPrice;
}
public void setAllPrice(String allPrice) {
this.allPrice = allPrice;
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Activities/PayConfirmActivity.java
package com.example.mybookstore.Activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mybookstore.R;
public class PayConfirmActivity extends AppCompatActivity {
TextView txtTitle;
ImageView imgBackButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_confirm);
findViews();
onClicks();
}
private void onClicks() {
imgBackButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
}
private void findViews() {
txtTitle = findViewById(R.id.txt_title_toolbar_second);
txtTitle.setText("نهایی کردن خرید");
imgBackButton = findViewById(R.id.img_back_second_toolbar);
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Activities/SendCommentActivity.java
package com.example.mybookstore.Activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.example.mybookstore.Utils.Put;
import com.example.mybookstore.Utils.UserSharedPrefrences;
import com.willy.ratingbar.ScaleRatingBar;
public class SendCommentActivity extends AppCompatActivity {
ScaleRatingBar ratingBar;
EditText edInsert,edPositive,edNegative;
CardView btnSubmit;
TextView txtTollbar;
ImageView imgBack;
String phone;
String id ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_comment);
findViews();
onClicks();
}
private void onClicks() {
imgBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (phone.equals("ورود/عضویت")){
Toast.makeText(SendCommentActivity.this, "لطفا وارد حساب کاربری خود شوید", Toast.LENGTH_SHORT).show();
}else {
if (!edInsert.getText().toString().equals("") && !edNegative.getText().toString().trim().equals("")
&& !edPositive.getText().toString().trim().equals("")){
if (ratingBar.getRating() != 0){
ApiServices apiServices = new ApiServices(SendCommentActivity.this);
apiServices.SendComment(id, phone, edInsert.getText().toString().trim(),
edPositive.getText().toString().trim(), edNegative.getText().toString().trim(),
ratingBar.getRating(), new ApiServices.OnCommentSend() {
@Override
public void onSend(int responsStatus) {
if (responsStatus == 218){
Toast.makeText(SendCommentActivity.this, "نظر با موفقیت ثبت شد", Toast.LENGTH_SHORT).show();
edInsert.setText("");
edNegative.setText("");
edPositive.setText("");
edInsert.requestFocus();
}
}
});
}else
Toast.makeText(SendCommentActivity.this, "لطفا امتیاز دهید", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(SendCommentActivity.this, "لطفا تمامی مقادیر را پر کنید", Toast.LENGTH_SHORT).show();
}
}
});
}
private void findViews() {
ratingBar = findViewById(R.id.rating_insert_comment);
edInsert = findViewById(R.id.ed_comment_input);
edInsert.requestFocus();
edNegative = findViewById(R.id.ed_negative);
edPositive = findViewById(R.id.ed_positive);
btnSubmit = findViewById(R.id.btn_submit);
txtTollbar = findViewById(R.id.txt_title_toolbar_second);
txtTollbar.setText(R.string.insert_comment);
imgBack = findViewById(R.id.img_back_second_toolbar);
UserSharedPrefrences userSharedPrefrences = new UserSharedPrefrences(SendCommentActivity.this);
phone = userSharedPrefrences.getUserName();
// image = userSharedPrefrences.getUserImaje();
id = getIntent().getStringExtra(Put.id);
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Activities/ChangePassActivity.java
package com.example.mybookstore.Activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.example.mybookstore.Utils.Put;
import com.example.mybookstore.Utils.UserSharedPrefrences;
import com.pnikosis.materialishprogress.ProgressWheel;
public class ChangePassActivity extends AppCompatActivity {
EditText edRepass, edCurrentPass,edNewPass;
RelativeLayout liner2;
TextView txtTitle;
CardView cardChangepass;
ProgressWheel progressWheel;
ImageView imgBack;
ApiServices apiServices;
String username,token;
UserSharedPrefrences userSharedPrefrences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_pass);
findViews();
initPage();
onClicks();
}
private void initPage() {
if (getIntent().getStringExtra("changepass").equals("forget")){
liner2.setVisibility(View.GONE);
edNewPass.requestFocus();
}else if (getIntent().getStringExtra("changepass").equals("change")){
edCurrentPass.requestFocus();
}
}
private void onClicks() {
imgBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
cardChangepass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (getIntent().getStringExtra("changepass").equals("forget")){
String pass = convertNumberToEnglish(edNewPass.getText().toString().trim());
String repass = convertNumberToEnglish(edRepass.getText().toString().trim());
apiServices.SetPass(getIntent().getStringExtra(Put.username),pass,repass,progressWheel);
}else if (getIntent().getStringExtra("changepass").equals("change")){
String pass = convertNumberToEnglish(edNewPass.getText().toString().trim());
String repass = convertNumberToEnglish(edRepass.getText().toString().trim());
String currentpass = convertNumberToEnglish(edCurrentPass.getText().toString().trim());
apiServices.ChangePass(username,token,currentpass,pass,repass,progressWheel);
}
}
});
}
private String convertNumberToEnglish(String num) {
String d = num;
d = d.replace("۰", "0");
d = d.replace("۱", "1");
d = d.replace("۲", "2");
d = d.replace("٣", "3");
d = d.replace("٤", "4");
d = d.replace("۵", "5");
d = d.replace("٦", "6");
d = d.replace("٧", "7");
d = d.replace("۸", "8");
d = d.replace("۹", "9");
d = d.replace("۰", "0");
d = d.replace("۱", "1");
d = d.replace("۲", "2");
d = d.replace("۳", "3");
d = d.replace("۴", "4");
d = d.replace("۵", "5");
d = d.replace("۶", "6");
d = d.replace("۷", "7");
d = d.replace("۸", "8");
d = d.replace("۹", "9");
return d;
}
private void findViews() {
userSharedPrefrences = new UserSharedPrefrences(ChangePassActivity.this);
apiServices = new ApiServices(ChangePassActivity.this);
txtTitle = findViewById(R.id.txt_title_toolbar_second);
txtTitle.setText("ایجاد کلمه عبور جدید");
cardChangepass = findViewById(R.id.card_Register);
progressWheel = findViewById(R.id.progress_wheel);
edCurrentPass = findViewById(R.id.ed_current_pass);
edNewPass = findViewById(R.id.ed_newpass);
edRepass = findViewById(R.id.ed_repass);
imgBack = findViewById(R.id.img_back_second_toolbar);
liner2 =findViewById(R.id.liner2);
username = userSharedPrefrences.getUserName();
token = userSharedPrefrences.getUserToken();
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Adapters/AdapterBanner.java
package com.example.mybookstore.Adapters;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.mybookstore.Activities.BannerActivity;
import com.example.mybookstore.Models.ModelBanner;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.Links;
import com.example.mybookstore.Utils.Put;
import com.squareup.picasso.Picasso;
import java.util.List;
public class AdapterBanner extends RecyclerView.Adapter<AdapterBanner.viewHolder> {
Context context;
List<ModelBanner> modelBanners;
public AdapterBanner(Context context, List<ModelBanner> modelBanners) {
this.context = context;
this.modelBanners = modelBanners;
}
@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_show_banner,viewGroup,false);
return new viewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final viewHolder viewHolder, final int i) {
Picasso.with(context).load(modelBanners.get(i).getImage())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(viewHolder.imgBanner);
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(viewHolder.itemView.getContext(), BannerActivity.class);
intent.putExtra(Put.id,modelBanners.get(i).getId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return modelBanners.size();
}
class viewHolder extends RecyclerView.ViewHolder{
ImageView imgBanner;
CardView cardView;
public viewHolder(@NonNull View itemView) {
super(itemView);
imgBanner = itemView.findViewById(R.id.img_banner);
cardView = itemView.findViewById(R.id.card_banner);
}
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Adapters/AdapterItemCat.java
package com.example.mybookstore.Adapters;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mybookstore.Activities.ItemActivity;
import com.example.mybookstore.Activities.ItemCatActivity;
import com.example.mybookstore.Models.ModelCategory;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.Links;
import com.example.mybookstore.Utils.Put;
import com.squareup.picasso.Picasso;
import java.util.List;
public class AdapterItemCat extends RecyclerView.Adapter<AdapterItemCat.viewHolder> {
Context context;
List<ModelCategory> modelCategories;
public AdapterItemCat(Context context, List<ModelCategory> modelCategories) {
this.context = context;
this.modelCategories = modelCategories;
}
@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_view_category,viewGroup,false);
return new viewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final viewHolder viewHolder, final int i) {
final ModelCategory modelCategory = modelCategories.get(i);
viewHolder.txtCat.setText(modelCategory.getTitle_category());
Picasso.with(context).load(modelCategory.getImage())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(viewHolder.imgCat);
viewHolder.cardCategory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(viewHolder.itemView.getContext(), ItemActivity.class);
intent.putExtra(Put.id,modelCategories.get(i).getId()+"");
String title = modelCategory.getTitle_category();
intent.putExtra(Put.name,title);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return modelCategories.size();
}
class viewHolder extends RecyclerView.ViewHolder{
CardView cardCategory;
ImageView imgCat;
TextView txtCat;
public viewHolder(@NonNull View itemView) {
super(itemView);
cardCategory=itemView.findViewById(R.id.card_category);
imgCat=itemView.findViewById(R.id.img_category);
txtCat=itemView.findViewById(R.id.txt_title_category);
}
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Adapters/AdapterSearch.java
package com.example.mybookstore.Adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mybookstore.Activities.ShowActivity;
import com.example.mybookstore.Models.ModelItemProduct;
import com.example.mybookstore.Models.ModelSearch;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.Links;
import com.example.mybookstore.Utils.Put;
import com.squareup.picasso.Picasso;
import java.text.DecimalFormat;
import java.util.List;
public class AdapterSearch extends RecyclerView.Adapter<AdapterSearch.viewHolder> {
Context context;
List<ModelSearch> modelSearches;
public AdapterSearch(Context context, List<ModelSearch> modelSearches) {
this.context = context;
this.modelSearches = modelSearches;
}
@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_show_search,viewGroup,false);
return new viewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final viewHolder viewHolder, int i) {
final ModelSearch modelSearch =modelSearches.get(i);
DecimalFormat decimalFormat = new DecimalFormat("###,###");
if (modelSearch.getLable() != null && modelSearch.getLable().equals("0")){
viewHolder.txtOffPrice.setVisibility(View.GONE);
}else {
viewHolder.txtPrice.setTextColor(Color.RED);
viewHolder.txtPrice.setPaintFlags(viewHolder.txtPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
viewHolder.txtOffPrice.setVisibility(View.VISIBLE);
viewHolder.txtOffPrice.setText(decimalFormat.format(Integer.valueOf(modelSearch.getOffPrice()))+" "+"تومان");
}
viewHolder.txtVisit.setText(modelSearch.getVisit());
viewHolder.txtTitle.setText(modelSearch.getTitle());
// viewHolder.txtPublisher.setText(modelSearch.getPublisher());
// viewHolder.txtAuthor.setText(modelSearch.getAuthor());
viewHolder.txtPrice.setText(decimalFormat.format(Integer.valueOf(modelSearch.getPrice()))+" "+"تومان");
viewHolder.txtDesc.setText(modelSearch.getDesc());
Picasso.with(context).load(modelSearch.getImage())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(viewHolder.imageViewSearch);
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(viewHolder.itemView.getContext(), ShowActivity.class);
if (modelSearch.getOffPrice().equals(modelSearch.getPrice())){
intent.putExtra(Put.offPrice,"0");
}else {
intent.putExtra(Put.offPrice,modelSearch.getOffPrice());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
intent.putExtra(Put.id,modelSearch.getId()+"");
intent.putExtra(Put.cat,modelSearch.getCat());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return modelSearches.size();
}
public class viewHolder extends RecyclerView.ViewHolder{
CardView cardView;
ImageView imageViewSearch;
TextView txtTitle,txtPrice,txtDesc,txtVisit,txtOffPrice;
public viewHolder(@NonNull View itemView) {
super(itemView);
cardView=itemView.findViewById(R.id.card_search);
imageViewSearch=itemView.findViewById(R.id.img_item_search);
txtTitle=itemView.findViewById(R.id.txttitle_search);
txtPrice=itemView.findViewById(R.id.txtprice_search);
txtDesc=itemView.findViewById(R.id.txtdescription_search);
txtVisit=itemView.findViewById(R.id.txt_visit_item_search);
txtOffPrice=itemView.findViewById(R.id.txtprice_off_item_search);
}
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Models/ModelAddress.java
package com.example.mybookstore.Models;
public class ModelAddress {
int idAddress;
String name;
String family;
String phone;
String postalcode;
String city;
String cityCap;
String idcityCap;
String idcity;
String mobile;
String address;
String iduser;
public ModelAddress() {
}
public String getIdcityCap() {
return idcityCap;
}
public void setIdcityCap(String idcityCap) {
this.idcityCap = idcityCap;
}
public String getIdcity() {
return idcity;
}
public void setIdcity(String idcity) {
this.idcity = idcity;
}
public int getIdAddress() {
return idAddress;
}
public void setIdAddress(int idAddress) {
this.idAddress = idAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPostalcode() {
return postalcode;
}
public void setPostalcode(String postalcode) {
this.postalcode = postalcode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCityCap() {
return cityCap;
}
public void setCityCap(String cityCap) {
this.cityCap = cityCap;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getIduser() {
return iduser;
}
public void setIduser(String iduser) {
this.iduser = iduser;
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Adapters/AdapterBasket.java
package com.example.mybookstore.Adapters;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.mybookstore.Models.ModelBasket;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.example.mybookstore.Utils.Links;
import com.example.mybookstore.Utils.MySingleton;
import com.squareup.picasso.Picasso;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AdapterBasket extends RecyclerView.Adapter<AdapterBasket.ViewHolder> {
Context context;
List<ModelBasket> list;
private OnloadPrice onloadPrice;
public AdapterBasket(Context context, List<ModelBasket> list) {
this.context = context;
this.list = list;
}
public void setOnloadPrice(OnloadPrice onloadPrice) {
this.onloadPrice = onloadPrice;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view =LayoutInflater.from(context).inflate(R.layout.item_show_basket,viewGroup,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
DecimalFormat decimalFormat = new DecimalFormat("###,###");
viewHolder.txtTotalPrice.setText(decimalFormat.format(Integer.valueOf(list.get(i).getAllPrice()))+" "+"تومان");
Picasso.with(context).load(list.get(i).getImage())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(viewHolder.imageBasket);
viewHolder.txtNumber.setText(list.get(i).getNumber()+" "+"عدد");
viewHolder.txtTitile.setText(list.get(i).getTitle());
viewHolder.txtPrice.setText(decimalFormat.format(Integer.valueOf(list.get(i).getPrice()))+" "+"تومان");
viewHolder.imgdelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if (onloadPrice !=null ){
// onloadPrice.onloadPrice();
// ApiServices apiServices = new ApiServices(context);
// apiServices.DeleteFromCart(list.get(i).getId());
// Handler handler = new Handler();
// handler.postDelayed(new Runnable() {
// @Override
// public void run() {
// list.remove(i);
// notifyItemRemoved(i);
// notifyItemRangeRemoved(i,list.size());
// }
// },2);
// }
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dilaog_default);
dialog.show();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setCancelable(false);
TextView tvTitle,tvText,tvNegativ,tvPositive;
tvNegativ=dialog.findViewById(R.id.tv_dialog_negative);
tvPositive=dialog.findViewById(R.id.tv_dialog_positive);
tvText=dialog.findViewById(R.id.tv_dialog_text);
tvTitle=dialog.findViewById(R.id.tv_dialog_title);
tvNegativ.setText("خیر");
tvPositive.setText("بله");
tvNegativ.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
},500);
}
});
tvPositive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Handler handlerr = new Handler();
handlerr.postDelayed(new Runnable() {
@Override
public void run() {
if (onloadPrice !=null ){
onloadPrice.onloadPrice();
ApiServices apiServices = new ApiServices(context);
apiServices.DeleteFromCart(list.get(i).getId());
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
list.remove(i);
notifyItemRemoved(i);
notifyItemRangeRemoved(i,list.size());
dialog.dismiss();
}
},2);
}
}
},500);
}
});
tvTitle.setText("حذف از سبد خرید");
tvText.setText("آیا مطمئن هستید؟");
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public interface OnloadPrice {
void onloadPrice();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageBasket,imgdelete;
TextView txtTitile,txtNumber,txtPrice,txtTotalPrice;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imgdelete=itemView.findViewById(R.id.img_delete_from_cart);
txtNumber=itemView.findViewById(R.id.txtnumberbasket);
txtPrice=itemView.findViewById(R.id.txtpricebasket);
txtTitile=itemView.findViewById(R.id.txttitlebasket);
txtTotalPrice=itemView.findViewById(R.id.txtpricetotalbasket);
imageBasket=itemView.findViewById(R.id.imgbasket);
}
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Activities/ShowCommentActivity.java
package com.example.mybookstore.Activities;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mybookstore.Adapters.AdapterComment;
import com.example.mybookstore.Models.ModelComment;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.example.mybookstore.Utils.Put;
import java.util.ArrayList;
import java.util.List;
public class ShowCommentActivity extends AppCompatActivity {
RecyclerView recyclerView;
AdapterComment adapterComment;
ImageView imgBack;
TextView txtTitle;
FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_comment);
findViews();
initPage();
onClicks();
}
private void onClicks() {
imgBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ShowCommentActivity.this,SendCommentActivity.class);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
intent.putExtra(Put.id,getIntent().getStringExtra(Put.id));
startActivity(intent);
}
});
}
private void initPage() {
ApiServices apiServices = new ApiServices(ShowCommentActivity.this);
apiServices.GetComment(getIntent().getStringExtra(Put.id),new ApiServices.OnCommentReceived() {
@Override
public void onComment(List<ModelComment> modelComments) {
adapterComment= new AdapterComment(ShowCommentActivity.this,modelComments);
recyclerView.setLayoutManager(new LinearLayoutManager(ShowCommentActivity.this));
recyclerView.setAdapter(adapterComment);
recyclerView.hasFixedSize();
}
});
}
private void findViews() {
fab=findViewById(R.id.fab_comment);
recyclerView=findViewById(R.id.recycler_comment);
txtTitle = findViewById(R.id.txt_title_toolbar_second);
txtTitle.setText("نظرات کاربران");
imgBack = findViewById(R.id.img_back_second_toolbar);
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Activities/FullProductActivity.java
package com.example.mybookstore.Activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mybookstore.Adapters.AdapterCategoryLittleView;
import com.example.mybookstore.Adapters.AdapterOff;
import com.example.mybookstore.Adapters.AdapterProduct;
import com.example.mybookstore.Models.ModelOff_Only_MostVisit;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.example.mybookstore.Utils.Links;
import com.example.mybookstore.Utils.Put;
import java.util.List;
public class FullProductActivity extends AppCompatActivity {
private TextView txtTitle;
private ImageView imgBack;
private ApiServices apiServices;
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_product);
findViews();
onClicks();
initPage();
}
private void initPage() {
if (getIntent().getStringExtra(Put.links).equals(Links.GET_OFF)){
apiServices.offReceived(Links.GET_OFF, new ApiServices.OnOffReceived() {
@Override
public void onOffReceived(List<ModelOff_Only_MostVisit> modelOffOnlies) {
AdapterProduct adapterProduct = new AdapterProduct(getApplicationContext(),modelOffOnlies);
recyclerView.setLayoutManager(new GridLayoutManager(FullProductActivity.this,2));
recyclerView.setAdapter(adapterProduct);
}
});
}else {
apiServices.onlyReceived(getIntent().getStringExtra(Put.links), new ApiServices.OnOnlyReceived() {
@Override
public void onOnlyReceived(List<ModelOff_Only_MostVisit> modelOnlies) {
AdapterProduct adapterProduct = new AdapterProduct(getApplicationContext(),modelOnlies);
recyclerView.setLayoutManager(new GridLayoutManager(FullProductActivity.this,2));
recyclerView.setAdapter(adapterProduct);
}
});
}
}
private void onClicks() {
imgBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private void findViews() {
txtTitle = findViewById(R.id.txt_title_toolbar_second);
txtTitle.setText("لیست کامل");
imgBack = findViewById(R.id.img_back_second_toolbar);
apiServices = new ApiServices(FullProductActivity.this);
recyclerView = findViewById(R.id.recycler_ull_products);
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Models/ModelCategory.java
package com.example.mybookstore.Models;
public class ModelCategory {
int id;
String title_category;
String image;
public ModelCategory(int id, String title_category, String image) {
this.id = id;
this.title_category = title_category;
this.image = image;
}
public ModelCategory() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle_category() {
return title_category;
}
public void setTitle_category(String title_category) {
this.title_category = title_category;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Activities/FavoriteActivity.java
package com.example.mybookstore.Activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mybookstore.Adapters.AdapterFav;
import com.example.mybookstore.Models.ModelFav;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.example.mybookstore.Utils.Put;
import java.util.List;
public class FavoriteActivity extends AppCompatActivity {
private TextView txtTitle;
private ImageView imgBackButton;
private RecyclerView recyclerView;
private AdapterFav adapterFav;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite);
findViews();
onClicks();
recyvlerInit();
}
private void recyvlerInit() {
// adapterFav = new AdapterFav(FavoriteActivity.this, modelFavs);
// recyclerView.setLayoutManager(new LinearLayoutManager(FavoriteActivity.this));
// recyclerView.setAdapter(adapterFav);
// recyclerView.hasFixedSize();
}
private void onClicks() {
imgBackButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private void findViews() {
txtTitle = findViewById(R.id.txt_title_toolbar_second);
txtTitle.setText("لیست علاقه مندی ها");
imgBackButton = findViewById(R.id.img_back_second_toolbar);
recyclerView = findViewById(R.id.recycler_fav);
}
@Override
protected void onStart() {
super.onStart();
ApiServices apiServices = new ApiServices(FavoriteActivity.this);
apiServices.FavReceived(getIntent().getStringExtra(Put.username), new ApiServices.OnFavtReceived() {
@Override
public void onReceived(List<ModelFav> modelFavs) {
adapterFav = new AdapterFav(FavoriteActivity.this, modelFavs);
recyclerView.setLayoutManager(new LinearLayoutManager(FavoriteActivity.this));
recyclerView.setAdapter(adapterFav);
recyclerView.hasFixedSize();
}
});
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Adapters/AdapterAddressFragment.java
package com.example.mybookstore.Adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.TextView;
import com.example.mybookstore.Models.ModelAddress;
import com.example.mybookstore.R;
import java.util.List;
public class AdapterAddressFragment extends RecyclerView.Adapter<AdapterAddressFragment.viewHolder> {
private RadioButton lastCheckedRB = null;
Context context;
List<ModelAddress> modelAddresses;
GetAddressUser getAddressUser;
public AdapterAddressFragment(Context context, List<ModelAddress> modelAddresses, GetAddressUser getAddressUser) {
this.context = context;
this.modelAddresses = modelAddresses;
this.getAddressUser=getAddressUser;
}
@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_show_address,viewGroup,false);
return new viewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final viewHolder viewHolder, final int position) {
viewHolder.radioButton.setVisibility(View.VISIBLE);
final ModelAddress modelAddress=modelAddresses.get(position);
viewHolder.tvNameFamily.setText(modelAddress.getName() + " " + modelAddress.getFamily());
viewHolder.tvMobile.setText("شماره تلفن ضروری : "+modelAddress.getMobile());
viewHolder.tvPhone.setText("شماره تلفن ثابت : "+modelAddress.getPhone());
viewHolder.tvAddress.setText("آدرس : "+modelAddress.getAddress());
viewHolder.tvCity.setText(" شهر: "+modelAddress.getCity());
viewHolder.tvCityCap.setText(" استان : "+modelAddress.getCityCap());
viewHolder.tvPostalCode.setText(" کدپستی : "+modelAddress.getPostalcode());
// viewHolder.radioButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// for (int i = 0; i <idRadioButton.length ; i++) {
// RadioButton radioButtonset = ((Activity)context).findViewById(idRadioButton[i]);
// if (view.getId() == idRadioButton[i]){
// radioButtonset.setChecked(true);
// Toast.makeText(context, "true", Toast.LENGTH_SHORT).show();
// }else {
// radioButtonset.setChecked(false);
// Toast.makeText(context, "false", Toast.LENGTH_SHORT).show();
// }
// }
// }
// });
viewHolder.radioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RadioButton checked_rb = (RadioButton) view;
getAddressUser.onAddressUser(modelAddress.getName(),modelAddress.getFamily(),modelAddress.getAddress(),modelAddress.getCity(),modelAddress.getCityCap(),modelAddress.getMobile());
if(lastCheckedRB != null){
lastCheckedRB.setChecked(false);
}
lastCheckedRB = checked_rb;
}
});
}
public interface GetAddressUser {
void onAddressUser(String name,String family,String address,String city,String cityCap,String mobile);
}
@Override
public int getItemCount() {
return modelAddresses.size();
}
public class viewHolder extends RecyclerView.ViewHolder {
CardView cardView;
RadioButton radioButton;
TextView tvNameFamily,tvCityCap,tvCity,tvPhone,tvMobile,tvAddress,tvPostalCode;
public viewHolder(@NonNull View itemView) {
super(itemView);
radioButton =itemView.findViewById(R.id.rb_select);
tvNameFamily=itemView.findViewById(R.id.Tv_name_user);
tvCityCap=itemView.findViewById(R.id.Tv_ostan_user);
tvCity=itemView.findViewById(R.id.Tv_city);
tvAddress=itemView.findViewById(R.id.Tv_address);
tvPostalCode=itemView.findViewById(R.id.Tv_postalcode);
tvPhone=itemView.findViewById(R.id.Tv_phone_home);
tvMobile=itemView.findViewById(R.id.Tv_mobile);
cardView = itemView.findViewById(R.id.card_address);
}
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Fragments/FragmentOrderConfirmaton.java
package com.example.mybookstore.Fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.mybookstore.Adapters.AdapterAddressFragment;
import com.example.mybookstore.Models.ModelAddress;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.example.mybookstore.Utils.Put;
import com.example.mybookstore.Utils.UserSharedPrefrences;
import java.util.List;
import java.util.Objects;
/**
* A simple {@link Fragment} subclass.
*/
public class FragmentOrderConfirmaton extends Fragment {
RecyclerView recyclerView;
ApiServices apiServices ;
TextView tvAddressInfo;
CardView cardOrder;
String addressUser,nameUser,cityUser,cityCapUser,mobileUser,familyUser;
public FragmentOrderConfirmaton() {
// Required empty public constructor
}
public void AddressInfo(String name,String family,String address,String city,String cityCap,String mobile){
this.nameUser=name;
this.addressUser=address;
this.cityUser=city;
this.cityCapUser=cityCap;
this.mobileUser=mobile;
this.familyUser=family;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_order_confirmation, container, false);
cardOrder = view.findViewById(R.id.card_fragment_order);
tvAddressInfo = view.findViewById(R.id.tv_address_info);
String text = "تمامی مرسوله های انتخابی " +nameUser+" "+familyUser+" به آدرس " + cityCapUser + " ،"
+cityUser + " ،" +addressUser +" و به شماره تلفن " +mobileUser + " ارسال خواهد شد";
tvAddressInfo.setText(text);
cardOrder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
return view;
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Utils/UserSharedPrefrences.java
package com.example.mybookstore.Utils;
import android.content.Context;
import android.content.SharedPreferences;
public class UserSharedPrefrences {
private static final String USER_SHARED_PREF_NAME = "user_shared_pref";
private SharedPreferences sharedPreferences;
public UserSharedPrefrences(Context context) {
sharedPreferences = context.getSharedPreferences(USER_SHARED_PREF_NAME, Context.MODE_PRIVATE);
}
public void saveUserLoginInfo(String username,String image,String token){
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString(Put.username,username);
editor.putString(Put.token,token);
editor.putString(Put.image,image);
editor.apply();
}
public void saveUserLoginInfoHA(String username ,String token){
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString(Put.username,username);
editor.putString(Put.token,token);
editor.apply();
}
// public void saveUserLoginInfo(String username,String image){
// SharedPreferences.Editor editor =sharedPreferences.edit();
// editor.putString(Put.username,username);
// editor.putString(Put.image,image);
// editor.apply();
// }
public void exitFromAccount(){
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString(Put.username,"ورود/عضویت");
editor.putString(Put.image,"");
editor.apply();
}
public String getUserName(){
return sharedPreferences.getString(Put.username,"ورود/عضویت");
}
public String getUserImaje(){
return sharedPreferences.getString(Put.image,"");
}
public String getUserToken(){
return sharedPreferences.getString(Put.token,"");
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Utils/Put.java
package com.example.mybookstore.Utils;
public class Put {
public static final int REQUEST_CODE =220;
public static final int STATUS_FAILED=0;
public static final int STATUS_SUCCESS=218;
public static final int CHOOSE_GALLERY=2332;
public static final int EXTERNAL_STORAGE=3211;
public static final int STATUS_USER_EXIST =214;
public static final String FIELDS_NOT_FILLED ="01";
public static final String NOT_EXIST_IN_DB ="0";
public static final String VERFICATION_ERROR ="209";
public static final int REQUEST_EXIT =214;
static final String email = "email";
public static final String username = "username";
static final String address = "address";
public static final String name = "name";
public static final String total = "total";
static final String family = "family";
public static final String password = "<PASSWORD>";
public static final String token = "token";
public static final String code = "code";
public static final String postalcode = "postalcode";
public static final String repass = "<PASSWORD>";
public static final String phone = "phone";
public static final String mobile = "mobile";
public static final String image = "image";
public static final String price = "price";
public static final String label = "label";
public static final String id = "id";
public static final String title = "title";
public static final String visit = "visit";
public static final String offPrice = "offPrice";
static final String date = "date";
static final String only = "only";
static final String author = "author";
static final String publisher = "publisher";
public static final String cat = "cat";
public static final String desc = "desc";
static final String num_sold = "num_sold";
static final String comment = "comment";
static final String user = "user";
static final String rating = "rating";
static final String negative = "negative";
static final String positive = "positive";
static final String finalrating = "finalrating";
static final String params = "param";
public static final String links = "links";
public static final String record = "record";
public static String newuser="newuser";
}
<file_sep>/app/src/main/java/com/example/mybookstore/Adapters/AdapterAddress.java
package com.example.mybookstore.Adapters;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mybookstore.Models.ModelAddress;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import org.w3c.dom.Text;
import java.util.List;
public class AdapterAddress extends RecyclerView.Adapter<AdapterAddress.viewHolder> {
Context context;
List<ModelAddress> modelAddresses;
CardView cardViewPlace;
RecyclerView recyclerView;
OnEndLine onEndLine;
public AdapterAddress(Context context, List<ModelAddress> modelAddresses,CardView cardView,RecyclerView recyclerView,OnEndLine onEndLine) {
this.context = context;
this.modelAddresses = modelAddresses;
this.cardViewPlace=cardView;
this.recyclerView=recyclerView;
this.onEndLine=onEndLine;
}
@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_show_address,viewGroup,false);
return new viewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull viewHolder viewHolder, final int i) {
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dilaog_default);
dialog.show();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setCancelable(true);
TextView tvTitle,tvText,tvNegativ,tvPositive;
tvNegativ=dialog.findViewById(R.id.tv_dialog_negative);
tvPositive=dialog.findViewById(R.id.tv_dialog_positive);
tvText=dialog.findViewById(R.id.tv_dialog_text);
tvTitle=dialog.findViewById(R.id.tv_dialog_title);
tvNegativ.setText("حذف");
tvPositive.setText("ویرایش");
tvNegativ.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
ApiServices apiServices = new ApiServices(context);
apiServices.DelAddress(String.valueOf(modelAddresses.get(i).getIdAddress()), new ApiServices.OnAddressDeleted() {
@Override
public void onDeleted(boolean succeed) {
if (succeed){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
modelAddresses.remove(i);
notifyItemRemoved(i);
notifyItemRangeRemoved(i,modelAddresses.size());
if (modelAddresses.isEmpty()){
recyclerView.setVisibility(View.GONE);
cardViewPlace.setVisibility(View.VISIBLE);
onEndLine.onEnd(true);
}
}
},20);
dialog.dismiss();
Toast.makeText(context, "آدرس مورد نظر با موفقیت حذف شد", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "عملیات حذف با خطا مواجه شد لطفا دوباره سعی کنید", Toast.LENGTH_SHORT).show();
}
}
});
}
},500);
}
});
tvPositive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Handler handlerr = new Handler();
handlerr.postDelayed(new Runnable() {
@Override
public void run() {
}
},500);
}
});
tvTitle.setText("حذف یا ویرایش آدرس");
tvText.setText("آدرس خود را ویرایش یا حذف کنید!");
}
});
final ModelAddress modelAddress=modelAddresses.get(i);
viewHolder.tvNameFamily.setText(modelAddress.getName() + " " + modelAddress.getFamily());
viewHolder.tvMobile.setText("شماره تلفن ضروری : "+modelAddress.getMobile());
viewHolder.tvPhone.setText("شماره تلفن ثابت : "+modelAddress.getPhone());
viewHolder.tvAddress.setText("آدرس : "+modelAddress.getAddress());
viewHolder.tvCity.setText(" شهر: "+modelAddress.getCity());
viewHolder.tvCityCap.setText(" استان : "+modelAddress.getCityCap());
viewHolder.tvPostalCode.setText(" کدپستی : "+modelAddress.getPostalcode());
}
public interface OnEndLine{
void onEnd(boolean isEnd);
}
@Override
public int getItemCount() {
return modelAddresses.size();
}
public class viewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView tvNameFamily,tvCityCap,tvCity,tvPhone,tvMobile,tvAddress,tvPostalCode;
public viewHolder(@NonNull View itemView) {
super(itemView);
tvNameFamily=itemView.findViewById(R.id.Tv_name_user);
tvCityCap=itemView.findViewById(R.id.Tv_ostan_user);
tvCity=itemView.findViewById(R.id.Tv_city);
tvAddress=itemView.findViewById(R.id.Tv_address);
tvPostalCode=itemView.findViewById(R.id.Tv_postalcode);
tvPhone=itemView.findViewById(R.id.Tv_phone_home);
tvMobile=itemView.findViewById(R.id.Tv_mobile);
cardView = itemView.findViewById(R.id.card_address);
}
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Activities/MainActivity.java
package com.example.mybookstore.Activities;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.example.mybookstore.Adapters.AdapterBanner;
import com.example.mybookstore.Adapters.AdapterCategory;
import com.example.mybookstore.Adapters.AdapterCategoryLittleView;
import com.example.mybookstore.Adapters.AdapterOff;
import com.example.mybookstore.Adapters.AdapterProduct;
import com.example.mybookstore.Models.ModelBanner;
import com.example.mybookstore.Models.ModelCategory;
import com.example.mybookstore.Models.ModelOff_Only_MostVisit;
import com.example.mybookstore.Models.ModelSlider;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.example.mybookstore.Utils.Links;
import com.example.mybookstore.Utils.Put;
import com.example.mybookstore.Utils.UserSharedPrefrences;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity
implements BaseSliderView.OnSliderClickListener {
DrawerLayout drawer;
Toolbar toolbar;
ImageView imgShopCart,imgSearch;
CircleImageView circleImageView;
SliderLayout sliderLayout;
CardView cardCategory;
RecyclerView recyclerOff, recyclerCategory,recyclerOnly,
recyclerMostVisit,recyclerMostSold,recycBanner,recyBannerBig,recycCatLittle;
AdapterOff adapterOff;
TextView txtNaviLogin,txtCount,navAbout, navCat,navBasket,navAccount,
navFav,txtListOffs,txtListOnly,txtListMostVisit,txtListMostSold;
LinearLayout specialOffersLable;
String username,token;
ApiServices apiServices = new ApiServices(MainActivity.this);
UserSharedPrefrences userSharedPrefrences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
findViews();
setUpToolbar();
sliderInitialize();
recyclerInitialize();
onCliclks();
setUpNavigation();
}
private void findViews() {
userSharedPrefrences = new UserSharedPrefrences(MainActivity.this);
username = userSharedPrefrences.getUserName();
token=userSharedPrefrences.getUserToken();
recyclerOff = findViewById(R.id.offlist_recycler);
sliderLayout = findViewById(R.id.slider);
cardCategory = findViewById(R.id.card_category_main);
specialOffersLable = findViewById(R.id.specialOffers_lable);
recyclerCategory = findViewById(R.id.recycler_categoryList_main_activity);
recyclerOnly = findViewById(R.id.recycler_only);
recyclerMostVisit = findViewById(R.id.recycler_most_visited);
recyclerMostSold = findViewById(R.id.recycler_most_sold);
recycCatLittle = findViewById(R.id.recyc_cat_little);
txtCount=findViewById(R.id.txt_count_cart);
drawer = findViewById(R.id.drawer_layout);
imgShopCart=findViewById(R.id.img_shop_cart);
imgSearch=findViewById(R.id.img_search);
toolbar = findViewById(R.id.toolbar);
txtListMostSold = findViewById(R.id.txt_list_most_sold);
txtListMostVisit = findViewById(R.id.txt_list_most_visit);
txtListOnly = findViewById(R.id.txt_list_only);
txtListOffs = findViewById(R.id.txt_list_offs);
recycBanner = findViewById(R.id.recycler_banner);
recyBannerBig = findViewById(R.id.recycler_banner_big);
navAbout = findViewById(R.id.nav_about);
navBasket = findViewById(R.id.nav_basket);
navCat = findViewById(R.id.nav_list_category);
navAccount = findViewById(R.id.nav_account);
navFav = findViewById(R.id.nav_favorite);
drawer = findViewById(R.id.drawer_layout);
circleImageView = findViewById(R.id.img_circle_nav_header);
if (userSharedPrefrences.getUserImaje().equals("")){
Picasso.with(MainActivity.this).load(R.drawable.avatar).
error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(circleImageView);
}else {
Picasso.with(MainActivity.this).load(userSharedPrefrences.getUserImaje()).
error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(circleImageView);
}
txtNaviLogin = findViewById(R.id.txt_nav_login);
txtNaviLogin.setText(username);
}
private void setUpNavigation() {
if (!username.isEmpty()) {
txtNaviLogin.setText(username);
}
navAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (txtNaviLogin.getText().equals("ورود/عضویت")) {
startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), Put.REQUEST_CODE);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
drawer.closeDrawer(GravityCompat.START);
} else {
startActivityForResult(new Intent(MainActivity.this, ProfileActivity.class), Put.REQUEST_EXIT);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
drawer.closeDrawer(GravityCompat.START);
}
}
});
navCat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,CategoryActivity.class));
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
drawer.closeDrawer(GravityCompat.START);
}
});
navBasket.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (txtNaviLogin.getText().equals("ورود/عضویت")) {
drawer.closeDrawer(GravityCompat.START);
Toast.makeText(MainActivity.this, "لطفا وارد حساب کاربری خود شوید", Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(MainActivity.this, BasketActivity.class));
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
drawer.closeDrawer(GravityCompat.START);
}
}
});
navAbout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,AboutActivity.class));
drawer.closeDrawer(GravityCompat.START);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
});
navFav.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (txtNaviLogin.getText().equals("ورود/عضویت")) {
Toast.makeText(MainActivity.this, "وارد حساب کاربری خود شوید", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(MainActivity.this, FavoriteActivity.class);
intent.putExtra(Put.username, username);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
}
});
}
private void onCliclks() {
txtNaviLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (txtNaviLogin.getText().equals("ورود/عضویت")) {
startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), Put.REQUEST_CODE);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
} else {
startActivityForResult(new Intent(MainActivity.this, ProfileActivity.class), Put.REQUEST_EXIT);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
}
});
cardCategory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CatActivity_ViewPager.class));
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
});
imgShopCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (username.equals("ورود/عضویت")){
Toast.makeText(MainActivity.this, "لطفا وارد حساب خود شوید", Toast.LENGTH_SHORT).show();
}else {
startActivity(new Intent(MainActivity.this,BasketActivity.class));
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
}
});
imgSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,SearchActivity.class));
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
});
txtListOffs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,FullProductActivity.class);
intent.putExtra(Put.links,Links.GET_OFF);
startActivity(intent);
}
});
txtListOnly.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,FullProductActivity.class);
intent.putExtra(Put.links,Links.GET_ONLY);
startActivity(intent);
}
});
txtListMostVisit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,FullProductActivity.class);
intent.putExtra(Put.links,Links.GET_MOST_VISIT);
startActivity(intent);
}
});
txtListMostSold.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,FullProductActivity.class);
intent.putExtra(Put.links,Links.GET_MOST_VISIT);
startActivity(intent);
}
});
}
private void recyclerInitialize() {
apiServices.offReceived(Links.GET_OFF,new ApiServices.OnOffReceived() {
@Override
public void onOffReceived(List<ModelOff_Only_MostVisit> modelOffOnlies) {
if (modelOffOnlies.size() == 0) {
specialOffersLable.setVisibility(View.INVISIBLE);
recyclerOff.setVisibility(View.INVISIBLE);
} else {
adapterOff = new AdapterOff(modelOffOnlies, MainActivity.this);
recyclerOff.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false));
recyclerOff.hasFixedSize();
recyclerOff.setAdapter(adapterOff);
}
}
});
apiServices.categoryReceive(new ApiServices.OnCategoryReceived() {
@Override
public void onCatReceived(List<ModelCategory> modelCategories) {
AdapterCategoryLittleView adapterCategoryLittleView = new AdapterCategoryLittleView(MainActivity.this, modelCategories);
recycCatLittle.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false));
recycCatLittle.hasFixedSize();
recycCatLittle.setAdapter(adapterCategoryLittleView);
}
});
apiServices.categoryReceive(new ApiServices.OnCategoryReceived() {
@Override
public void onCatReceived(List<ModelCategory> modelCategories) {
AdapterCategory adapterCategory = new AdapterCategory(MainActivity.this, modelCategories);
recyclerCategory.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false));
recyclerCategory.hasFixedSize();
recyclerCategory.setAdapter(adapterCategory);
}
});
apiServices.onlyReceived(Links.GET_ONLY,new ApiServices.OnOnlyReceived() {
@Override
public void onOnlyReceived(List<ModelOff_Only_MostVisit> modelOnlies) {
AdapterProduct adapterProduct = new AdapterProduct(MainActivity.this,modelOnlies);
recyclerOnly.setLayoutManager(new LinearLayoutManager(MainActivity.this,LinearLayoutManager.HORIZONTAL,false));
recyclerOnly.hasFixedSize();
recyclerOnly.setAdapter(adapterProduct);
}
});
apiServices.MostvisitReceived(Links.GET_MOST_VISIT,new ApiServices.OnMostVisitReceived() {
@Override
public void onMostVisit(List<ModelOff_Only_MostVisit> modelMostVisit) {
AdapterProduct adapterProduct = new AdapterProduct(MainActivity.this,modelMostVisit);
recyclerMostVisit.setLayoutManager(new LinearLayoutManager(MainActivity.this,LinearLayoutManager.HORIZONTAL,false));
recyclerMostVisit.hasFixedSize();
recyclerMostVisit.setAdapter(adapterProduct);
}
});
apiServices.MostSoldReceived(Links.GET_MOST_SOLD,new ApiServices.OnMostSoldReceived() {
@Override
public void onSold(List<ModelOff_Only_MostVisit> modelSold) {
AdapterProduct adapterProduct = new AdapterProduct(MainActivity.this,modelSold);
recyclerMostSold.setLayoutManager(new LinearLayoutManager(MainActivity.this,LinearLayoutManager.HORIZONTAL,false));
recyclerMostSold.hasFixedSize();
recyclerMostSold.setAdapter(adapterProduct);
}
});
apiServices.GetBanners(new ApiServices.OnBannerReceived() {
@Override
public void onBanner(List<ModelBanner> modelBanners) {
AdapterBanner adapterBanner = new AdapterBanner(MainActivity.this,modelBanners);
recycBanner.setLayoutManager(new GridLayoutManager(MainActivity.this,2));
recycBanner.hasFixedSize();
recycBanner.setAdapter(adapterBanner);
}
});
apiServices.GetBannerBig(new ApiServices.OnBannerReceived() {
@Override
public void onBanner(List<ModelBanner> modelBanners) {
AdapterBanner adapterBanner = new AdapterBanner(MainActivity.this,modelBanners);
recyBannerBig.setLayoutManager(new GridLayoutManager(MainActivity.this,1));
recyBannerBig.hasFixedSize();
recyBannerBig.setAdapter(adapterBanner);
}
});
}
private void sliderInitialize() {
apiServices.GetSliders(new ApiServices.OnSliderReceived() {
@Override
public void onSlider(List<ModelSlider> modelSliders) {
HashMap<String, String> url_image = new HashMap<>();
for (int i = 0; i < modelSliders.size(); i++) {
url_image.put(modelSliders.get(i).getName(),modelSliders.get(i).getImage());
}
for (int i = 0; i < url_image.keySet().size(); i++) {
String keyname = url_image.keySet().toArray()[i].toString();
TextSliderView textSliderView = new TextSliderView(MainActivity.this);
textSliderView
.description(keyname)
.image(url_image.get(keyname))
.setOnSliderClickListener(MainActivity.this)
.empty(R.drawable.placeholder)
.error(R.drawable.placeholder)
.setScaleType(BaseSliderView.ScaleType.Fit);
textSliderView.bundle(new Bundle());
textSliderView.getBundle()
.putString("extra", keyname);
sliderLayout.setDuration(3000);
sliderLayout.addSlider(textSliderView);
}
}
});
// HashMap<String, String> url_image = new HashMap<>();
// url_image.put("image1",Links.Link_HOST + "/samed_bookstore/uploads/banners/banner4.jpg");
// url_image.put("image2",Links.Link_HOST + "/samed_bookstore/uploads/banners/banner1.jpg");
// url_image.put("image3",Links.Link_HOST + "/samed_bookstore/uploads/banners/banner7.jpg");
// url_image.put("image4",Links.Link_HOST + "/samed_bookstore/uploads/banners/banner8.jpg");
//
// for (int i = 0; i < url_image.keySet().size(); i++) {
// String keyname = url_image.keySet().toArray()[i].toString();
// TextSliderView textSliderView = new TextSliderView(MainActivity.this);
// textSliderView
//// .description(keyname)
// .image(url_image.get(keyname))
// .setOnSliderClickListener(this)
// .empty(R.drawable.placeholder)
// .error(R.drawable.placeholder)
// .setScaleType(BaseSliderView.ScaleType.Fit);
//
// textSliderView.bundle(new Bundle());
// textSliderView.getBundle()
// .putString("extra", keyname);
// sliderLayout.setDuration(3000);
// sliderLayout.addSlider(textSliderView);
// }
}
private void setUpToolbar() {
setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (username != null && username.equals("ورود/عضویت")){
imgShopCart.setColorFilter(Color.rgb(170,170,170));
txtCount.setVisibility(View.GONE);
}
}
@SuppressLint("SetTextI18n")
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Put.REQUEST_CODE && resultCode == RESULT_OK) {
if (data != null) {
String username = data.getStringExtra(Put.username);
String image = data.getStringExtra(Put.image);
txtNaviLogin.setText("خوش آمدید " + username);
Picasso.with(MainActivity.this).load(image)
.placeholder(R.drawable.avatar)
.error(R.drawable.avatar)
.into(circleImageView);
recreate();
}
} else if (requestCode == Put.REQUEST_EXIT && resultCode == RESULT_OK) {
if (data != null) {
String username = data.getStringExtra(Put.username);
String image = data.getStringExtra(Put.image);
if (image.equals("")){
Picasso.with(MainActivity.this).load(R.drawable.banner2).
error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(circleImageView);
}else {
Picasso.with(MainActivity.this).load(userSharedPrefrences.getUserImaje()).
error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(circleImageView);
}
txtNaviLogin.setText(username);
recreate();
}
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public void onSliderClick(BaseSliderView slider) {
String s = slider.getBundle().get("extra") + "";
// switch (s) {
// case ("image1"):
// Toast.makeText(this, "عکس شماره 1", Toast.LENGTH_SHORT).show();
// break;
// case ("image2"):
// Toast.makeText(this, "عکس شماره 2", Toast.LENGTH_SHORT).show();
// break;
// case ("image3"):
// Toast.makeText(this, "عکس شماره 3", Toast.LENGTH_SHORT).show();
// break;
// case ("image4"):
// Toast.makeText(this, "عکس شماره 4", Toast.LENGTH_SHORT).show();
// break;
//
//
// }
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onStart() {
super.onStart();
apiServices.GetCount(token, new ApiServices.OnCountReceived() {
@Override
public void onCount(String count) {
txtCount.setText(count);
}
});
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Adapters/AdapterOff.java
package com.example.mybookstore.Adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mybookstore.Activities.ShowActivity;
import com.example.mybookstore.Models.ModelOff_Only_MostVisit;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.Links;
import com.example.mybookstore.Utils.Put;
import com.squareup.picasso.Picasso;
import java.text.DecimalFormat;
import java.util.List;
import jp.shts.android.library.TriangleLabelView;
public class AdapterOff extends RecyclerView.Adapter<AdapterOff.viewHolder> {
private List<ModelOff_Only_MostVisit> modelOffOnlies;
private Context context;
public AdapterOff(List<ModelOff_Only_MostVisit> modelOffOnlies, Context context) {
this.modelOffOnlies = modelOffOnlies;
this.context = context;
}
@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(context).inflate(R.layout.item_show_off,viewGroup,false);
return new viewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull final AdapterOff.viewHolder viewHolder, final int i) {
DecimalFormat decimalFormat = new DecimalFormat("###,###");
viewHolder.txtPrice.setText(decimalFormat.format(Float.valueOf(modelOffOnlies.get(i).getOffPrice()))+" "+"تومان");
viewHolder.txtVisit.setText(modelOffOnlies.get(i).getVisit());
viewHolder.txtTitle.setText(modelOffOnlies.get(i).getTitle());
viewHolder.txtoffPrice.setText(decimalFormat.format(Integer.valueOf(modelOffOnlies.get(i).getPrice()))+" "+"تومان");
viewHolder.txtoffPrice.setPaintFlags(viewHolder.txtoffPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
viewHolder.triangleLabelView.setSecondaryText(modelOffOnlies.get(i).getLable());
Picasso.with(context)
.load(modelOffOnlies.get(i).getImage())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(viewHolder.imgOff);
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(viewHolder.itemView.getContext(), ShowActivity.class);
intent.putExtra(Put.id,modelOffOnlies.get(i).getId()+"");
intent.putExtra(Put.offPrice,modelOffOnlies.get(i).getOffPrice());
intent.putExtra(Put.cat,modelOffOnlies.get(i).getCat());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return modelOffOnlies.size();
}
class viewHolder extends RecyclerView.ViewHolder{
CardView cardView;
TriangleLabelView triangleLabelView;
ImageView imgOff;
TextView txtTitle,txtVisit,txtPrice,txtoffPrice;
viewHolder(@NonNull View itemView) {
super(itemView);
cardView=itemView.findViewById(R.id.cardview_product);
triangleLabelView = itemView.findViewById(R.id.triangle_product);
imgOff = itemView.findViewById(R.id.img_product);
txtTitle = itemView.findViewById(R.id.txt_title_product);
txtPrice = itemView.findViewById(R.id.txt_price_product);
txtVisit = itemView.findViewById(R.id.txt_visit_product);
txtoffPrice = itemView.findViewById(R.id.txt_price_off);
}
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Fragments/FragmentOrder.java
package com.example.mybookstore.Fragments;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.Toast;
import com.example.mybookstore.Activities.BasketActivity;
import com.example.mybookstore.Activities.EditInformation;
import com.example.mybookstore.Adapters.AdapterAddressFragment;
import com.example.mybookstore.Adapters.AdapterBasket;
import com.example.mybookstore.Models.ModelAddress;
import com.example.mybookstore.Models.ModelBasket;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.example.mybookstore.Utils.Links;
import com.example.mybookstore.Utils.Put;
import com.example.mybookstore.Utils.UserSharedPrefrences;
import com.pnikosis.materialishprogress.ProgressWheel;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Objects;
/**
* A simple {@link Fragment} subclass.
*/
public class FragmentOrder extends Fragment {
RecyclerView recyclerViewAddress,recyclerViewProducts;
ProgressWheel progressWheel;
ApiServices apiServices ;
CheckBox checkBoxFactor;
CardView cardOrder,cardPlaceHolder;
String nameUser,addressUser,cityUser,cityCapUser,mobileUser,familyUser;
public FragmentOrder() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_order, container, false);
String token = Objects.requireNonNull(getActivity()).getIntent().getStringExtra(Put.token);
recyclerViewAddress = view.findViewById(R.id.recycler_fragment_order_address);
recyclerViewProducts = view.findViewById(R.id.recycler_fragment_order_products);
cardPlaceHolder = view.findViewById(R.id.card_placeholder);
checkBoxFactor = view.findViewById(R.id.chk_factor);
checkBoxFactor.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), Links.LINK_FONT_VAZIR));
progressWheel = view.findViewById(R.id.progress_wheel);
apiServices = new ApiServices(getActivity());
apiServices.GetAddress(token, new ApiServices.OnAddressReceived() {
@Override
public void onReceived(List<ModelAddress> modelAddresses) {
AdapterAddressFragment adapterAddress = new AdapterAddressFragment(getActivity(), modelAddresses, new AdapterAddressFragment.GetAddressUser() {
@Override
public void onAddressUser(String name,String family ,String address, String city, String cityCap, String mobile) {
nameUser=name;
addressUser=address;
cityUser=city;
cityCapUser=cityCap;
mobileUser=mobile;
familyUser=family;
}
});
if (modelAddresses.isEmpty()){
cardPlaceHolder.setVisibility(View.VISIBLE);
recyclerViewAddress.setVisibility(View.GONE);
}else {
recyclerViewAddress.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false));
recyclerViewAddress.setAdapter(adapterAddress);
recyclerViewAddress.hasFixedSize();
}
}
});
cardPlaceHolder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),EditInformation.class);
startActivity(intent);
}
});
apiServices.CartReceived(progressWheel,token, new ApiServices.OnCartReceived() {
@Override
public void onReceived(List<ModelBasket> modelBaskets, int totalPrice) {
AdapterBasket adapterBasket = new AdapterBasket(getActivity(),modelBaskets);
recyclerViewProducts.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false));
recyclerViewProducts.setAdapter(adapterBasket);
}
});
cardOrder = view.findViewById(R.id.card_fragment_order);
cardOrder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (addressUser == null || addressUser.equals("")){
Toast.makeText(getActivity(), "لطفا آدرس را جهت ارسال مرسوله انتخاب کنید" , Toast.LENGTH_SHORT).show();
}else {
FragmentManager fragmentManager = getFragmentManager();
FragmentOrderConfirmaton fragmentOrderConfirmaton = new FragmentOrderConfirmaton();
fragmentOrderConfirmaton.AddressInfo(nameUser,familyUser,addressUser,cityUser,cityCapUser,mobileUser);
FragmentTransaction transaction = Objects.requireNonNull(fragmentManager).beginTransaction();
transaction.replace(R.id.rel_root,fragmentOrderConfirmaton).addToBackStack("");
transaction.commit();
}
}
},1000);
}
});
return view;
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Adapters/AdapterProduct.java
package com.example.mybookstore.Adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mybookstore.Activities.ShowActivity;
import com.example.mybookstore.Models.ModelOff_Only_MostVisit;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.Links;
import com.example.mybookstore.Utils.Put;
import com.squareup.picasso.Picasso;
import java.text.DecimalFormat;
import java.util.List;
import jp.shts.android.library.TriangleLabelView;
public class AdapterProduct extends RecyclerView.Adapter<AdapterProduct.viewHolder> {
private Context context;
private List<ModelOff_Only_MostVisit> modelProduct;
public AdapterProduct(Context context, List<ModelOff_Only_MostVisit> modelProduct) {
this.context = context;
this.modelProduct = modelProduct;
}
@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_show_product,viewGroup,false);
return new viewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final viewHolder viewHolder, final int i) {
DecimalFormat decimalFormat = new DecimalFormat("###,###");
if (Integer.valueOf(modelProduct.get(i).getLable()) > 0){
viewHolder.txtPrice.setText(decimalFormat.format(Float.valueOf(modelProduct.get(i).getOffPrice()))+" "+"تومان");
viewHolder.txtVisit.setText(modelProduct.get(i).getVisit());
viewHolder.txtTitle.setText(modelProduct.get(i).getTitle());
viewHolder.triangleLabelView.setSecondaryText(modelProduct.get(i).getLable());
Picasso.with(context)
.load(modelProduct.get(i).getImage())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(viewHolder.imgOnly);
}else {
viewHolder.txtPrice.setText(decimalFormat.format(Integer.valueOf(modelProduct.get(i).getPrice()))+" "+"تومان");
viewHolder.txtVisit.setText(modelProduct.get(i).getVisit());
viewHolder.txtTitle.setText(modelProduct.get(i).getTitle());
viewHolder.triangleLabelView.setVisibility(View.GONE);
Picasso.with(context)
.load(modelProduct.get(i).getImage())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(viewHolder.imgOnly);
}
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(viewHolder.itemView.getContext(), ShowActivity.class);
intent.putExtra(Put.id,modelProduct.get(i).getId()+"");
intent.putExtra(Put.offPrice,modelProduct.get(i).getOffPrice());
intent.putExtra(Put.cat,modelProduct.get(i).getCat());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return modelProduct.size();
}
class viewHolder extends RecyclerView.ViewHolder{
CardView cardView;
TriangleLabelView triangleLabelView;
ImageView imgOnly;
TextView txtTitle,txtVisit,txtPrice;
viewHolder(@NonNull View itemView) {
super(itemView);
cardView=itemView.findViewById(R.id.cardview_product);
triangleLabelView = itemView.findViewById(R.id.triangle_product);
imgOnly = itemView.findViewById(R.id.img_product);
txtTitle = itemView.findViewById(R.id.txt_title_product);
txtPrice = itemView.findViewById(R.id.txt_price_product);
txtVisit = itemView.findViewById(R.id.txt_visit_product);
}
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Activities/BannerActivity.java
package com.example.mybookstore.Activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mybookstore.Adapters.AdapterItemProduct;
import com.example.mybookstore.Models.ModelItemProduct;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.example.mybookstore.Utils.Put;
import java.util.List;
public class BannerActivity extends AppCompatActivity {
private TextView txtTitle;
private ImageView imgBackButton;
private RecyclerView recyBannerItem;
private ApiServices apiServices;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_banner);
finViews();
onClicks();
initPage();
}
private void initPage() {
String id = String.valueOf(getIntent().getIntExtra(Put.id,0));
apiServices = new ApiServices(BannerActivity.this);
apiServices.GetItemBanner(id, new ApiServices.OnItemBannerReceived() {
@Override
public void onItemReceived(List<ModelItemProduct> modelItemProducts) {
AdapterItemProduct adapterItemProduct = new AdapterItemProduct(BannerActivity.this,modelItemProducts);
recyBannerItem.setLayoutManager(new LinearLayoutManager(BannerActivity.this));
recyBannerItem.setAdapter(adapterItemProduct);
recyBannerItem.hasFixedSize();
}
});
}
private void finViews() {
txtTitle = findViewById(R.id.txt_title_toolbar_second);
txtTitle.setText("محصولات");
imgBackButton = findViewById(R.id.img_back_second_toolbar);
recyBannerItem = findViewById(R.id.recycler_banner_item);
}
private void onClicks() {
imgBackButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Activities/RegisterActivity.java
package com.example.mybookstore.Activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.ApiServices;
import com.pnikosis.materialishprogress.ProgressWheel;
public class RegisterActivity extends AppCompatActivity {
EditText edUsername,edPassword;
TextView txtTitle;
CardView cardRegister;
CheckBox checkBox;
ImageView imgBack;
ApiServices apiServices;
ProgressWheel progressWheel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg);
findViews();
onClicks();
}
private void onClicks() {
imgBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
edPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}else {
edPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
cardRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!edPassword.getText().toString().trim().equals("")&&!edUsername.getText().toString().trim().equals("")){
if (!(edPassword.getText().toString().trim().length() <4)){
String username=convertNumberToEnglish(edUsername.getText().toString().trim());
String password=convertNumberToEnglish(edPassword.getText().toString().trim());
// Toast.makeText(RegisterActivity.this, username, Toast.LENGTH_SHORT).show();
apiServices.registeWhitSMS(username,password,progressWheel);
}else{
edPassword.setError("پسورد حداقل باید چهار کاراکتر باشد");
edPassword.requestFocus();
}
}else{
edUsername.setError("لطفا نام کاربری و پسورد را وارد کنید");
edPassword.setError("لطفا نام کاربری و پسورد را وارد کنید");
edUsername.requestFocus();
}
}
});
}
private String convertNumberToEnglish(String num) {
String d = num;
d = d.replace("۰", "0");
d = d.replace("۱", "1");
d = d.replace("۲", "2");
d = d.replace("٣", "3");
d = d.replace("٤", "4");
d = d.replace("۵", "5");
d = d.replace("٦", "6");
d = d.replace("٧", "7");
d = d.replace("۸", "8");
d = d.replace("۹", "9");
d = d.replace("۰", "0");
d = d.replace("۱", "1");
d = d.replace("۲", "2");
d = d.replace("۳", "3");
d = d.replace("۴", "4");
d = d.replace("۵", "5");
d = d.replace("۶", "6");
d = d.replace("۷", "7");
d = d.replace("۸", "8");
d = d.replace("۹", "9");
return d;
}
private void findViews() {
apiServices = new ApiServices(RegisterActivity.this);
txtTitle = findViewById(R.id.txt_title_toolbar_second);
txtTitle.setText("ثبت نام");
cardRegister = findViewById(R.id.card_Register);
progressWheel=findViewById(R.id.progress_wheel);
edPassword = findViewById(R.id.ed_password);
edUsername = findViewById(R.id.ed_phone);
edUsername.requestFocus();
imgBack = findViewById(R.id.img_back_second_toolbar);
checkBox = findViewById(R.id.checkbox_reg);
}
}
<file_sep>/app/src/main/java/com/example/mybookstore/Adapters/AdapterComment.java
package com.example.mybookstore.Adapters;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RatingBar;
import android.widget.TextView;
import com.example.mybookstore.Models.ModelComment;
import com.example.mybookstore.R;
import com.example.mybookstore.Utils.Links;
import com.squareup.picasso.Picasso;
import com.willy.ratingbar.ScaleRatingBar;
import java.lang.reflect.Type;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class AdapterComment extends RecyclerView.Adapter<AdapterComment.viewHolder> {
Context context;
List<ModelComment> modelComments;
public AdapterComment(Context context, List<ModelComment> modelComments) {
this.context = context;
this.modelComments = modelComments;
}
@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_show_comments,viewGroup,false);
return new viewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull viewHolder viewHolder, int i) {
ModelComment comment = modelComments.get(i);
viewHolder.txtUser.setText(comment.getUser());
viewHolder.txtPositive.setText(comment.getPositive());
viewHolder.txtNegative.setText(comment.getNegative());
viewHolder.txtComment.setText(comment.getComment());
//
// Picasso.with(context).load(comment.getImage())
// .error(R.drawable.placeholder)
// .placeholder(R.drawable.placeholder)
// .into(viewHolder.circleImageView);
viewHolder.ratingBar.setRating(comment.getRating());
}
@Override
public int getItemCount() {
return modelComments.size();
}
class viewHolder extends RecyclerView.ViewHolder{
TextView txtComment,txtUser,txtPositive,txtNegative;
// CircleImageView circleImageView;
ScaleRatingBar ratingBar;
viewHolder(@NonNull View itemView) {
super(itemView);
txtComment=itemView.findViewById(R.id.txt_commnet);
txtNegative=itemView.findViewById(R.id.txt_negativeComment);
txtPositive=itemView.findViewById(R.id.txt_posotiveComment);
txtUser=itemView.findViewById(R.id.txt_usercomment);
// circleImageView = itemView.findViewById(R.id.img_userComment);
ratingBar = itemView.findViewById(R.id.rating_comment);
}
}
}
| e48ced0b67f0b7edb7c82221be9578ba84963a29 | [
"Java"
] | 26 | Java | majiddeh/MyBookStore | 937ae92103170ed9dcdd241605ceff424bd54cd6 | 6315d22fed2bca8992a8fd313159881db9ca5f5e | |
refs/heads/master | <file_sep>import React from 'react'
class PageNotFound extends React.Component {
render() {
return (
<div>
The page you requested is not available right now.
<h1>Page Not Found.</h1>
<h2>Error 404</h2>
</div>
)
}
}
export default PageNotFound
<file_sep># MyReads - <NAME>
A project based on Books sorting according to -
- Currently Reading
- Want to Read
- Read
and user can search the books and sort according his needs.
Installation Instructions -
1) npm install ------ Install dependencies
2) npm start ------ Start the app | de72b94b6e34526fe7e5a5f388edbdad2ee0423c | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | t009s/my-reads | 0fc620ce6509be1281252ce057ff21ff63979ab5 | f4e851bff855fd22791a30232ab0307620014366 | |
refs/heads/master | <file_sep>$(document).ready(function() {
var $btn = $('#run-mad-lib');
var $mad_lib = $('.mad-lib');
//grab all the input values
var noun = $('#noun').val();
var us_state = $('#us-state').val();
var a = $('#adjective').val();
var t_of_d = $('#type-of-drink').val();
var slang = $('#slang').val();
$btn.click(function() {
// var words_array = [noun, us_state, a, t_of_d, slang]
var words_array = ['cat', 'florida', 'happy', 'corona', 'dopest'];
var gif_array = [];
for (i = 0; i < words_array.length; i++) {
$.ajax({
url: "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" + words_array[i],
async: false
}).done(function(gif) {
gif_array.push(gif.data.image_url);
});
}
console.log(gif_array);
//build DOM element
var mad_lib_gif = "<div><p>Jimmy and Karen decided one day that they were going to get their whole family together for a";
mad_lib_gif += "<img src='" + gif_array[0] + "'/>. ";
mad_lib_gif += "They decided to go to <img src='" + gif_array[1] + "'/>. ";
mad_lib_gif += "First to join them were Jim and Katie. Then Jamie, Jessica, Avery, Luke, Sydney, Connor and Jack followed.";
mad_lib_gif += " They were all so <img src='" + gif_array[2] + "' />!";
mad_lib_gif += " Once they got to <img src'" + gif_array[1] + "'/>, they immediately went straight to the toilet. It was so much fun!";
mad_lib_gif += " Jim poured himself too many <img src='" + gif_array[3] + "'/>, and landed himself in the hospital! Oh no!";
mad_lib_gif += " Then finally, Abhi, Brian & Brad arrived. This was cool, because they are the coolest <img src='" + gif_array[4] + "'/> out of the group. Especially Abhi.";
mad_lib_gif += "</div>";
//attach to page
$mad_lib.children().remove();
$mad_lib.append(mad_lib_gif);
});
})
| 349969bfa31227ad9027e3302deb2ba1169effb6 | [
"JavaScript"
] | 1 | JavaScript | abhisharma2/mad-lib-gif | b12c8a94d3aa2a1241ab460b3b73bd031edf6d7a | 9ed9aa3ff92dc86727dd2081f7d87bbee4febbd5 | |
refs/heads/master | <repo_name>mrVanboy/zonky-api-example<file_sep>/Makefile
DEVELOP_CONTAINER_NAME=zonky_docker_node_dev
DEVELOP_IMAGE=node:latest
.PHONY: help
# HELP
# This will output the help for each task
# thanks to https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
help: ## This help.
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
.DEFAULT_GOAL := help
docker-develop: ## Start docker container with development environment
@ docker run \
--name $(DEVELOP_CONTAINER_NAME) \
-p 4200:4200 \
-v $(PWD):/app \
-ti \
--entrypoint bash \
$(DEVELOP_IMAGE)
docker-stop: ## Stop docker environment container and remove it
@ docker rm $(DEVELOP_CONTAINER_NAME)
up: ## Up docker compose with builded aplication
@ docker-compose up
down: ## Down docker-compose containers with app
@ docker-compose down
build: ## Build docker-compose images
@ docker-compose build
build-up: build up ## Build and up docker-compose containers<file_sep>/Dockerfile
FROM node:10.3-alpine as build-env
COPY ./package.json ./package-lock.json /
RUN npm set progress=false && npm config set depth 0 && npm cache clean --force
## Storing node modules on a separate layer will prevent unnecessary npm installs at each build
RUN npm i && mkdir /app && cp -R ./node_modules ./app
COPY . /app
WORKDIR /app
RUN $(npm bin)/ng build --prod --build-optimizer --output-path /app/dist
# ++++++++++++++++++++++++++++
FROM nginx:1.14-alpine
MAINTAINER <NAME> <<EMAIL>>
COPY --from=build-env /app/dist /usr/share/nginx/html
<file_sep>/README.md
# Zonky Api Example
Example project that using [Zonky API](https://zonky.docs.apiary.io/#).
> **YOU MUST DISABLE CROSS-ORIGIN SECURITY IN BROWSER**
> Ex. Chrome must be lauched with parameters: `google-chrome --disable-web-security --user-data-dir`
## Development server
You can use classic way of the development with local instance of node or
here is prepared *Makefile* with dockerized environment.
```bash
make docker-develop
# Next commands must be runned inside docker container
cd /app
npm start -- --host=0.0.0.0
```
After that just open `localhost:400` in your browser.
## Build
Resulted image is builded with *docker-compose* and *Makefile* contain
prepared tasks.
Run `make up`, wait until container will be prepared and open
[localhost:8080](http://localhost:8080).
<file_sep>/docker-compose.yml
version: "3"
services:
zonky-api-example:
build: .
ports:
- 8080:80
<file_sep>/src/app/app.component.ts
import {Component} from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {HttpObserve} from "@angular/common/http/src/client";
import {isArray} from "util";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(private http: HttpClient) {
}
result: string = 'Select the rating';
ratingArray = [
new Rating('A**', 'AAAAA'),
new Rating('A*', 'AAAA'),
new Rating('A++', 'AAA'),
new Rating('A+', 'AA'),
new Rating('A', 'A'),
new Rating('B', 'B'),
new Rating('C', 'C'),
new Rating('D', 'D'),
];
onSelectChange(newValue: string) {
this.sendRequest(newValue);
this.result = 'Loading...'
}
private static url = 'https://api.zonky.cz/loans/marketplace?fields=id,amount&&rating__eq=';
private loadAllItems(v: string, totalNumber: number) {
const options = {
headers: new HttpHeaders().set('X-Size', totalNumber.toString()),
};
this.http.get(AppComponent.url + v, options).subscribe(res => {
this.calculateAverage(res)
});
}
private calculateAverage(res: any) {
let sum = 0;
let q = 0;
if (isArray(res)) {
res.forEach(value => {
if (value.hasOwnProperty('amount')) {
sum += value.amount;
q++;
} else {
console.warn('Can\'t parse loan object: ', value)
}
});
let avg = sum / q;
this.result = 'Average amount: ' + avg.toFixed(2)
}
else {
this.result = 'No loans available'
}
}
private sendRequest(v: string) {
let httpObserve: HttpObserve = 'response';
const options = {
headers: new HttpHeaders().set('X-Size', '1'),
observe: httpObserve,
};
this.http.head(AppComponent.url + v, options).subscribe(res => {
let sNumber = res.headers.get('X-Total');
let number = parseInt(sNumber);
this.loadAllItems(v, number)
});
}
}
class Rating {
name: string;
value: string;
constructor(name, value: string) {
this.name = name;
this.value = value;
}
}
| 52fdf33aed5acd416425ee46d721d4c32263446e | [
"YAML",
"Markdown",
"Makefile",
"TypeScript",
"Dockerfile"
] | 5 | Makefile | mrVanboy/zonky-api-example | 08859a9d8a5cbdb40d51cf774d5afdf2fb726cab | daa134696730eb281dfa701a970a530b41ff090f | |
refs/heads/master | <repo_name>ems-invirohub/kingAPI<file_sep>/Dockerfile
FROM node
MAINTAINER <NAME> <<EMAIL>>
ADD . usr/src/app
WORKDIR /usr/src/app
RUN npm install
EXPOSE 8080
CMD ["node", "server.js" ]<file_sep>/plugins/utils/plugin.js
'use strict';
exports.register = (server, option, next) => {
server.route({
method: 'GET',
path: '/utils',
handler: (request, reply) => reply('Testing Testing')
});
next();
};
exports.register.attributes = {name: 'routes-utils'};<file_sep>/config.js
let config = {};
config.rethink = {};
config.hapi = {};
config.remote = {};
config.billing = { };
//local
config.rethink.host = 'localhost';
config.rethink.port = 32769;
config.hapi.port = 3011;
module.exports = config;<file_sep>/routes.js
'use strict';
const routes = [].concat(
require('./plugins/utils/plugin')
);
module.exports = routes;
<file_sep>/server.js
'use strict';
const Hapi = require('hapi'),
Hoek = require('hoek'),
r = require('rethinkdb'),
config = require('./config'),
goodOptions = require('./good-options');
const server = new Hapi.Server();
server.connection({ port: config.hapi.port, routes: {cors: true} });
const connectRethink = function(cb) {
r.connect(config.rethink, (err, conn) => {
if(err) {
console.log(config.rethink);
console.log(err.message);
}
cb(err, conn);
});
};
const closeRethink = function(conn) {
conn.close((err) => {
if(err) console.error(err);
});
};
server.method('rConnect', connectRethink);
server.method('rClose', closeRethink);
server.register(require('./routes'), (err) => {
if(err){
throw err;
} else {
server.start((err) => {
Hoek.assert(!err, err);
console.log(`Server listening at ${server.info.uri}`);
});
}
});
server.register({
register: require('good'),
goodOptions
});
| eb6181a6bd5a52ec8d721f7af124b58e1e8cdda4 | [
"JavaScript",
"Dockerfile"
] | 5 | Dockerfile | ems-invirohub/kingAPI | 121bfe24084ee944c656db14163a23357c929d81 | 7e51e0a20ad44bf5110867a4defb95945073b9d5 | |
refs/heads/master | <repo_name>Samad-Ullah/CoffeeCafe<file_sep>/Project Coffee Cafe.md
# CoffeeCafe
In this project i am worked on Authentication of firebase.
I learned All from a youtube channel https://www.youtube.com/watch?v=aN1LnNq4z54&list=PL4cUxeGkcC9jUPIes_B8vRjn1_GaplOPQ
This is actually a good platorm to make web , android and many other applications.
In this projet i used one Cloud function that authtenticate the admin panel which is only for admins.
Coffee detail page is viewed by admin as well as new user.
admin make new user to admin if he wants.
All data store in fireabase collection named CofeeCollection.
<file_sep>/javascript/index.js
const coffeeList = document.querySelector('.coffeess');
const linksLoggedIn = document.querySelectorAll('.logged-in');
const linksLoggedOut = document.querySelectorAll('.logged-out');
const account = document.querySelector('.account-details');
const adminitems =document.querySelectorAll('.admin');
// toggle UI Elements
const navbarlinks = (user) =>{
if(user){
if(user.admin){
adminitems.forEach(item => item.style.display="block");
}
// account info.
const html=`
<div>loged In as ${user.email}</div>
<div style="color: pink;">${user.admin? "admin" : ""}</div>
`;
account.innerHTML=html;
linksLoggedIn.forEach(item => item.style.display ='block');
linksLoggedOut.forEach(item =>item.style.display ='none');
}else{
// All logout scenario
adminitems.forEach(item => item.style.display="none");
account.innerHTML='';
linksLoggedIn.forEach(item =>item.style.display ='none');
linksLoggedOut.forEach(item =>item.style.display ='block');
}
}
const setupCoffee = (data) =>{
let html = '';
data.forEach(doc => {
const coffee =doc.data();
const li = `
<li>
<div class="collapsible-header grey >${coffee.Price}</div>
<div class="collapsible-body white>${coffee.CoffeeName}</div>
<div class="collapsible-body white>${coffee.Description}</div>
</li>
`;
html += li;
});
coffeeList.innerHTML= html;
};
document.addEventListener('DOMContentLoaded', (e) => {
var modals = document.querySelectorAll('.modal');
M.Modal.init(modals);
var items = document.querySelectorAll('.collapsible');
M.Collapsible.init(items);
});<file_sep>/javascript/Authentication.js
// for cloud function
const addNewAdmin = document.querySelector('.admin-actions');
addNewAdmin.addEventListener('submit',(e)=>{
e.preventDefault();
const adminEmail = document.querySelector('#user-ID').value;
const confirmNewAdmin = functions.httpsCallable('confirmNewAdmin');
confirmNewAdmin({email: adminEmail}).then(result =>{
console.log(result);
});
});
//for auth state changes
auth.onAuthStateChanged(user =>{
if(user) {
user.getIdTokenResult().then(IdTokenResult =>{
user.admin =IdTokenResult.claims.admin;
navbarlinks(user);
})
//get data from database
db.collection('CofeeCollection').onSnapshot(snapshot => {
setupCoffee (snapshot.docs);
});
}else{
navbarlinks();
setupCoffee([]);
}
});
// add new Coffee in db
const addcoffee =document.querySelector('#create-form');
addcoffee.addEventListener('submit',(e)=>{
e.preventDefault();
db.collection('CofeeCollection').add({
CoffeeName:addcoffee['CoffeeName'].value,
Price:addcoffee['Price'].value,
Description:addcoffee['Description'].value
}).then(() =>{
const modal = document.querySelector('#modal-create');
M.Modal.getInstance(modal).close();
addcoffee.reset();
});
});
const signupForm =document.querySelector('#signup-form');
signupForm.addEventListener('submit',(e)=>{
e.preventDefault();
// get user data
const email = signupForm['signup-email'].value;
const password = signupForm['signup-password'].value;
auth.createUserWithEmailAndPassword(email,password).then(cred =>{
console.log(cred.user);
const modal = document.querySelector('#modal-signup');
M.Modal.getInstance(modal).close();
signupForm.reset();
});
});
const logout =document.querySelector('#logout');
logout.addEventListener('click',(e) =>{
e.preventDefault();
auth.signOut();
});
const loginForm=document.querySelector('#login-form');
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = loginForm['login-email'].value;
const password =loginForm['login-password'].value;
auth.signInWithEmailAndPassword(email,password).then(cred => {
console.log(cred.user);
const modal =document.querySelector('#modal-login');
M.Modal.getInstance(modal).close();
loginForm.reset();
});
}); | 239fcb2c1f2bca3bc600fa911e9581f4b645a54b | [
"Markdown",
"JavaScript"
] | 3 | Markdown | Samad-Ullah/CoffeeCafe | c7a14c3b71d7fb47ad51f50916dadb9cffc706ba | 0058586085cb1b78987c14b5176231fac4d1fdc9 | |
refs/heads/master | <file_sep>- フォームなどの内容をPHPで処理したいときに使うやつ。(よく忘れる)
-
- HTML側でname属性を割り当てられたものを$_POST['$name_element']で指定して処理。
-
-
-
-
-
-
-
<file_sep>- DBから値を取得してきて配列で扱う
- fetchAll(PDO::FETCH_ASSOC);
- 例)
- $pdo->prepare("SELECT comment,name FROM user_comment")の結果を
- fetchを使って配列に格納
- 結果)
- Array (
- [0] => Array ( [comment] => test [name] => shy )
- [1] => Array ( [comment] => Wow! [name] => shy )
- )
- fetchの結果を$resultなどに格納した場合、$result[1][name]などでお目当の値が扱える。
<file_sep>- ALTER TABLE を実行後 general error 1364が発生
-
- 原因
- ALTER TABLE実行時に AUTO_INCREMENT を付与し忘れた。
- (それが原因でプログラムから格納するカラムにズレが生じた)
-
-
-
-
-
<file_sep>/*
PHPでの登録画面の実装
PHP内でのDBへの処理などを学んだ
セキュリティー対策が必要
クエリの発行で必要になったエスケープシーケンスがうまくいかなかったため、
$escを使ってやや強引に実装。
*/
<?php
$user = "root";
$pass = "<PASSWORD>";
$esc = '"';
$V_id = $esc .$_POST['user_id']. $esc;
$V_mail =$esc.$_POST["mail_address"]. $esc;
$V_pass = $esc.$_POST["password"]. $esc;
// MySQLへの接続
$dbh = new PDO("mysql:host=localhost;dbname=zendo_local", $user, $pass);
// SQLの処理
$dbh->query("INSERT INTO user(username,email,password) VALUES($V_id,$V_mail,$V_pass)");
<file_sep>JSでモジュールを使用した開発に必要な環境
必要なものは3種類
1 タスクランナー
gulp
gurunt
2 モジュールバンドラー
webpack
browseryify
parcel
3 トランスパイラ
babel
それぞれの役割
1 2,3の作業を自動化。
2 現状Web上ではモジュールの読み込みができない。その対策としてこれが、モジュールをweb上でも使えるようにしてくれる。
3 ES6で書かれたJSをES5に書き換えてくれる。
所感
色々必要なものが多すぎて少々手に負えない。
少しずつ触っていく。
| 9a6f535fa6c97a092e64aa875546ea3b26271ea9 | [
"Markdown",
"PHP"
] | 5 | Markdown | SuperLowTech/TIL | 704c59ca4ca3de8598cf4790f27dab569cc8e6c7 | f2c549a58f9afba9fa8735c6d6f0eab322299fa8 | |
refs/heads/main | <repo_name>afthab208/ginny-riddle-O<file_sep>/DontOpen.py
We're no strangers to love
You know the rules and so do I
A full commitment's what I'm thinking of
You wouldn't get this from any other guy
I just wanna tell you how I'm feeling
Gotta make you understand
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
We've known each other for so long
Your heart's been aching but you're too shy to say it
Inside we both know what's been going on
We know the game and we're gonna play it
And if you ask me how I'm feeling
Don't tell me you're too blind to see
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
No, I'm never gonna give you up
No, I'm never gonna let you down
No, I'll never run around and hurt you
Never, ever desert you
We've known each other for so long
Your heart's been aching but
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
No, I'm never gonna give you up
No, I'm never gonna let you down
No, I'll never run around and hurt you
I'll never, ever desert you
| 752e081da4b01211b27bffaed07b4534e3db7d43 | [
"Python"
] | 1 | Python | afthab208/ginny-riddle-O | b470f755af8cd35d043acb570bebf23326e52c72 | d2fd52cc3b94b31aa22f071e39387095d3692889 | |
refs/heads/master | <repo_name>relaxedtomato/mealstogo-create-initial-restaurant-details-modal<file_sep>/src/scenes/restaurant/index.js
import React from 'react';
import { SafeAreaView, Text } from 'react-native';
const Restaurant = () => (
<SafeAreaView>
<Text>Restaurant</Text>
</SafeAreaView>
);
export default Restaurant;
| 9126f0b9c9e36a1a4c362b529a60010bcbf299c0 | [
"JavaScript"
] | 1 | JavaScript | relaxedtomato/mealstogo-create-initial-restaurant-details-modal | 1f39a1351c70b019a6436956931d0f9488dbddfa | 5c18556270d695dc4ebd41a37b55776e28adbfd8 | |
refs/heads/master | <file_sep>#!/usr/bin/php
<?php
$ops = getopt("d:i:o:eyqvh");
$quiet = false;
$verbose = false;
$prompt = true;
$erase = false;
$output = ".";
$input = "";
$operation = "GIT";
$commands = array();
$display = array();
if(array_key_exists('h',$ops))
{
usage();
return 0;
}
if(array_key_exists('q',$ops))
$quiet = true;
if(array_key_exists('v',$ops))
$verbose = true;
if(array_key_exists('y',$ops))
$prompt = true;
if(array_key_exists('e',$ops))
$erase = true;
if(array_key_exists('d',$ops))
$output = $ops['d'];
if(array_key_exists('o',$ops))
$operation = $ops['o'];
if(array_key_exists('i',$ops))
$input = $ops['i'];
else
{
echo "Error: No input specified\n\n";
usage();
return -1;
}
$display = array();
$commands = array();
// Validate operation and do stuff
switch($operation)
{
case 'GIT':
git($quiet,$verbose,$erase,$output,$input,$display,$commands);
break;
case 'FILE':
fileop($quiet,$verbose,$erase,$output,$input,$display,$commands);
break;
case 'TAR':
die("Error: Not created yet.\n\n");
break;
default:
echo "Error: Not a valid operation.\n\n";
usage();
return -1;
break;
}
prompt($display);
run($commands);
return;
function git($quiet,$verbose,$erase,$dir,$input,&$display,&$commands)
{
$commands = array();
$display = array();
$outdir = "/tmp/phpdeploy".(time() + rand());
$display[] = "A git clone will be performed on $input.";
$display[] = "The output will be placed into $dir.";
$ops = "";
if($quiet)
{
$ops .= " -q";
$display[] = "This will be done quietly.";
}
if($verbose)
{
$ops .= " -v";
$display[] = "This will be done verbosely.";
}
$ops = trim($ops);
$commands[] = "git clone $ops $input $outdir";
if($erase)
{
$display[] = "\033[0;31m*** DANGER ***";
$display[] = "The contents of $dir will be erased.\033[0m";
$commands[] = "rm -rf $dir";
}
$ops = "";
if($quiet)
$ops .= "q";
if($verbose)
$ops .= "v";
$commands[] = "rsync -aC$ops --exclude \".git\" --exclude \".git/\" $outdir/ $dir";
$commands[] = "rm -rf $outdir";
}
function fileop($quiet,$verbose,$erase,$dir,$input,&$display,&$commands)
{
$commands = array();
$display = array();
$display[] = "A rsync will be performed from $input to $dir.";
$ops = "";
if($quiet)
{
$ops .= "q";
$display[] = "This will be done quietly.";
}
if($verbose)
{
$ops .= "v";
$display[] = "This will be done verbosely.";
}
if($erase)
{
$display[] = "\033[0;31m*** DANGER ***";
$display[] = "The contents of $dir will be erased.\033[0m";
$commands[] = "rm -rf $dir";
}
$commands[] = "rsync -aC$ops --exclude \".git\" --exclude \".git/\" $input $dir";
}
function run($commands)
{
global $verbose;
$junk = array();
$val = 0;
foreach($commands as $command)
{
if($verbose)
echo $command."\n";
passthru($command,$val);
if($val != 0)
{
echo "\n\n\033[0;31mAn error occured while running the following command:\n";
echo "\t$command\033[0m\n\n";
return -1;
}
}
echo "\033[0;32mOperations Successful\033[0m\n";
}
function prompt($array)
{
$txt = implode("\n",$array);
$val = readline($txt."\n\nDo you want to continue? [yN]: ");
if(trim(strtolower($val)) != "y")
{
exit(0);
}
else
{
return true;
}
}
function usage()
{
global $argv, $argc;
echo "
usage: ${argv[0]} [-o GIT] [-d OUTPUT_DIR] -i INPUT
This script can be used to deploy code from a directory, tar file, or
git repository into a given directory.
OPTIONS:
-d Output directory. Defaults to .
-i Input for the givem operation
Git URL, File Path, Tar location, etc.
-o Defines operation used to get files.
Valid options are GIT, FILE, and TAR
GIT is the default
-e Empty output directory before deploying *DANGEROUS*
-y Bypass prompt to confirm operation
-q Quiet
-v Verbose
-h Display this message
";
}
?>
<file_sep>#!/bin/bash
#rsync -aC --exclude ".git" --exclude ".git/" WOTRK/ WOTRK2/
TMPFOLDER=/tmp/DEPLOY$RANDOM
#git clone http://dev.webapps.brake.local/git/WOTRK.git $TMPFOLDER
#########################################
usage()
{
cat << EOF
usage: $0 [-o GIT] [-d OUTPUT_DIR] -i INPUT
This script can be used to deploy code from a directory, tar file, or
git repository into a given directory.
OPTIONS:
-d Output directory. Defaults to .
-i Input for the givem operation
Git URL, File Path, Tar location, etc.
-o Defines operation used to get files.
Valid options are GIT, FILE, and TAR
GIT is the default
-e Empty output directory before deploying *DANGEROUS*
-y Bypass prompt to confirm operation
-q Quiet
-v Verbose
-h Display this message
EOF
}
###
# Parse Arguments
###
ARGC=$#
OUTPUT='.'
INPUT=""
OPERATION="GIT"
DELETE=0
PROMPT=1
QUIET=0
VERBOSE=0
while getopts “o:i:d:eyqvh” OPTION
do
case $OPTION in
h)
usage
exit 1
;;
o)
OPERATION=$OPTARG
;;
e)
DELETE=1
;;
y)
PROMPT=0
;;
q)
QUIET=1
;;
v)
VERBOSE=1
;;
i)
INPUT=$OPTARG
;;
d)
OUTPUT=$OPTARG
;;
?)
usage
exit 1
;;
esac
done
# Build the arguments for the operation.
COMMAND=""
DISP=""
case $OPERATION in
GIT)
i=0
OPS=""
DISP="\n\nUsing git the repo at \"$INPUT\" will be cloned to $TMPFOLDER.\n"
DISP="${DISP}The files will then be moved to $OUTPUT.\n"
if [ "$QUIET" = "1" ]; then
OPS="$OPS -q"
DISP="${DISP}This will be done quietly.\n"
fi
if [ "$VERBOSE" = "1" ]; then
DISP="${DISP}This will be done verbosly.\n"
OPS="$OPS -v"
fi
COMMAND[$i]="git clone $INPUT $TMPFOLDER"
i=$i+1
if [ "$DELETE" = "1" ]; then
COMMAND[$i]="$COMMAND;rm -rf $OUTPUT"
i=$i+1
DISP="${DISP}**DANGER**\n$OUTPUT will be emptied.\n"
fi
COMMAND[$i]="$COMMAND && rsync -aC --exclude \".git\" --exclude \".git/\" $TMPFOLDER/ $OUTPUT"
i=$i+1
COMMAND[$i]="$COMMAND && rm -rf $TMPFOLDER"
i=$i+1
;;
FILE)
echo "Error: Not created yet"
exit -1
;;
TAR)
echo "Error: Not created yet"
exit -1
;;
esac
if [ "$PROMPT" -eq "1" ]; then
echo -e $DISP
echo -e "\nDo you want to do this? [y/N]"
VALUE=""
read VALUE
if [ "$VALUE" != "y" -a "$VALUE" != "Y" ]; then
exit
fi
fi
echo -e "\nCommand:\n$COMMAND"
COMMAND=("${COMMAND[@]}")
for x in ${!COMMAND[*]}; do
${COMMAND[$x]}
done
| b7c091fd3672c9f0c6468ba630507d1c595a7c74 | [
"PHP",
"Shell"
] | 2 | PHP | jbutz/PHPDeploy | d2f9b92feaa699428c7f044fd94065fa0b5cdc6c | f51dbb7ab327acd64c72c11ebefddfd5cc3b9bfd | |
refs/heads/master | <repo_name>apacherose/pr.reau<file_sep>/PropertyRegister.REAU.Test/Mocks/Extensions.cs
using PropertyRegister.REAU.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Test.Mocks
{
public static class Extensions
{
}
}
<file_sep>/PropertyRegister.REAU.Test/Mocks/ActionDispatcherMock.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PropertyRegister.REAU.Applications;
using PropertyRegister.REAU.Common;
using Rebus.Activation;
using Rebus.Bus;
using Rebus.Config;
using Rebus.Routing.TypeBased;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Test.Mocks
{
public class RebusActionDispatcherMock : IActionDispatcher
{
private readonly BuiltinHandlerActivator HandlerActivator = new BuiltinHandlerActivator();
private readonly IBus Bus;
public RebusActionDispatcherMock()
{
Bus = Configure.With(HandlerActivator)
.Transport(t => t.UseMsmq("apps_queue"))
.Routing(r => r.TypeBased().Map<long>("ApplicationAcceptance"))
.Start();
}
public Task SendAsync(object actionData)
{
//TODO check if {actionname} exists in routing mapping?
return Bus.Send(actionData);
}
public void Dispose()
{
HandlerActivator.Dispose();
}
}
public class DummyActionDispatcherMock : IActionDispatcher
{
private readonly JsonSerializer Serializer;
public DummyActionDispatcherMock()
{
Serializer = new JsonSerializer();
}
public Task SendAsync(object actionData)
{
JsonSerializer serializer = new JsonSerializer();
string path = @"c:\tmp\reau_dispacher_queue\" + $"{DateTime.Now.ToString("yyyyMMddhhmmss")}.txt";
using (StreamWriter sw = new StreamWriter(path))
{
using (JsonWriter writer = new JsonTextWriter(sw))
{
Serializer.Serialize(writer, actionData);
}
}
return Task.CompletedTask;
}
public void Dispose()
{
}
}
}
<file_sep>/PropertyRegister.REAU.Test/Mocks/DocumentServiceMock.cs
using PropertyRegister.REAU.Common;
using PropertyRegister.REAU.Common.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Test.Mocks
{
public class DocumentServiceMock : IDocumentService
{
public Task DeleteDocumentAsync(string documentIdentifier)
{
throw new NotImplementedException();
}
public Task<DocumentData> GetDocumentAsync(string documentIdentifier)
{
throw new NotImplementedException();
}
public Task<List<DocumentData>> GetDocumentsAsync(List<string> documentIdentifiers)
{
throw new NotImplementedException();
}
public Task<IEnumerable<DocumentData>> GetDocumentsAsync(List<string> documentIdentifiers, bool loadContent = false)
{
throw new NotImplementedException();
}
public Task<DocumentData> SaveDocumentAsync(DocumentCreateRequest request)
{
return Task.FromResult(new DocumentData() { DocID = 100 });
}
Task<DocumentCreateResult> IDocumentService.SaveDocumentAsync(DocumentCreateRequest request)
{
throw new NotImplementedException();
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/Persistence/ServiceDocumentRepository.cs
using PropertyRegister.REAU.Applications.Models;
using CNSys.Data;
namespace PropertyRegister.REAU.Applications.Persistence
{
public interface IServiceDocumentRepository : IRepository<ServiceDocument, long?, object>
{
}
public class ServiceDocumentRepository : RepositoryBase<ServiceDocument, long?, object, ApplicationProcessDataContext>, IServiceDocumentRepository
{
public ServiceDocumentRepository() : base(false)
{
}
protected override void CreateInternal(ApplicationProcessDataContext context, ServiceDocument item)
{
base.CreateInternal(context, item);
}
protected override void UpdateInternal(ApplicationProcessDataContext context, ServiceDocument item)
{
base.UpdateInternal(context, item);
}
protected override void DeleteInternal(ApplicationProcessDataContext context, ServiceDocument item)
{
base.DeleteInternal(context, item);
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/Models/ServiceInstanceAction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications.Models
{
public enum ServicеActionTypes
{
/// <summary>
/// пъровначално подаване на заявление
/// </summary>
ApplicationAcceptance = 1,
/// <summary>
/// наредено задължение
/// </summary>
RequestedPayment = 2,
WaitingRegistrationInPR = 3,
/// <summary>
/// Регистриране в ИС на ИР
/// </summary>
ApplicationRegistrationInPR = 4,
/// <summary>
/// изпълнение на ел.справка с отдалечен достъп
/// </summary>
ExecuteRemoteReportInPR = 5,
PaymentChange = 6
}
/// <summary>
/// Действия по услугите
/// </summary>
public class ServiceInstanceAction
{
/// <summary>
/// PK
/// </summary>
public long? ServiceActionID { get; set; }
/// <summary>
/// Идентификатор на операция в рамките на която е действието
/// </summary>
public Guid OperationID { get; set; }
/// <summary>
/// Идентификатор на операция в рамките на която е действието
/// </summary>
public long? ServiceOperationID { get; set; }
/// <summary>
/// Връзка към услугата.
/// </summary>
public long ServiceInstanceID { get; set; }
/// <summary>
/// Връзка към заявлението
/// </summary>
public long ApplicationID { get; set; }
/// <summary>
/// Вид на действието
/// </summary>
public ServicеActionTypes? ActionTypeID { get; set; }
/// <summary>
/// Статус на заявлението, до който води действието.
/// </summary>
public ApplicationStatuses ApplicationStatus { get; set; }
/// <summary>
/// Връзка към документ-резултат от действието (може и да липсва).
/// </summary>
public long? ServiceDocumentID { get; set; }
/// <summary>
/// пояснителен текст съпътсващ действието.
/// </summary>
public string Description { get; set; }
}
}
<file_sep>/PropertyRegister.REAU/Persistence/REAUDbContext.cs
using CNSys.Data;
using CNSys.Security;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Configuration;
using System.Threading;
namespace PropertyRegister.REAU.Persistence
{
public class REAUDbContext : DbContext
{
#region Constructors
public REAUDbContext(ConnectionStringSettings connectionString, DbContextOptions options)
: base(connectionString, options)
{
}
#endregion
#region Overriden Methods
protected override void InitConnection()
{
var dataSourceUser = Thread.CurrentPrincipal as IDataSourceUser;
if (dataSourceUser != null)
{
int user = int.Parse(dataSourceUser.ClientID);
const string currentUserKey = "currentUser";
object currentUser = null;
bool hasContextItemsUser = this.ConnectionContextItems.TryGetValue(currentUserKey, out currentUser);
if (!hasContextItemsUser ||
int.Parse(currentUser.ToString()) != user)
{
(Connection as OracleConnection).ClientId = user.ToString();
if (hasContextItemsUser)
ConnectionContextItems[currentUserKey] = user;
else
ConnectionContextItems.Add(currentUserKey, user);
}
}
}
#endregion
#region Static Interface
public static new REAUDbContext CreateDefaultSerializationContext()
{
return CreateSerializationContext(ConnectionStrings.DefaultConnectionString, true);
}
public static new REAUDbContext CreateSerializationContext(ConnectionStringSettings connectionStringSettings, bool useTransaction)
{
if (useTransaction)
return CreateContext(connectionStringSettings, DbContextOptions.UseTransaction);
else
return CreateContext(connectionStringSettings, DbContextOptions.None);
}
public static new REAUDbContext CreateContext(ConnectionStringSettings connectionStringSettings, DbContextOptions options)
{
if ((options & DbContextOptions.SuppressConnection) == DbContextOptions.SuppressConnection)
throw new NotImplementedException("SuppressConnection option is not yet implemented.");
return new REAUDbContext(connectionStringSettings, options);
}
#endregion
}
}
<file_sep>/PropertyRegister.REAU/Common/Persistence/ServiceOperationRepository.cs
using PropertyRegister.REAU.Common.Models;
using CNSys.Data;
using System;
using System.Collections.Generic;
namespace PropertyRegister.REAU.Common.Persistence
{
public class ServiceOperationSearchCriteria
{
public long? ServiceOperationID { get; set; }
public Guid? OperationID { get; set; }
public ServiceOperationTypes? ServiceOperationType { get; set; }
}
public interface IServiceOperationRepository : IRepository<ServiceOperation, long?, ServiceOperationSearchCriteria>
{
}
public class ServiceOperationRepository : RepositoryBase<ServiceOperation, long?, ServiceOperationSearchCriteria, CommonDataContext>, IServiceOperationRepository
{
public ServiceOperationRepository()
: base(false)
{
}
protected override void CreateInternal(CommonDataContext context, ServiceOperation item)
{
context.ServiceOperationCreate(item.OperationID.ToString(), (int)item.ServiceOperationType,
out long serviceOperationID, out bool isCompleted, out string result);
item.ServiceOperationID = serviceOperationID;
item.IsCompleted = isCompleted;
item.Result = result;
}
protected override void UpdateInternal(CommonDataContext context, ServiceOperation item) =>
context.ServiceOperationUpdate(item.ServiceOperationID.Value, item.OperationID.ToString(), item.IsCompleted, item.Result.ToString());
protected override IEnumerable<ServiceOperation> SearchInternal(CommonDataContext context, ServiceOperationSearchCriteria searchCriteria)
{
IEnumerable<ServiceOperation> res;
using (var data = context.ServiceOperationSearch(searchCriteria.ServiceOperationID, searchCriteria.OperationID?.ToString(), (int?)searchCriteria.ServiceOperationType))
{
res = data.ReadToList<ServiceOperation>();
}
return res;
}
}
}
<file_sep>/PropertyRegister.REAU.Test/Mocks/TestPrincipal.cs
using CNSys.Security;
using PropertyRegister.REAU.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Test.Mocks
{
public class TestPrincipal : IPrincipal, IDataSourceUser
{
public TestPrincipal(string clientID) => ClientID = clientID;
public IIdentity Identity => throw new NotImplementedException();
public string ClientID { get; }
public string ProxyUserID => throw new NotImplementedException();
public bool IsInRole(string role)
{
throw new NotImplementedException();
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/MessageHandlers/ApplicationAcceptedResultHandler.cs
using CNSys.Security;
using PropertyRegister.REAU.Applications.Results;
using Rebus.Handlers;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications.MessageHandlers
{
public class ApplicationAcceptedResultHandler : IHandleMessages<ApplicationAcceptedResult>
{
private readonly IApplicationProcessingService ProcessingService;
public ApplicationAcceptedResultHandler(IApplicationProcessingService processingService)
{
ProcessingService = processingService;
}
public async Task Handle(ApplicationAcceptedResult message)
{
using (var mti = new ManagedThreadImpersonation(new GenericDataSourceUser("1", Thread.CurrentPrincipal)))
{
await ProcessingService.ProcessApplicationAsync(message.ApplicationID);
}
Console.WriteLine($"Handled message of {nameof(message)} with value {message.ApplicationNumber}.");
}
}
public class ApplicationProcessedResultHandler : IHandleMessages<ApplicationProcessedResult>
{
private readonly IApplicationProcessingService ProcessingService;
public ApplicationProcessedResultHandler(IApplicationProcessingService processingService)
{
ProcessingService = processingService;
}
public Task Handle(ApplicationProcessedResult message)
{
throw new NotImplementedException("in progress");
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/Integration/Objects.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace PropertyRegister.REAU.Applications.Integration
{
//[XmlType(AnonymousType = true, Namespace = "reau.pr.bg")]
//[XmlRoot("Application", Namespace = "reau.pr.bg", IsNullable = false)]
//public class PortalApplication
//{
// public Header Header { get; set; }
// [XmlArrayItem("AttachedDocument")]
// public AttachedDocument[] AttachedDocuments { get; set; }
//}
//public class Header
//{
// public ServiceInfo ServiceInfo { get; set; }
// public string OfficeID { get; set; }
// public Applicant Applicant { get; set; }
//}
//public class ServiceInfo
//{
// public string Code { get; set; }
// public decimal? Obligation { get; set; }
//}
//public class Applicant
//{
// public string CIN { get; set; }
//}
//public class AttachedDocument
//{
// public Guid BackOfficeGUID { get; set; }
//}
}
<file_sep>/ConsoleApp0/Program.cs
using PropertyRegister.REAU.Applications;
using Rebus.Activation;
using Rebus.Config;
using Rebus.Routing.TypeBased;
using System;
using System.Threading.Tasks;
namespace ConsoleApp0
{
class Program
{
static void Main(string[] args)
{
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
string connString = "Data Source=pr_reau; User ID=pr_reau_dev; Password=<PASSWORD>;";
using (var activator = new BuiltinHandlerActivator())
{
Configure.With(activator)
//.Transport(t => t.UseMsmqAsOneWayClient())
.Transport(t => t.UseOracleAsOneWayClient(connString, "mbus_messages"))
.Routing(r => r.TypeBased().Map<ApplicationReceivedMessage>("consumer.input"))
.Start();
while (true)
{
Console.WriteLine(@"a) Publish string");
var keyChar = char.ToLower(Console.ReadKey(true).KeyChar);
var bus = activator.Bus.Advanced.SyncBus;
if (keyChar == 'q')
goto consideredHarmful;
else
{
bus.Send(new ApplicationReceivedMessage(keyChar));
}
}
consideredHarmful:;
Console.WriteLine("Quitting!");
}
}
}
}
<file_sep>/PropertyRegister.REAU/Common/DeferredInitializedStream.cs
using CNSys.Data;
using PropertyRegister.REAU.Persistence;
using System;
using System.IO;
namespace PropertyRegister.REAU.Common
{
public class DeferredDbStream : Stream
{
private bool _isInnerStreamInitialized = false;
private readonly Func<Tuple<DbContext, Stream>> _streamFactory;
private Stream _innerStream;
private DbContext _dbContext;
public DeferredDbStream(Func<Tuple<DbContext, Stream>> streamFactory)
{
_streamFactory = streamFactory ?? throw new ArgumentNullException(nameof(streamFactory));
}
#region Overriden Methods
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
EnsureInnerStreamInitialized();
return _innerStream.BeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
EnsureInnerStreamInitialized();
return _innerStream.EndRead(asyncResult);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
EnsureInnerStreamInitialized();
return _innerStream.BeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
EnsureInnerStreamInitialized();
_innerStream.EndWrite(asyncResult);
}
public override bool CanRead
{
get
{
EnsureInnerStreamInitialized();
return _innerStream.CanRead;
}
}
public override bool CanSeek
{
get
{
EnsureInnerStreamInitialized();
return _innerStream.CanSeek;
}
}
public override bool CanTimeout
{
get
{
EnsureInnerStreamInitialized();
return _innerStream.CanTimeout;
}
}
public override bool CanWrite
{
get
{
EnsureInnerStreamInitialized();
return _innerStream.CanWrite;
}
}
public override void Close()
{
base.Close();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_dbContext != null)
{
_dbContext.Complete();
_dbContext.Dispose();
_dbContext = null;
}
if (_innerStream != null)
{
_innerStream.Dispose();
_innerStream = null;
}
}
public override long Length
{
get
{
EnsureInnerStreamInitialized();
return _innerStream.Length;
}
}
public override long Position
{
get
{
EnsureInnerStreamInitialized();
return _innerStream.Position;
}
set
{
EnsureInnerStreamInitialized();
_innerStream.Position = value;
}
}
public override int ReadTimeout
{
get
{
EnsureInnerStreamInitialized();
return _innerStream.ReadTimeout;
}
set
{
EnsureInnerStreamInitialized();
_innerStream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
EnsureInnerStreamInitialized();
return _innerStream.WriteTimeout;
}
set
{
EnsureInnerStreamInitialized();
_innerStream.WriteTimeout = value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
EnsureInnerStreamInitialized();
return _innerStream.Read(buffer, offset, count);
}
public override int ReadByte()
{
EnsureInnerStreamInitialized();
return _innerStream.ReadByte();
}
public override void Write(byte[] buffer, int offset, int count)
{
EnsureInnerStreamInitialized();
_innerStream.Write(buffer, offset, count);
}
public override void WriteByte(byte value)
{
EnsureInnerStreamInitialized();
_innerStream.WriteByte(value);
}
public override void SetLength(long value)
{
EnsureInnerStreamInitialized();
_innerStream.SetLength(value);
}
public override long Seek(long offset, SeekOrigin origin)
{
EnsureInnerStreamInitialized();
return _innerStream.Seek(offset, origin);
}
public override void Flush()
{
EnsureInnerStreamInitialized();
_innerStream.Flush();
}
#endregion
#region Protected Interface
protected virtual void InitializeInnerStream()
{
_isInnerStreamInitialized = true;
(_dbContext, _innerStream) = _streamFactory();
}
protected void EnsureInnerStreamInitialized()
{
if (!_isInnerStreamInitialized)
{
InitializeInnerStream();
}
}
#endregion
}
}
<file_sep>/PropertyRegister.REAU/Applications/Persistence/ApplicationDocumentRepository.cs
using PropertyRegister.REAU.Applications.Models;
using CNSys.Data;
namespace PropertyRegister.REAU.Applications.Persistence
{
public interface IApplicationDocumentRepository : IRepository<ApplicationDocument, long?, object>
{
}
public class ApplicationDocumentRepository : RepositoryBase<ApplicationDocument, long?, object, ApplicationProcessDataContext>, IApplicationDocumentRepository
{
public ApplicationDocumentRepository() : base(false)
{
}
protected override void CreateInternal(ApplicationProcessDataContext context, ApplicationDocument item)
{
context.ApplicationDocumentCreate(item.ApplicationID, item.DocumentType.Value, item.DocumentID, out long appDocumentID);
item.ApplicationDocumentID = appDocumentID;
}
protected override void DeleteInternal(ApplicationProcessDataContext context, ApplicationDocument item)
{
base.DeleteInternal(context, item);
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/Results/ApplicationAcceptedResult.cs
using PropertyRegister.REAU.Applications.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications.Results
{
public class ApplicationAcceptedResult
{
public string ApplicationNumber { get; set; }
public ApplicationStatuses? ApplicationStatus { get; set; }
public DateTime RegistrationTime { get; set; }
public ICollection<string> Errors { get; set; }
public long ApplicationID { get; set; }
}
}
<file_sep>/PropertyRegister.REAU/Persistence/DataContextHelper.cs
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace PropertyRegister.REAU.Persistence
{
public class DataContextHelper
{
public static CustomPropertyTypeMap ColumnMap<T>(Dictionary<string, string> columnMappings = null)
{
return new CustomPropertyTypeMap(typeof(T),
(type, columnName) =>
{
return type.GetProperties().FirstOrDefault(prop => string.Compare(GetMappedColumnName(prop, columnMappings), columnName, true) == 0);
});
}
private static string GetMappedColumnName(MemberInfo member, Dictionary<string, string> columnMappings)
{
if (member == null)
return null;
var attrib = (DapperColumnAttribute)Attribute.GetCustomAttribute(member, typeof(DapperColumnAttribute), false);
if (attrib != null)
return attrib.Name;
string mappedPropName = null;
if (columnMappings?.Any() == true
&& columnMappings.TryGetValue(member.Name, out mappedPropName))
return mappedPropName;
return null;
}
}
}
<file_sep>/PropertyRegister.REAU.Test/Mocks/Sets.cs
using PropertyRegister.REAU.Applications.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Test.Mocks
{
public class DbDataSets
{
public IEnumerable<Applications.Models.Application> Applications = new List<Applications.Models.Application>()
{
new Applications.Models.Application()
{
ApplicationID = 100,
ServiceInstanceID = 100,
ApplicationIdentifier = "20181109/777",
Status = REAU.Applications.Models.ApplicationStatuses.Registered,
ApplicationTypeID = 1,
},
new Applications.Models.Application()
{
ApplicationID = 101,
ServiceInstanceID = 101,
ApplicationIdentifier = "20181109/778",
Status = REAU.Applications.Models.ApplicationStatuses.WaitingPayment,
ApplicationTypeID = 1,
},
};
public IEnumerable<ServiceInstanceAction> ServiceActions = new List<ServiceInstanceAction>()
{
new ServiceInstanceAction()
{
OperationID = Guid.NewGuid(),
ApplicationID = 1000,
ServiceInstanceID = 1000,
ActionTypeID = ServicеActionTypes.ApplicationAcceptance,
}
};
}
}
<file_sep>/PropertyRegister.REAU/Applications/ApplicationInfoResolver.cs
using System.Collections.Generic;
using System.IO;
using System.Xml;
namespace PropertyRegister.REAU.Applications
{
public interface IApplicationInfoResolver
{
ApplicationXmlInfo GetApplicationInfoFromXml(Stream xml);
}
public class ApplicationXmlInfo
{
public string XmlNamespace { get; set; }
public string MainApplicationNumber { get; set; }
public decimal? PaymentObligationAmount { get; set; }
public IEnumerable<string> AttachedDocumentIDs { get; set; }
}
public class ApplicationInfoResolver : IApplicationInfoResolver
{
private const string _docNamespacePrefix = "__docns";
public ApplicationXmlInfo GetApplicationInfoFromXml(Stream xml)
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(xml);
XmlNamespaceManager nsmgr = BuildDocumentNamespaceManager(doc.NameTable, doc.DocumentElement.NamespaceURI);
string mainAppNumber = doc.SelectSingleNode($"//{_docNamespacePrefix}:MainApplicationNumber", nsmgr)?.InnerText;
var attDocsNodes = doc.SelectNodes("//att0:AttachedDocument/att1:DocumentUniqueId", nsmgr);
List<string> docIdentifiers = new List<string>();
foreach (XmlNode attDoc in attDocsNodes)
{
docIdentifiers.Add(attDoc.InnerText);
}
return new ApplicationXmlInfo()
{
XmlNamespace = doc.DocumentElement.NamespaceURI,
MainApplicationNumber = mainAppNumber,
AttachedDocumentIDs = docIdentifiers
};
}
private XmlNamespaceManager BuildDocumentNamespaceManager(XmlNameTable xmlNameTable, string documentNamespace)
{
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlNameTable);
nsmgr.AddNamespace(_docNamespacePrefix, documentNamespace);
nsmgr.AddNamespace("att0", "AttachedDocuments");
nsmgr.AddNamespace("att1", "AttachedDocument");
return nsmgr;
}
}
}
<file_sep>/PropertyRegister.REAU.Web.Api/Controllers/DocumentsController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PropertyRegister.REAU.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Web.Api.Controllers
{
public class DocumentsController : BaseApiController
{
private readonly IDocumentService DocumentService;
public DocumentsController(IDocumentService documentService)
{
DocumentService = documentService;
}
[HttpPost]
public async Task<IActionResult> CreateDocument(IFormFile file)
{
var documentResult = await DocumentService.SaveDocumentAsync(new DocumentCreateRequest()
{
ContentType = file.ContentType,
Filename = file.FileName,
Content = file.OpenReadStream()
});
return Ok(new {
docIdentifier = documentResult.DocumentIdentifier
});
}
[Route("{documentIdentifier}")]
[HttpDelete]
public async Task<IActionResult> DeleteDocument(string documentIdentifier)
{
await DocumentService.DeleteDocumentAsync(documentIdentifier);
return Ok();
}
[Route("{documentIdentifier}")]
[HttpGet]
public async Task<IActionResult> GetDocument(string documentIdentifier)
{
var docs = await DocumentService.GetDocumentsAsync(new List<string>() { documentIdentifier }, true);
var doc = docs.SingleOrDefault();
if (doc != null)
{
return File(fileStream: doc.Content, contentType: doc.ContentType, fileDownloadName: doc.Filename);
}
else
{
return NotFound();
}
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/Models/ServicePayment.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications.Models
{
/// <summary>
/// статуси на наредено плащане в Модул плащания
/// </summary>
public enum PaymentStatuses
{
/// Наредено плащане
Ordered = 1,
/// Неуспешно обработено
Error = 2,
// Отказано
Cancelled = 3
}
/// <summary>
/// наредено плащане в Модул плащания от РЕАУ по заявление по услуга
/// ОЩЕ НЕ Е УТОЧНЕН ТОЗИ МОДЕЛ!!!
/// </summary>
public class ServicePayment
{
public long? PaymentRequestID { get; set; }
public long? ServiceInstanceID { get; set; }
public string PaymentIdentifier { get; set; } // PaymentNumber?
public PaymentStatuses? Status { get; set; } // ?
public decimal ObligationAmount { get; set; }
public decimal ServiceFee { get; set; }
public DateTime? PaymentDeadline { get; set; }
public string ErrorDescription { get; set; }
}
}
<file_sep>/PropertyRegister.REAU/Applications/ApplicationAcceptanceService.cs
using PropertyRegister.REAU.Applications.Models;
using PropertyRegister.REAU.Applications.Persistence;
using PropertyRegister.REAU.Applications.Results;
using PropertyRegister.REAU.Common;
using PropertyRegister.REAU.Nomenclatures;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications
{
public interface IApplicationAcceptanceService
{
Task<ApplicationAcceptedResult> AcceptApplicationAsync(string portalOperationID, Stream xml);
}
public class ApplicationAcceptanceService : IApplicationAcceptanceService
{
private readonly INomenclaturesProvider NomenclaturesProvider;
private readonly IDocumentService DocumentService;
private readonly IIdempotentOperationExecutor IdempotentOperationExecutor;
private readonly IActionDispatcher ActionDispatcher;
private readonly IApplicationInfoResolver ApplicationInfoResolver;
private readonly IApplicationRepository ApplicationRepository;
private readonly IApplicationDocumentRepository ApplicationDocumentRepository;
private readonly IServiceActionRepository ServiceActionRepository;
private readonly IServiceInstanceRepository ServiceInstanceRepository;
public ApplicationAcceptanceService(
IApplicationRepository applicationRepository,
IServiceInstanceRepository serviceInstanceRepository,
IApplicationDocumentRepository applicationDocumentRepository,
IServiceActionRepository serviceActionRepository,
IDocumentService documentService,
INomenclaturesProvider nomenclaturesProvider,
IIdempotentOperationExecutor idempotentOperationExecutor,
IActionDispatcher actionDispatcher,
IApplicationInfoResolver applicationInfoResolver)
{
ApplicationRepository = applicationRepository;
ServiceInstanceRepository = serviceInstanceRepository;
ApplicationDocumentRepository = applicationDocumentRepository;
ServiceActionRepository = serviceActionRepository;
DocumentService = documentService;
NomenclaturesProvider = nomenclaturesProvider;
IdempotentOperationExecutor = idempotentOperationExecutor;
ActionDispatcher = actionDispatcher;
ApplicationInfoResolver = applicationInfoResolver;
}
public async Task<ApplicationAcceptedResult> AcceptApplicationAsync(string portalOperationID, Stream xml)
{
var operationResult = await IdempotentOperationExecutor.ExecuteAsync(portalOperationID, Common.Models.ServiceOperationTypes.AcceptServiceApplication,
async (oid) =>
{
var application = await InitialSaveApplication(xml);
var action = new ServiceAction()
{
OperationID = oid,
ServiceInstanceID = application.ServiceInstanceID,
ApplicationID = application.ApplicationID.Value,
ApplicationStatus = application.Status.Value,
ActionTypeID = ServicеActionTypes.ApplicationAcceptance
};
ServiceActionRepository.Create(action);
var result = new Results.ApplicationAcceptedResult()
{
ApplicationID = application.ApplicationID.Value,
ApplicationNumber = application.ApplicationIdentifier,
ApplicationStatus = application.Status,
RegistrationTime = application.RegistrationTime
};
return result;
},
async (r) =>
{
await ActionDispatcher.SendAsync(r);
});
return operationResult;
}
private async Task<Application> InitialSaveApplication(Stream xml)
{
var appInfo = ApplicationInfoResolver.GetApplicationInfoFromXml(xml);
var serviceType = NomenclaturesProvider.GetApplicationServiceTypes().SingleOrDefault(t => t.XmlNamespace == appInfo.XmlNamespace);
if (serviceType == null)
throw new InvalidOperationException("Unknown application type namespace from xml!");
long? serviceInstanceID = null;
long? mainApplicationID = null;
if (string.IsNullOrEmpty(appInfo.MainApplicationNumber))
{
var serviceInstance = new ServiceInstance()
{
OfficeID = 1,
ApplicantCIN = "100"
};
ServiceInstanceRepository.Create(serviceInstance);
serviceInstanceID = serviceInstance.ServiceInstanceID;
}
else
{
var mainApp = ApplicationRepository.Search(new ApplicationSearchCriteria() { ApplicationIdentifier = appInfo.MainApplicationNumber }).SingleOrDefault();
if (mainApp == null)
throw new InvalidOperationException("Cannot find initial main application!");
serviceInstanceID = mainApp.ServiceInstanceID;
mainApplicationID = mainApp.ApplicationID;
}
var application = new Models.Application()
{
ServiceInstanceID = serviceInstanceID.Value,
ApplicationTypeID = serviceType.ApplicationTypeID,
MainApplicationID = mainApplicationID,
RegistrationTime = DateTime.UtcNow,
IsReport = serviceType.IsReport,
Status = ApplicationStatuses.Accepted
};
ApplicationRepository.Create(application);
await SaveApplicationDocumentsAsync(application.ApplicationID.Value, appInfo, xml);
return application;
}
private async Task SaveApplicationDocumentsAsync(long applicationID, ApplicationXmlInfo applInfo, Stream xml)
{
var packageDocumentData = await DocumentService.SaveDocumentAsync(new DocumentCreateRequest()
{
Filename = "ApplicationXml",
ContentType = "application/xml",
Content = xml
});
var packageDocument = new ApplicationDocument()
{
ApplicationID = applicationID,
DocumentType = 1, // main package
DocumentID = packageDocumentData.DocumentDataID
};
List<ApplicationDocument> applicationDocuments = new List<ApplicationDocument>();
applicationDocuments.Add(packageDocument);
if (applInfo.AttachedDocumentIDs != null && applInfo.AttachedDocumentIDs.Any())
{
var attachedDocs = await DocumentService.GetDocumentsAsync(applInfo.AttachedDocumentIDs.ToList());
applicationDocuments.AddRange(attachedDocs.Select(d => new ApplicationDocument()
{
ApplicationID = applicationID,
DocumentID = d.DocID.Value,
DocumentType = 2 // attachment
}));
}
foreach (var applDoc in applicationDocuments)
{
ApplicationDocumentRepository.Create(applDoc);
}
}
}
}
<file_sep>/PropertyRegister.REAU/Persistence/BaseDataContext.cs
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Persistence
{
public class BaseDataContext : IDisposable
{
public BaseDataContext(DbConnection dbConnection)
{
DbConnection = dbConnection;
}
public DbConnection DbConnection
{
get;
protected set;
}
public void Dispose()
{
}
}
}
<file_sep>/PropertyRegister.REAU.Web.Api/Controllers/BaseApiController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Linq;
namespace PropertyRegister.REAU.Web.Api.Controllers
{
[Route("api/[controller]")]
public class BaseApiController : Controller
{
protected string RequestOperationID =>
HttpContext.Request.Headers["Operation-Id"].SingleOrDefault();
}
public class RequiredOperationHeaderAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var operationHeader = context.HttpContext.Request.Headers["Operation-Id"].SingleOrDefault();
if (string.IsNullOrEmpty(operationHeader))
{
context.Result = new BadRequestResult();
}
}
}
}
<file_sep>/PropertyRegister.REAU/Payments/PaymentManager.cs
using PropertyRegister.REAU.Applications.Models;
using PropertyRegister.REAU.Domain;
using PropertyRegister.REAU.Integration;
using PropertyRegister.REAU.Nomenclatures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Payments
{
public interface IPaymentManager
{
Task<ServicePayment> RequestApplicationPaymentAsync(Application application, decimal? filedAmount);
}
public class PaymentManager : IPaymentManager
{
private readonly IPaymentIntegrationClient PaymentIntegrationClient;
private readonly INomenclaturesProvider NomenclaturesProvider;
public PaymentManager(IPaymentIntegrationClient paymentIntegrationClient, INomenclaturesProvider nomenclaturesProvider)
{
PaymentIntegrationClient = paymentIntegrationClient;
NomenclaturesProvider = nomenclaturesProvider;
}
public async Task<ServicePayment> RequestApplicationPaymentAsync(Application application, decimal? filedAmount)
{
decimal? serviceFee, obligationAmount;
var serviceType = NomenclaturesProvider.GetApplicationServiceTypes().Single(t => t.ApplicationTypeID == application.ApplicationTypeID);
if (serviceType.IsFree)
{
serviceFee = obligationAmount = 0m;
}
else
{
if (serviceType.PaymentAmount.HasValue)
{
serviceFee = obligationAmount = serviceType.PaymentAmount.Value;
}
else
{
serviceFee = 0m;
obligationAmount = filedAmount.Value;
}
}
var paymentResponse = serviceType.PaymentAfterRegistration ?
await PaymentIntegrationClient.InitiateServiceApplicationAsync(new ServiceRequest { ServiceFee = serviceFee.Value }) :
await PaymentIntegrationClient.InitiatePaymentAsync(new PaymentRequest()
{
PaymentFor = application.ApplicationIdentifier,
ServiceFee = serviceFee.Value,
ObligationAmount = obligationAmount.Value
});
var applPayment = new ServicePayment()
{
ServiceInstanceID = application.ApplicationID,
ServiceFee = serviceFee.Value,
ObligationAmount = obligationAmount.Value
};
if (paymentResponse.Successfull)
{
applPayment.Status = PaymentStatuses.Ordered;
applPayment.PaymentIdentifier = paymentResponse.PaymentIdentifier;
if (serviceType.PaymentDeadline.HasValue)
applPayment.PaymentDeadline = DateTime.Now.Add(serviceType.PaymentDeadline.Value); // как се определя?
}
else
{
applPayment.Status = PaymentStatuses.Error;
applPayment.ErrorDescription = paymentResponse.Errors;
}
return applPayment;
}
}
}
<file_sep>/PropertyRegister.REAU.Web.Api/Program.cs
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Serilog;
using Serilog.Core;
using Serilog.Events;
namespace PropertyRegister.REAU.Web.Api
{
public class Program
{
public static void Main(string[] args)
{
Log.Logger = CreateLogger();
CreateWebHostBuilder(args)
.Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog();
public static Logger CreateLogger() =>
new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.With<UserIdentityEnricher>()
.WriteTo.File(
path: @"C:\tmp\EPZEU\PR.REAU.Web.Api\log.txt",
outputTemplate: "---------------------------------------------------------------------- {NewLine} {Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{UserIdentity}] [{Level:u3}] {Message:lj}{NewLine}{Exception}",
rollingInterval: RollingInterval.Hour)
.CreateLogger();
}
public class UserIdentityEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
=> logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserIdentity", @"cnsys\vachev"));
}
}
<file_sep>/PropertyRegister.REAU/Common/Persistence/DocumentDataRepository.cs
using CNSys.Data;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
using PropertyRegister.REAU.Common.Models;
using PropertyRegister.REAU.Persistence;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
namespace PropertyRegister.REAU.Common.Persistence
{
public class DocumentDataSearchCriteria
{
public List<long> DocumentDataIDs { get; set; }
public List<string> Identifiers { get; set; }
}
public interface IDocumentDataRepository : IRepository<DocumentData, Guid, DocumentDataSearchCriteria>
{
Stream ReadContent(string documentIdentifier);
}
public class DocumentDataRepository : RepositoryBase<DocumentData, Guid, DocumentDataSearchCriteria, CommonDataContext>, IDocumentDataRepository
{
public DocumentDataRepository()
: base(false)
{
}
protected override void CreateInternal(CommonDataContext context, DocumentData item)
{
item.Identifier = item.Identifier ?? Guid.NewGuid().ToString();
using (var blobContent = new OracleBlob(context.DbConnection as OracleConnection))
{
item.Content.CopyTo(blobContent);
context.DocumentDataCreate(item.Identifier, item.ContentType, item.Filename, item.IsTemporal, blobContent, out long documentId);
item.DocID = documentId;
}
}
protected override void UpdateInternal(CommonDataContext context, DocumentData item) =>
context.DocumentDataUpdate(item.Identifier, item.ContentType, item.Filename, item.IsTemporal);
protected override void DeleteInternal(CommonDataContext context, Guid key) =>
context.DocumentDataDelete(key);
protected override IEnumerable<DocumentData> SearchInternal(CommonDataContext context, DocumentDataSearchCriteria searchCriteria)
{
IEnumerable<DocumentData> res;
using (var data = context.DocumentDataSearch(
ToStringCollection(searchCriteria.DocumentDataIDs),
ToStringCollection(searchCriteria.Identifiers), 1, 20, out int? count))
{
res = data.ReadToList<DocumentData>();
}
return res;
}
public Stream ReadContent(string documentIdentifier)
{
return new DeferredDbStream(() => {
var dbContext = CreateDbContext();
var dataCtx = CreateDataContext(dbContext);
return new Tuple<DbContext, Stream>(dbContext, new WrappedBinaryStream(dataCtx.DocumentContentGet(documentIdentifier)));
});
}
public static string ToStringCollection(IEnumerable items, char separator = ',')
{
if (items == null)
return null;
StringBuilder res = new StringBuilder();
foreach (var item in items)
{
res.AppendFormat("{0}{1}", item, separator);
}
return
res.Length > 0 ?
res.ToString().Trim(separator) : null;
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/ApplicationReceivedMessage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications
{
/// <summary>
/// Dummy - тест за rebus!
/// </summary>
public class ApplicationReceivedMessage
{
public ApplicationReceivedMessage(long id)
{
ID = id;
}
public long ID { get; private set; }
}
}
<file_sep>/PropertyRegister.REAU/Persistence/DbContextHelper.cs
using Dapper;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Persistence
{
public static class DbContextHelper
{
public static void SPExecute(this IDbConnection connection, string procName, SqlMapper.IDynamicParameters parameters = null)
{
connection.Execute(procName, parameters, commandType: CommandType.StoredProcedure);
}
public static object SPExecuteScalar(this IDbConnection connection, string procName, SqlMapper.IDynamicParameters parameters = null)
{
return connection.ExecuteScalar(string.Format("\"{0}\"", procName), parameters, commandType: CommandType.StoredProcedure);
}
public static CnsysGridReader SPExecuteReader(this DbConnection connection, string procName, SqlMapper.IDynamicParameters parameters)
{
var reader = connection.ExecuteReader(procName, parameters, commandType: CommandType.StoredProcedure);
return new CnsysGridReader(reader);
}
public static IDataReader SPExecuteReader(this DbConnection connection, string procName, SqlMapper.IDynamicParameters parameters = null, CommandBehavior behavior = CommandBehavior.Default)
{
CommandDefinition commandDefinition = new CommandDefinition(procName, parameters, null, null, CommandType.StoredProcedure, CommandFlags.None);
var reader = connection.ExecuteReader(commandDefinition, behavior);
return reader;
}
public static async Task<T> TransactionalOperationAsync<T>(Func<Task<T>> func)
{
T res = default(T);
try
{
using (var dbContext = REAUDbContext.CreateDefaultSerializationContext())
{
res = await func();
dbContext.Complete();
}
}
catch (Exception ex)
{
// log ex
throw;
}
return res;
}
public static async Task TransactionalOperationAsync(Func<Task> func)
{
try
{
using (var dbContext = REAUDbContext.CreateDefaultSerializationContext())
{
await func();
dbContext.Complete();
}
}
catch (Exception ex)
{
// log ex
throw;
}
}
}
public class CnsysGridReader : IDisposable
{
private IDataReader _reader = null;
private bool _isFirstCall = true;
public CnsysGridReader(IDataReader reader)
{
_reader = reader;
}
public List<T> ReadToList<T>()
{
return Read<T>().ToList();
}
public IEnumerable<T> Read<T>()
{
if (!_isFirstCall)
{
_reader.NextResult();
}
else
{
_isFirstCall = false;
}
return _reader.Parse<T>();
}
public void Dispose()
{
if (_reader != null)
{
if (!_reader.IsClosed)
_reader.Close();
_reader.Dispose();
}
_reader = null;
}
}
public class OracleDynamicParameters : SqlMapper.IDynamicParameters
{
private readonly DynamicParameters dynamicParameters = new DynamicParameters();
private readonly List<OracleParameter> oracleParameters = new List<OracleParameter>();
public void Add(string name, OracleDbType oracleDbType, object value = null, ParameterDirection? direction = null, int? size = null)
{
ParameterDirection p_direction = direction ?? ParameterDirection.Input;
var oracleParameter = size.HasValue ? new OracleParameter(name, oracleDbType, size.Value, value, p_direction) :
new OracleParameter(name, oracleDbType, value, p_direction);
oracleParameters.Add(oracleParameter);
}
public void Add(string name, OracleDbType oracleDbType, ParameterDirection direction)
{
var oracleParameter = new OracleParameter(name, oracleDbType, direction);
oracleParameters.Add(oracleParameter);
}
public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
((SqlMapper.IDynamicParameters)dynamicParameters).AddParameters(command, identity);
var oracleCommand = command as OracleCommand;
if (oracleCommand != null)
{
oracleCommand.Parameters.AddRange(oracleParameters.ToArray());
}
}
public T Get<T>(string name)
{
var paramInfo = oracleParameters.Single(p => p.ParameterName == name);
object val = paramInfo.Value;
if (val == DBNull.Value)
{
if (default(T) != null)
{
throw new ApplicationException("Attempting to cast a DBNull to a non nullable type! Note that out/return parameters will not have updated values until the data stream completes (after the 'foreach' for Query(..., buffered: false), or after the GridReader has been disposed for QueryMultiple)");
}
return default(T);
}
return (T)val;
}
public int GetIntNumber(string name) => Get<OracleDecimal>(name).ToInt32();
public long GetLongNumber(string name) => Get<OracleDecimal>(name).ToInt64();
public bool GetBoolean(string name) => Get<OracleDecimal>(name).ToByte() == 1;
public string GetString(string name) =>
Get<OracleString>(name) != null ? Get<OracleString>(name).Value : null;
}
}
<file_sep>/PropertyRegister.REAU.Web.Api/ServiceCollectionExtensions.cs
using Microsoft.Extensions.Configuration;
using PropertyRegister.REAU.Applications.Results;
using Rebus.Config;
using Rebus.Routing.TypeBased;
using Rebus.ServiceProvider;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddRebusWithOracleTransport(this IServiceCollection services, IConfiguration configuration)
{
return services.AddRebus(rconfig => rconfig
.Transport(t => t.UseOracleAsOneWayClient(System.Configuration.ConfigurationManager.ConnectionStrings["defaultRWConnectionString"].ConnectionString, "mbus_messages"))
.Routing(r => r.TypeBased().Map<ApplicationAcceptedResult>("q_appl_processing")));
}
}
}
<file_sep>/PropertyRegister.REAU/Common/WrappedBinaryStream.cs
using System;
using System.Data;
using System.IO;
namespace PropertyRegister.REAU.Common
{
public class WrappedBinaryStream : Stream
{
private readonly IDataReader _reader;
private int _columnIndex = 0;
private long _position = 0;
#region Construcotrs
public WrappedBinaryStream(IDataReader reader)
{
_position = 0;
_reader = reader;
_reader.Read();
}
#endregion
#region Overriden Methods
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { return _position; }
set { _position = value; }
}
public override void Flush()
{
}
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
{
if ((offset < 0) && (offset > this.Length))
throw new ArgumentException("Invalid seek origin.");
_position = offset;
break;
}
case SeekOrigin.End:
{
if ((offset > 0) && (offset < -this.Length))
throw new ArgumentException("Invalid seek origin.");
_position = this.Length - offset;
break;
}
case SeekOrigin.Current:
{
if ((_position + offset > this.Length) || (_position + offset < 0))
throw new ArgumentException("Invalid seek origin.");
_position = _position + offset;
break;
}
default:
{
throw new ArgumentOutOfRangeException("origin", origin, "Unknown SeekOrigin");
}
}
return _position;
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
int _bytesRead = Convert.ToInt32(_reader.GetBytes(_columnIndex, _position, buffer, offset, count));
_position += (long)_bytesRead;
return (int)_bytesRead;
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
protected override void Dispose(bool disposing)
{
if (_reader != null)
_reader.Dispose();
base.Dispose(disposing);
}
#endregion
}
}
<file_sep>/ConsoleApp1/Program.cs
using PropertyRegister.REAU.Applications;
using PropertyRegister.REAU.Applications.Results;
using Rebus.Activation;
using Rebus.Config;
using Rebus.Handlers;
using Rebus.Retry.Simple;
using Rebus.Routing.TypeBased;
using System;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
string connString = "Data Source=pr_reau; User ID=pr_reau_dev; Password=<PASSWORD>;";
using (var activator = new BuiltinHandlerActivator())
{
//activator.Handle<ApplicationReceivedMessage>((message) =>
//{
// Console.WriteLine($"Got message of {nameof(message)} with value {(char)message.ID}.");
// return Task.CompletedTask;
//});
activator.Register(() => new ApplicationAcceptedResultHandler1());
var bus = Configure.With(activator)
//.Transport(t => t.UseMsmq("consumer.input"))
.Transport(t => t.UseOracle(connString, "mbus_messages", "error"))
.Routing(r => r.TypeBased()
.Map<ApplicationReceivedMessage>("consumer.input")
.Map<ApplicationAcceptedResult>("error"))
.Options(c => c.SimpleRetryStrategy(maxDeliveryAttempts: 3, errorQueueAddress: "q_error"))
.Start();
//bus.Subscribe<ApplicationReceivedMessage>().Wait();
Console.WriteLine("This is Console 1: Subscriber");
Console.WriteLine("Press ENTER to quit");
Console.ReadLine();
Console.WriteLine("Quitting...");
}
}
}
public class ApplicationAcceptedResultHandler1 : IHandleMessages<ApplicationAcceptedResult>
{
public Task Handle(ApplicationAcceptedResult message)
{
Console.WriteLine($"Handled message of {nameof(message)} with value {message.ApplicationNumber}.");
return Task.CompletedTask;
}
}
}
<file_sep>/PropertyRegister.REAU.Web.Api/Test/NomeclaturesProviderDummy.cs
using PropertyRegister.REAU.Domain;
using PropertyRegister.REAU.Nomenclatures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Web.Api.Test
{
public class NomenclaturesProviderDummy : INomenclaturesProvider
{
public ICollection<ApplicationServiceType> GetApplicationServiceTypes()
{
return new List<ApplicationServiceType>
{
new ApplicationServiceType() {
ApplicationTypeID = 1,
Title = "Услуга платена стандартна",
IsFree = false,
IsReport = false,
PaymentAfterRegistration = false,
PaymentAmount = 10m,
PaymentDeadline = new TimeSpan(3, 0, 0, 0),
XmlNamespace = "https://registryagency.bg/schema/v1/CertificateForPerson"
},
new ApplicationServiceType() {
ApplicationTypeID = 2,
Title = "Услуга безплатна стандартна",
IsFree = true,
IsReport = false,
PaymentAfterRegistration = false,
PaymentAmount = 0m,
XmlNamespace = "https://registryagency.bg/schema/v1/CertificateForPersonFree"
},
new ApplicationServiceType() {
ApplicationTypeID = 3,
Title = "Корекция",
IsFree = true,
IsReport = false,
PaymentAfterRegistration = false,
PaymentAmount = 0m,
XmlNamespace = "https://registryagency.bg/schema/v1/Correction"
},
new ApplicationServiceType() {
ApplicationTypeID = 4,
Title = "Справка безплатна стандартна",
IsFree = true,
IsReport = true,
PaymentAfterRegistration = false,
PaymentAmount = 10m,
PaymentDeadline = new TimeSpan(3, 0, 0, 0),
XmlNamespace = "https://registryagency.bg/schema/v1/Report1"
},
new ApplicationServiceType() {
ApplicationTypeID = 5,
Title = "Справка платена стандартна",
IsFree = false,
IsReport = true,
PaymentAfterRegistration = false,
PaymentAmount = 10m,
PaymentDeadline = new TimeSpan(3, 0, 0, 0),
XmlNamespace = "https://registryagency.bg/schema/v1/Report2"
},
};
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/Persistence/ServiceActionRepository.cs
using CNSys.Data;
using PropertyRegister.REAU.Applications.Models;
using System.Collections.Generic;
namespace PropertyRegister.REAU.Applications.Persistence
{
public class ServiceActionSearchCriteria
{
public long? ServiceOperationID { get; internal set; }
public string OperationID { get; set; }
public ServicеActionTypes? ActionType { get; internal set; }
}
public interface IServiceActionRepository : IRepository<ServiceAction, long?, ServiceActionSearchCriteria>
{
}
public class ServiceActionRepository : RepositoryBase<ServiceAction, long?, ServiceActionSearchCriteria, ApplicationProcessDataContext>, IServiceActionRepository
{
public ServiceActionRepository() : base(false)
{
}
protected override void CreateInternal(ApplicationProcessDataContext context, ServiceAction item)
{
context.ServiceActionCreate(item.OperationID, item.ServiceInstanceID, item.ApplicationID, (int)item.ApplicationStatus, (int)item.ActionTypeID.Value, out long serviceActionID);
item.ServiceActionID = serviceActionID;
}
protected override IEnumerable<ServiceAction> SearchInternal(ApplicationProcessDataContext context, ServiceActionSearchCriteria searchCriteria)
{
return base.SearchInternal(context, searchCriteria);
}
}
}
<file_sep>/PropertyRegister.REAU.Web.Api/Controllers/ApplicationsController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using PropertyRegister.REAU.Applications;
using System;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Web.Api.Controllers
{
public class ApplicationsController : BaseApiController
{
private readonly IApplicationAcceptanceService ApplicationService;
public ApplicationsController(IApplicationAcceptanceService applicationService)
{
ApplicationService = applicationService;
}
[HttpGet]
//[RequiredOperationHeader]
public IActionResult Get([FromServices] ILogger<int> logger)
{
//int id = 55;
//logger.LogError("test", id);
//logger.LogCritical("some critical event with id: {id}", id);
return Ok(new { id = 5, oid = RequestOperationID });
}
[HttpPost]
[RequiredOperationHeader]
public async Task<IActionResult> AcceptApplication(IFormFile file)
{
var result = await ApplicationService.AcceptApplicationAsync(RequestOperationID, file.OpenReadStream());
return Ok(result);
}
}
}
<file_sep>/PropertyRegister.REAU.Web.Api/PrincipalMiddleware.cs
using CNSys.Security;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Web.Api
{
public class PrincipalMiddleware
{
private readonly RequestDelegate _next;
private const string TestUserClientID = "1";
public PrincipalMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
var user = httpContext.User;
var testPrincipal = new TestPrincipal(user, TestUserClientID);
httpContext.User = testPrincipal;
System.Threading.Thread.CurrentPrincipal = testPrincipal;
await _next(httpContext);
}
}
public static class PrincipalMiddlewareExtensions
{
public static IApplicationBuilder UsePrincipalMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<PrincipalMiddleware>();
}
}
public class TestPrincipal : ClaimsPrincipal, IDataSourceUser
{
public TestPrincipal(IPrincipal principal, string clientID) : base(principal)
=> ClientID = clientID;
public string ClientID { get; }
public string ProxyUserID => throw new NotImplementedException();
}
}
<file_sep>/PropertyRegister.REAU/Common/Persistence/CommonDataContext.cs
using Dapper;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
using PropertyRegister.REAU.Common.Models;
using PropertyRegister.REAU.Persistence;
using System;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
namespace PropertyRegister.REAU.Common.Persistence
{
public class CommonDataContext : BaseDataContext
{
public CommonDataContext(DbConnection dbConnection) : base(dbConnection)
{
SqlMapper.SetTypeMap(typeof(ServiceOperation), DataContextHelper.ColumnMap<ServiceOperation>());
SqlMapper.SetTypeMap(typeof(DocumentData), DataContextHelper.ColumnMap<DocumentData>());
}
public void ServiceOperationCreate(string operationID, int serviceOperationTypeID,
out long serviceOperationID, out bool isCompleted, out string result)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_OperationID", OracleDbType.Varchar2, operationID);
parameters.Add("p_OperationTypeID", OracleDbType.Int32, serviceOperationTypeID);
parameters.Add("p_ServiceOperationID_out", OracleDbType.Int32, null, System.Data.ParameterDirection.Output);
parameters.Add("p_IsCompleted_out", OracleDbType.Int32, null, System.Data.ParameterDirection.Output);
parameters.Add("p_Result_out", OracleDbType.Varchar2, null, System.Data.ParameterDirection.Output, 2000);
DbConnection.SPExecute("pkg_velin.p_Service_Operation_Create", parameters);
serviceOperationID = parameters.GetLongNumber("p_ServiceOperationID_out");
isCompleted = parameters.GetBoolean("p_IsCompleted_out");
result = parameters.GetString("p_Result_out");
}
public void ServiceOperationUpdate(long serviceOperationID, string operationID, bool isCompleted, string result)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_ServiceOperationID", OracleDbType.Int64, serviceOperationID);
parameters.Add("p_OperationID", OracleDbType.Varchar2, operationID);
parameters.Add("p_IsCompleted", OracleDbType.Int32, isCompleted);
parameters.Add("p_Result", OracleDbType.Varchar2, result);
DbConnection.SPExecute("pkg_velin.p_Service_Operation_Update", parameters);
}
public CnsysGridReader ServiceOperationSearch(long? serviceOperationID, string operationID, int? operationTypeID)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_ServiceOperationID", OracleDbType.Int64, serviceOperationID);
parameters.Add("p_OperationID", OracleDbType.Varchar2, operationID);
parameters.Add("p_OperationTypeID", OracleDbType.Int32, operationTypeID);
parameters.Add("c_Data", OracleDbType.RefCursor, ParameterDirection.Output);
return DbConnection.SPExecuteReader("PKG_VELIN.p_Service_Operation_Search", parameters);
}
#region documents
public void DocumentDataCreate(string docIdentifier, string contentType, string filename, bool isTemporal, OracleBlob content, out long documentId)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_Guid", OracleDbType.Varchar2, docIdentifier);
parameters.Add("p_ContentType", OracleDbType.Varchar2, contentType);
parameters.Add("p_Filename", OracleDbType.Varchar2, filename);
parameters.Add("p_IsTemp", OracleDbType.Int32, isTemporal);
parameters.Add("p_Content", OracleDbType.Blob, content);
parameters.Add("p_DocumentId_out", OracleDbType.Int32, null, System.Data.ParameterDirection.Output);
DbConnection.SPExecute("pkg_velin.p_Document_Data_Create", parameters);
documentId = parameters.GetLongNumber("p_DocumentId_out");
}
public void DocumentDataUpdate(string docIdentifier, string contentType, string filename, bool isTemporal)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_Guid", OracleDbType.Varchar2, docIdentifier);
parameters.Add("p_ContentType", OracleDbType.Varchar2, contentType);
parameters.Add("p_Filename", OracleDbType.Varchar2, filename);
parameters.Add("p_IsTemp", OracleDbType.Int32, isTemporal);
DbConnection.SPExecute("pkg_velin.p_Document_Data_Update", parameters);
}
public void DocumentDataDelete(Guid key)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_Guid", OracleDbType.Varchar2, key);
DbConnection.SPExecute("pkg_velin.p_Document_Data_Delete", parameters);
}
public CnsysGridReader DocumentDataSearch(string documentIDs, string documentIdentifiers, int startIndex, int pageSize, out int? count)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_Document_Ids", OracleDbType.Varchar2, documentIDs);
parameters.Add("p_Guid_Ids", OracleDbType.Varchar2, documentIdentifiers);
parameters.Add("p_StartIndex", OracleDbType.Int32, startIndex);
parameters.Add("p_PageSize", OracleDbType.Int32, pageSize);
parameters.Add("p_ResultsCount_out", OracleDbType.Int32, null, System.Data.ParameterDirection.Output);
parameters.Add("p_Data", OracleDbType.RefCursor, ParameterDirection.Output);
var reader = DbConnection.SPExecuteReader("PKG_VELIN.p_Document_Data_Search", parameters);
count = parameters.GetIntNumber("p_ResultsCount_out");
return reader;
}
public IDataReader DocumentContentGet(string docIdentifier)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_Guid", OracleDbType.Varchar2, docIdentifier);
parameters.Add("c_Data", OracleDbType.RefCursor, ParameterDirection.Output);
return DbConnection.SPExecuteReader("PKG_VELIN.p_Document_Data_GetContent", parameters, CommandBehavior.SequentialAccess);
}
#endregion
}
}
<file_sep>/PropertyRegister.REAU/Applications/Models/ServiceInstance.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications.Models
{
/// <summary>
/// Заявена услуга
/// </summary>
public class ServiceInstance
{
public long? ServiceInstanceID { get; set; }
/// <summary>
/// Идентификатор на служба по вписвания
/// </summary>
public int OfficeID { get; set; }
/// <summary>
/// идентификатор на потребителския профил на заявителя в ЕПЗЕУ
/// </summary>
public string ApplicantCIN { get; set; }
}
}
<file_sep>/PropertyRegister.REAU.Test/Mocks/PaymentIntegrationClientMock.cs
using PropertyRegister.REAU.Integration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Test.Mocks
{
public class PaymentIntegrationClientMock : IPaymentIntegrationClient
{
public Task<PaymentResponse> InitiatePaymentAsync(PaymentRequest paymentRequest)
{
return Task.FromResult(new PaymentResponse()
{
PaymentIdentifier = $"PMT_{Guid.NewGuid()}",
Successfull = true
});
}
public Task<PaymentResponse> InitiateServiceApplicationAsync(ServiceRequest serviceRequest)
{
return Task.FromResult(new PaymentResponse()
{
PaymentIdentifier = $"PMT_{Guid.NewGuid()}",
Successfull = true
});
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/ApplicationService.cs
using PropertyRegister.REAU.Applications.Models;
using PropertyRegister.REAU.Applications.Persistence;
using PropertyRegister.REAU.Applications.Results;
using PropertyRegister.REAU.Common;
using PropertyRegister.REAU.Integration;
using PropertyRegister.REAU.Nomenclatures;
using PropertyRegister.REAU.Payments;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications
{
public interface IApplicationProcessingService
{
Task<ApplicationProcessedResult> ProcessApplicationAsync(long applicationID);
}
public class ApplicationService : IApplicationProcessingService
{
private readonly INomenclaturesProvider NomenclaturesProvider;
private readonly IIdempotentOperationExecutor IdempotentOperationExecutor;
private readonly IActionDispatcher ActionDispatcher;
private readonly IPaymentManager PaymentManager;
private readonly IPropertyRegisterClient PropertyRegisterClient;
private readonly IApplicationRepository ApplicationRepository;
private readonly IServiceActionRepository ServiceActionRepository;
public ApplicationService(
IApplicationRepository applicationRepository,
IServiceActionRepository serviceActionRepository,
IPropertyRegisterClient propertyRegisterClient,
INomenclaturesProvider nomenclaturesProvider,
IIdempotentOperationExecutor idempotentOperationExecutor,
IActionDispatcher actionDispatcher,
IPaymentManager paymentManager)
{
ApplicationRepository = applicationRepository;
ServiceActionRepository = serviceActionRepository;
PropertyRegisterClient = propertyRegisterClient;
NomenclaturesProvider = nomenclaturesProvider;
IdempotentOperationExecutor = idempotentOperationExecutor;
ActionDispatcher = actionDispatcher;
PaymentManager = paymentManager;
}
public async Task<ApplicationProcessedResult> ProcessApplicationAsync(long applicationID)
{
var result = await IdempotentOperationExecutor.ExecuteAsync(applicationID.ToString(), Common.Models.ServiceOperationTypes.ProcessServiceApplication, (oid) =>
{
var application = ApplicationRepository.Search(new ApplicationSearchCriteria() { ApplicationIDs = new List<long> { applicationID } }).SingleOrDefault();
if (application == null && application.Status != ApplicationStatuses.Accepted)
throw new InvalidOperationException();
// decide which api to call
if (application.IsMainApplication)
{
return RequestApplicationPaymentAsync(oid, application);
}
else
{
return SendCorrectionApplicationToPRAsync(oid, application);
}
}, async (operationResult) => {
// when application is free should be prepared to be sent to PR immediatelly
if (operationResult.ApplicationStatus == ApplicationStatuses.WaitingRegistration ||
operationResult.ApplicationStatus == ApplicationStatuses.InProgress)
{
await ActionDispatcher.SendAsync(operationResult);
}
});
return result;
}
public async Task ProcessServicePaymentChangeAsync(string paymentIdentifier, object paymentData)
{
var operationResult = await IdempotentOperationExecutor.ExecuteAsync(paymentIdentifier, Common.Models.ServiceOperationTypes.ProcessServicePayment, (oid) =>
{
var application = ApplicationRepository
.Search(new ApplicationSearchCriteria() { PaymentIdentifier = paymentIdentifier }).SingleOrDefault();
if (application == null || application.Status != ApplicationStatuses.WaitingPayment)
throw new InvalidOperationException();
var serviceType = NomenclaturesProvider.GetApplicationServiceTypes().Single(t => t.ApplicationTypeID == application.ApplicationTypeID);
application.Status = serviceType.IsReport ? ApplicationStatuses.InProgress : ApplicationStatuses.WaitingRegistration;
ApplicationRepository.Update(application);
var action = new ServiceAction()
{
OperationID = oid,
ServiceInstanceID = application.ServiceInstanceID,
ApplicationID = application.ApplicationID.Value,
ApplicationStatus = application.Status.Value,
ActionTypeID = ServicеActionTypes.PaymentChange,
};
ServiceActionRepository.Create(action);
return Task.FromResult(new Results.PaymentProcessedResult()
{
ApplicationID = application.ApplicationID.Value,
ApplicationStatus = application.Status.Value
});
});
await ActionDispatcher.SendAsync(operationResult);
}
//////
////// API CALLS
//////
private async Task<ApplicationProcessedResult> SendCorrectionApplicationToPRAsync(long operationID, Models.Application application)
{
var prResponse = await PropertyRegisterClient.RegisterServiceApplicationAsync(null);
// TODO
// ANALYZE prResponse
application.Status = ApplicationStatuses.Completed;
ApplicationRepository.Update(application);
var action = new ServiceAction()
{
OperationID = operationID,
ServiceInstanceID = application.ServiceInstanceID,
ApplicationID = application.ApplicationID.Value,
ApplicationStatus = application.Status.Value,
ActionTypeID = ServicеActionTypes.ApplicationRegistrationInPR,
};
ServiceActionRepository.Create(action);
return new Results.ApplicationProcessedResult()
{
ApplicationID = application.ApplicationID.Value
};
}
private async Task<ApplicationProcessedResult> RequestApplicationPaymentAsync(long operationID, Models.Application application)
{
var servicePayment = await PaymentManager.RequestApplicationPaymentAsync(application, filedAmount: null /*from xml*/);
if (servicePayment.Status != PaymentStatuses.Ordered)
throw new Exception(servicePayment.ErrorDescription);
ApplicationRepository.CreateServicePayment(servicePayment);
var serviceType = NomenclaturesProvider.GetApplicationServiceTypes().Single(t => t.ApplicationTypeID == application.ApplicationTypeID);
application.Status = serviceType.IsFree ?
(serviceType.IsReport ? ApplicationStatuses.InProgress : ApplicationStatuses.WaitingRegistration) : ApplicationStatuses.WaitingPayment;
ApplicationRepository.Update(application);
var action = new ServiceAction()
{
OperationID = operationID,
ServiceInstanceID = application.ServiceInstanceID,
ApplicationID = application.ApplicationID.Value,
ApplicationStatus = application.Status.Value,
ActionTypeID = ServicеActionTypes.RequestedPayment,
};
ServiceActionRepository.Create(action);
return new Results.ApplicationProcessedResult
{
ApplicationStatus = application.Status,
PaymentAmount = servicePayment.ObligationAmount,
PaymentDeadline = servicePayment.PaymentDeadline,
PaymentIdentifier = servicePayment.PaymentIdentifier
};
}
}
}
<file_sep>/PropertyRegister.REAU/Common/Models/ServiceOperation.cs
using PropertyRegister.REAU.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Common.Models
{
public enum ServiceOperationTypes
{
AcceptServiceApplication = 1,
ProcessServiceApplication = 2,
ProcessServicePayment = 3
}
public class ServiceOperation
{
[DapperColumn("service_operation_id")]
public long? ServiceOperationID { get; set; }
[DapperColumn("operation_id")]
public string OperationID { get; set; }
[DapperColumn("operation_type")]
public ServiceOperationTypes ServiceOperationType { get; set; }
[DapperColumn("is_completed")]
public bool IsCompleted { get; set; }
[DapperColumn("result")]
public string Result { get; set; }
}
}
<file_sep>/PropertyRegister.REAU.Test/Mocks/PropertyRegisterClientMock.cs
using PropertyRegister.REAU.Integration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Test.Mocks
{
public class PropertyRegisterClientMock : IPropertyRegisterClient
{
public Task<PropertyRegisterApplicationResult> ExecuteReportApplicationAsync(object request)
{
return Task.FromResult(new PropertyRegisterApplicationResult()
{
DocumentIdentifier = $"PR_REP_{DateTime.Now.ToString("yyyymmdd")}"
});
}
public Task<ServiceApplicationResult> RegisterServiceApplicationAsync(object request)
{
return Task.FromResult(new ServiceApplicationResult()
{
RegisterStatusID = 1,
DocumentIdentifier = $"PR_{DateTime.Now.ToString("yyyymmdd")}_number"
});
}
}
}
<file_sep>/PropertyRegister.REAU/Integration/PaymentIntegrationClient.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Integration
{
public interface IPaymentIntegrationClient
{
Task<PaymentResponse> InitiatePaymentAsync(PaymentRequest paymentRequest);
Task<PaymentResponse> InitiateServiceApplicationAsync(ServiceRequest serviceRequest);
}
internal class PaymentIntegrationClient : IPaymentIntegrationClient
{
public Task<PaymentResponse> InitiatePaymentAsync(PaymentRequest paymentRequest)
{
return Task.FromResult(new PaymentResponse() {
PaymentIdentifier = paymentRequest.PaymentFor
});
}
public Task<PaymentResponse> InitiateServiceApplicationAsync(ServiceRequest serviceRequest)
{
return Task.FromResult(new PaymentResponse());
}
}
public class PaymentRequest
{
public string PaymentFor { get; set; }
/// <summary>
/// размера на задължението
/// </summary>
public decimal ObligationAmount { get; set; }
/// <summary>
/// стойността на услугата
/// </summary>
public decimal ServiceFee { get; set; }
}
public class ServiceRequest
{
/// <summary>
/// стойността на услугата
/// </summary>
public decimal ServiceFee { get; set; }
}
public class PaymentResponse
{
public string PaymentIdentifier { get; set; }
public bool Successfull { get; set; }
public string Errors { get; set; }
}
}
<file_sep>/PropertyRegister.REAU/Integration/PropertyRegisterClient.cs
using System.IO;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Integration
{
public class PropertyRegisterApplicationResult
{
public string DocumentIdentifier { get; set; }
public Stream DocumentContent { get; set; }
}
public class ServiceApplicationResult : PropertyRegisterApplicationResult
{
public int RegisterStatusID { get; set; }
}
public interface IPropertyRegisterClient
{
Task<ServiceApplicationResult> RegisterServiceApplicationAsync(object request);
Task<PropertyRegisterApplicationResult> ExecuteReportApplicationAsync(object request);
}
public class PropertyRegisterClient : IPropertyRegisterClient
{
public Task<PropertyRegisterApplicationResult> ExecuteReportApplicationAsync(object request)
{
return Task.FromResult(new PropertyRegisterApplicationResult());
}
public Task<ServiceApplicationResult> RegisterServiceApplicationAsync(object request)
{
return Task.FromResult(new ServiceApplicationResult());
}
}
}
<file_sep>/PropertyRegister.REAU.Test/ApplicationTests.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PropertyRegister.REAU.Applications;
using PropertyRegister.REAU.Applications.Persistence;
using PropertyRegister.REAU.Applications.Results;
using PropertyRegister.REAU.Common;
using PropertyRegister.REAU.Common.Persistence;
using PropertyRegister.REAU.Domain;
using PropertyRegister.REAU.Integration;
using PropertyRegister.REAU.Test.Mocks;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace PropertyRegister.REAU.Test
{
[TestClass]
public class ApplicationTests
{
private ServiceProvider ServiceProvider;
private ServiceCollection Services;
public ApplicationTests()
{
var services = new ServiceCollection();
services.AddTransient<ApplicationService>();
services.AddTransient<IApplicationRepository, ApplicationEntityMock>();
services.AddTransient<IDocumentService, DocumentServiceMock>();
services.AddTransient<IPropertyRegisterClient, PropertyRegisterClientMock>();
services.AddTransient<IPaymentIntegrationClient, PaymentIntegrationClientMock>();
services.AddSingleton<DbDataSets>();
Services = services;
ServiceProvider = services.BuildServiceProvider();
}
[TestMethod]
public void TestMethod1()
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("sample.xml");
var obj = (Application)Deserialize(doc, typeof(Application));
}
[TestMethod]
public async Task Test_Application_Save()
{
var response = await DoApplicationSave("sample0101.xml");
Assert.IsNotNull(response);
}
[TestMethod]
public async Task Test_FreeApplication_Save()
{
var response = await DoApplicationSave("sample0102.xml");
Assert.IsTrue(response != null
&& response.PaymentAmount == 0m
&& response.ApplicationStatus == Applications.Models.ApplicationStatuses.Completed
&& !string.IsNullOrEmpty(response.RegisterOutcomeNumber));
}
[TestMethod]
public async Task Test_Correction_Save()
{
var response = await DoApplicationSave("correction01.xml");
Assert.IsNotNull(response);
}
[TestMethod]
public async Task Test_FreeReport_Save()
{
var response = await DoApplicationSave("report01.xml");
Assert.IsTrue(response.ApplicationStatus == Applications.Models.ApplicationStatuses.Completed
&& (response.PaymentAmount == 0m || response.PaymentAmount == null));
}
[TestMethod]
public async Task Test_PaidReport_Save()
{
var response = await DoApplicationSave("report02.xml");
Assert.IsTrue(response.ApplicationStatus == Applications.Models.ApplicationStatuses.WaitingPayment
&& response.PaymentAmount.GetValueOrDefault() > 0m);
}
public Task<ApplicationProcessedResult> DoApplicationSave(string filename, string operationID = null, ServiceProvider serviceProvider = null)
{
return Task.FromResult(new ApplicationProcessedResult());
//XmlDocument doc = new XmlDocument();
//doc.PreserveWhitespace = true;
//doc.Load(filename);
//var portalOperationID = operationID ?? Guid.NewGuid().ToString();
//var applicationService = (serviceProvider ?? ServiceProvider).GetRequiredService<ApplicationService>();
//ApplicationResponse response = null;
//using (var ms = new MemoryStream())
//{
// doc.Save(ms);
// ms.Position = 0;
// response = await applicationService.SaveAsync(portalOperationID, ms);
//}
//return response;
}
[TestMethod]
public void Test_DeserializeConcreteType()
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("sample0101.xml");
var obj = (CertificateForPerson)Deserialize(doc, typeof(CertificateForPerson));
}
[TestMethod]
public void Test_Application_CRUD_Create()
{
new ApplicationRepository().Create(new Applications.Models.Application());
}
[TestMethod]
public void Test_ServiceOperation_Search()
{
var entity = new ServiceOperationRepository();
var data = entity.Search(new ServiceOperationSearchCriteria()
{
ServiceOperationType = Common.Models.ServiceOperationTypes.AcceptServiceApplication
}).ToList();
Assert.IsTrue(data != null);
}
[TestMethod]
public void Test_ServiceOperation_Create()
{
var entity = new ServiceOperationRepository();
var operation = new Common.Models.ServiceOperation()
{
OperationID = Guid.NewGuid().ToString(),
ServiceOperationType = Common.Models.ServiceOperationTypes.AcceptServiceApplication
};
entity.Create(operation);
Assert.IsTrue(operation.ServiceOperationID.HasValue);
}
private object Deserialize(XmlDocument doc, Type type)
{
var serializer = new XmlSerializer(type);
using (StringReader rdr = new StringReader(doc.OuterXml))
{
return serializer.Deserialize(rdr);
}
}
}
[XmlType(AnonymousType = true, Namespace = "reau.pr.bg")]
[XmlRoot("Application", Namespace = "reau.pr.bg", IsNullable = false)]
public class Application
{
public Header Header { get; set; }
[System.Xml.Serialization.XmlArrayItemAttribute("AttachedDocument")]
public AttachedDocument[] AttachedDocuments { get; set; }
}
public class Header
{
public ServiceInfo ServiceInfo { get; set; }
public string OfficeID { get; set; }
public Applicant Applicant { get; set; }
}
public class ServiceInfo
{
public string Code { get; set; }
public decimal Obligation { get; set; }
}
public class Applicant
{
public string CIN { get; set; }
}
public class AttachedDocument
{
public Guid BackOfficeGUID { get; set; }
}
[XmlType(AnonymousType = true, Namespace = "reau.pr.bg/CertificateForPerson")]
[XmlRoot("CertificateForPerson", Namespace = "reau.pr.bg/CertificateForPerson", IsNullable = false)]
public class CertificateForPerson : ApplicationBase
{
public string Type { get; set; }
}
[XmlType(AnonymousType = true, Namespace = "reau.pr.bg")]
public class ApplicationBase
{
public Header Header { get; set; }
[System.Xml.Serialization.XmlArrayItemAttribute("AttachedDocument")]
public AttachedDocument[] AttachedDocuments { get; set; }
}
}
<file_sep>/PropertyRegister.REAU/Extensions/ServiceCollectionExtensions.cs
using PropertyRegister.REAU.Applications;
using PropertyRegister.REAU.Applications.Persistence;
using PropertyRegister.REAU.Common;
using PropertyRegister.REAU.Common.Persistence;
using PropertyRegister.REAU.Integration;
using PropertyRegister.REAU.Nomenclatures;
using PropertyRegister.REAU.Payments;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddApplicationsPersistence(this IServiceCollection serviceCollection)
{
return serviceCollection
.AddTransient<IApplicationRepository, ApplicationRepository>()
.AddTransient<IServiceInstanceRepository, ServiceInstanceRepository>()
.AddTransient<IApplicationDocumentRepository, ApplicationDocumentRepository>()
.AddTransient<IServiceActionRepository, ServiceActionRepository>();
}
public static IServiceCollection AddApplicationsAcceptance(this IServiceCollection serviceCollection)
{
return serviceCollection
.AddTransient<IApplicationAcceptanceService, ApplicationAcceptanceService>()
.AddTransient<INomenclaturesProvider, NomenclaturesProvider>()
.AddTransient<IApplicationInfoResolver, ApplicationInfoResolver>();
}
public static IServiceCollection AddApplicationsProcessing(this IServiceCollection serviceCollection)
{
return serviceCollection
.AddTransient<IApplicationProcessingService, ApplicationService>()
.AddTransient<INomenclaturesProvider, NomenclaturesProvider>()
.AddTransient<IPaymentManager, PaymentManager>();
}
public static IServiceCollection AddDocuments(this IServiceCollection serviceCollection)
{
return serviceCollection
.AddTransient<IDocumentDataRepository, DocumentDataRepository>()
.AddTransient<IDocumentService, DocumentService>();
}
public static IServiceCollection AddREAUInfrastructureServices(this IServiceCollection serviceCollection)
{
return serviceCollection
.AddTransient<IActionDispatcher, DefaultActionDispatcher>()
.AddTransient<IIdempotentOperationExecutor, IdempotentOperationExecutor>()
.AddTransient<IServiceOperationRepository, ServiceOperationRepository>();
}
public static IServiceCollection AddIntegrationClients(this IServiceCollection serviceCollection)
{
return serviceCollection
.AddTransient<IPropertyRegisterClient, PropertyRegisterClient>()
.AddTransient<IPaymentIntegrationClient, PaymentIntegrationClient>();
}
}
}
<file_sep>/PropertyRegister.REAU/Common/DistributedOperationService.cs
using Newtonsoft.Json;
using PropertyRegister.REAU.Common.Models;
using PropertyRegister.REAU.Common.Persistence;
using PropertyRegister.REAU.Persistence;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Common
{
public interface IIdempotentOperationExecutor
{
Task<T> ExecuteAsync<T>(string operationID, ServiceOperationTypes operationType, Func<long, Task<T>> transactionalOperation, Action<T> nonTransactionOperationOnFirstCall = null);
}
public class IdempotentOperationExecutor : IIdempotentOperationExecutor
{
private readonly IServiceOperationRepository ServiceOperationRepository;
public IdempotentOperationExecutor(IServiceOperationRepository serviceOperationRepository)
{
ServiceOperationRepository = serviceOperationRepository;
}
public async Task<T> ExecuteAsync<T>(string operationID, ServiceOperationTypes operationType,
Func<long, Task<T>> transactionalOperation, Action<T> nonTransactionOperationOnFirstCall = null)
{
try
{
bool firstOperationCall = false;
var transactResult = await DbContextHelper.TransactionalOperationAsync(async () =>
{
var operation = new ServiceOperation()
{
OperationID = operationID,
ServiceOperationType = operationType
};
ServiceOperationRepository.Create(operation);
if (operation.IsCompleted)
{
if (string.IsNullOrEmpty(operation.Result))
return default(T);
return JsonConvert.DeserializeObject<T>(operation.Result);
}
else
{
T res = await transactionalOperation(operation.ServiceOperationID.Value);
operation.Result = JsonConvert.SerializeObject(res);
operation.IsCompleted = true;
ServiceOperationRepository.Update(operation);
firstOperationCall = true;
return res;
}
});
if (firstOperationCall)
nonTransactionOperationOnFirstCall?.Invoke(transactResult);
return transactResult;
}
catch (Exception ex)
{
// log ex
throw;
}
}
}
}
<file_sep>/PropertyRegister.REAU.Test/DocumentsTests.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PropertyRegister.REAU.Common.Models;
using PropertyRegister.REAU.Common.Persistence;
using PropertyRegister.REAU.Persistence;
using PropertyRegister.REAU.Test.Mocks;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Test
{
[TestClass]
public class DocumentsTests
{
private ServiceProvider ServiceProvider;
private ServiceCollection Services;
public DocumentsTests()
{
var services = new ServiceCollection();
services.AddTransient<IDocumentDataRepository, DocumentDataRepository>();
Services = services;
ServiceProvider = services.BuildServiceProvider();
}
[TestInitialize]
public void Init()
{
Thread.CurrentPrincipal = new TestPrincipal("1");
}
[TestMethod]
public async Task Test_DocumentData()
{
await DbContextHelper.TransactionalOperationAsync(() =>
{
string filename = @"C:\Users\vachev\Desktop\scripts.sql";
var entity = ServiceProvider.GetRequiredService<IDocumentDataRepository>();
using (var fs = File.OpenRead(filename))
{
var document = new DocumentData()
{
ContentType = "text/xml",
Filename = "test.txt",
IsTemporal = true,
Content = fs
};
entity.Create(document);
Assert.IsTrue(document.DocID.HasValue);
document.IsTemporal = false;
entity.Update(document);
var documentFound = entity.Search(new DocumentDataSearchCriteria() { Identifiers = new List<string>() { document.Identifier } }).SingleOrDefault();
Assert.IsTrue(documentFound != null && documentFound.IsTemporal == false);
}
return Task.CompletedTask;
});
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/Persistence/ApplicationRepository.cs
using CNSys.Data;
using PropertyRegister.REAU.Applications.Models;
using System;
using System.Collections.Generic;
using CNSys.Extensions;
namespace PropertyRegister.REAU.Applications.Persistence
{
public class ApplicationSearchCriteria
{
public List<long> ApplicationIDs { get; set; }
public long? MainApplicationID { get; set; }
public long? ServiceInstanceID { get; set; }
public string ApplicationIdentifier { get; set; }
public string ReportIdentifier { get; set; }
public ApplicationStatuses? ApplicationStatus { get; set; }
public int? ApplicationType { get; set; }
public string PaymentIdentifier { get; set; }
}
public interface IApplicationRepository : IRepository<Application, long?, ApplicationSearchCriteria>
{
void CreateServicePayment(ServicePayment paymentRequest);
}
public class ApplicationRepository : RepositoryBase<Application, long?, ApplicationSearchCriteria, ApplicationProcessDataContext>, IApplicationRepository
{
public ApplicationRepository() : base(false)
{
}
protected override void CreateInternal(ApplicationProcessDataContext context, Application item)
{
context.ApplicationCreate(item.MainApplicationID, item.ServiceInstanceID, item.IsReport,
(int)item.Status, item.StatusTime, item.ApplicationTypeID.Value, item.RegistrationTime, out long applicationID, out string applIdentifier, out string reportIdentifier);
item.ApplicationID = applicationID;
item.ApplicationIdentifier = applIdentifier;
item.ReportIdentifier = reportIdentifier;
}
protected override void UpdateInternal(ApplicationProcessDataContext context, Application item)
{
context.ApplicationUpdate(item.ApplicationID.Value, item.MainApplicationID, item.ServiceInstanceID, item.ApplicationIdentifier, item.ReportIdentifier,
(int)item.Status, item.StatusTime, item.ApplicationTypeID.Value, item.RegistrationTime);
}
protected override IEnumerable<Application> SearchInternal(ApplicationProcessDataContext context, ApplicationSearchCriteria searchCriteria)
{
IEnumerable<Application> res;
string ids = string.Join(",", searchCriteria.ApplicationIDs.ToArray());
using (var data = context.ApplicationSearch(ids, searchCriteria.MainApplicationID, searchCriteria.ServiceInstanceID,
searchCriteria.ApplicationIdentifier, searchCriteria.ReportIdentifier, (int?)searchCriteria.ApplicationStatus, searchCriteria.ApplicationType,
1, 20, out int count))
{
res = data.ReadToList<Application>();
}
return res;
}
public void CreateServicePayment(ServicePayment paymentRequest)
{
throw new NotImplementedException();
}
}
}
<file_sep>/PropertyRegister.REAU.Test/Mocks/ApplicationEntityMock.cs
using CNSys.Data;
using PropertyRegister.REAU.Applications;
using PropertyRegister.REAU.Applications.Models;
using PropertyRegister.REAU.Applications.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
namespace PropertyRegister.REAU.Test.Mocks
{
public class ApplicationEntityMock : IApplicationRepository
{
private readonly DbDataSets DataSets;
public bool IsReadOnly => throw new NotImplementedException();
public ApplicationEntityMock(DbDataSets dataSets)
{
DataSets = dataSets;
}
public void AddApplication(Applications.Models.Application application)
{
if (application.ServiceInstanceID == default(long) ||
application.Status == null ||
application.ApplicationTypeID == null)
throw new ArgumentException("IApplicationEntity.AddApplication has wrong parameters!");
application.ApplicationID = 1000;
application.ApplicationIdentifier = $"{DateTime.Now.ToString("yyyymmdd")}-0001";
}
public void SaveApplicationDocument(ApplicationDocument applicationDocument)
{
if (applicationDocument.DocumentID == default(long) || applicationDocument.DocumentType == null)
throw new ArgumentException(nameof(applicationDocument));
}
public void SaveServiceDocument(ServiceDocument serviceDocument)
{
if (serviceDocument.DocumentID == default(long) || serviceDocument.ServiceDocumentTypeID == null)
throw new ArgumentException(nameof(serviceDocument));
}
public void SavePaymentRequest(ServicePayment paymentRequest)
{
paymentRequest.PaymentRequestID = 1000;
}
public IEnumerable<Applications.Models.Application> SearchApplications(long? applicationID, string appNumber)
{
return DataSets.Applications.Where(a => (applicationID.HasValue && a.ApplicationID == applicationID.Value) ||
(!string.IsNullOrEmpty(appNumber) && a.ApplicationIdentifier == appNumber));
}
public IEnumerable<ServiceInstanceAction> SearchServiceActions(string operationID, ServicеActionTypes actionType)
{
return DataSets.ServiceActions.Where(sa => sa.OperationID.ToString() == operationID && sa.ActionTypeID == actionType);
}
public void UpdateApplication(Applications.Models.Application application)
{
}
public void SaveServiceAction(ServiceInstanceAction serviceAction)
{
serviceAction.ServiceActionID = 1000;
}
public void AddServiceInstance(ServiceInstance serviceInstance)
{
serviceInstance.ServiceInstanceID = 1000;
}
public void CreateServicePayment(ServicePayment paymentRequest)
{
throw new NotImplementedException();
}
public void Create(Applications.Models.Application item)
{
throw new NotImplementedException();
}
public void Delete(long? key)
{
throw new NotImplementedException();
}
public void Delete(Applications.Models.Application item)
{
throw new NotImplementedException();
}
public IEnumerable<Applications.Models.Application> Search(ApplicationSearchCriteria searchCriteria)
{
throw new NotImplementedException();
}
public IEnumerable<Applications.Models.Application> Search(object state, ApplicationSearchCriteria searchCriteria)
{
throw new NotImplementedException();
}
public void Update(Applications.Models.Application item)
{
throw new NotImplementedException();
}
public Applications.Models.Application Read(long? key)
{
throw new NotImplementedException();
}
public IEnumerable<Applications.Models.Application> Search(PagedDataState state, ApplicationSearchCriteria searchCriteria)
{
throw new NotImplementedException();
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/Models/Application.cs
using PropertyRegister.REAU.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications.Models
{
/// <summary>
/// Статуси на Заявление за услуга
/// </summary>
public enum ApplicationStatuses
{
/// <summary>
/// Прието.
/// </summary>
Accepted = 1,
/// <summary>
/// Чака регистрация.
/// </summary>
WaitingRegistration = 2,
/// <summary>
/// В процес на изпълнение.
/// </summary>
InProgress = 3,
/// <summary>
/// Чака плащане.
/// </summary>
WaitingPayment = 4,
/// <summary>
/// Прекратено .
/// </summary>
Terminated = 5,
/// <summary>
/// Изпълнено.
/// </summary>
Completed = 6,
//
// Service only
//
/// <summary>
/// Регистрирано
/// </summary>
Registered = 11,
/// <summary>
/// Без движение – за преразглеждане
/// </summary>
WithoutMovementForReview = 12,
/// <summary>
/// Без движение
/// </summary>
WithoutMovement = 13,
/// <summary>
/// Отказано
/// </summary>
Denied = 14,
}
/// <summary>
/// Заявление за услуга
/// </summary>
public class Application
{
[DapperColumn("application_id")]
public long? ApplicationID { get; set; }
/// <summary>
/// връзка към заявена услуга
/// </summary>
[DapperColumn("serviceinstance_id")]
public long ServiceInstanceID { get; set; }
/// <summary>
/// Връзка към основното заявление от ServiceInstanceApplication
/// </summary>
[DapperColumn("mainapplication_id")]
public long? MainApplicationID { get; set; }
/// <summary>
/// уникален идентификатор (референтен номер)
/// </summary>
[DapperColumn("application_identifier")]
public string ApplicationIdentifier { get; set; }
/// <summary>
/// уникален регистров номер на заявление за справка (различен е от референтния номер)
/// </summary>
[DapperColumn("report_identifier")]
public string ReportIdentifier { get; set; }
/// <summary>
/// Актуален Статус (Денормализация?)
/// </summary>
[DapperColumn("status")]
public ApplicationStatuses? Status { get; set; }
/// <summary>
/// Дата на статус (Денормализация?).
/// </summary>
[DapperColumn("statustime")]
public DateTime StatusTime { get; set; }
/// <summary>
/// Идентификатор на вида на заявлението от номенклатурата на ИС на ИР
/// </summary>
[DapperColumn("applicationtype_id")]
public int? ApplicationTypeID { get; set; }
/// <summary>
/// дата на регистрация на заявлението в РЕАУ.
/// </summary>
[DapperColumn("registrationtime")]
public DateTime RegistrationTime { get; set; }
public bool IsReport { get; set; }
public bool IsMainApplication => MainApplicationID == null;
}
}
<file_sep>/PropertyRegister.REAU/Common/DocumentService.cs
using PropertyRegister.REAU.Common.Models;
using PropertyRegister.REAU.Common.Persistence;
using PropertyRegister.REAU.Persistence;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Common
{
public class DocumentCreateRequest
{
public string Filename { get; set; }
public string ContentType { get; set; }
public Stream Content { get; set; }
}
public class DocumentCreateResult
{
public long DocumentDataID { get; set; }
public string DocumentIdentifier { get; set; }
}
public interface IDocumentService
{
Task<DocumentCreateResult> SaveDocumentAsync(DocumentCreateRequest request);
Task DeleteDocumentAsync(string documentIdentifier);
Task<IEnumerable<DocumentData>> GetDocumentsAsync(List<string> documentIdentifiers, bool loadContent = false);
}
public class DocumentService : IDocumentService
{
private readonly IDocumentDataRepository DocumentDataRepository;
public DocumentService(IDocumentDataRepository documentDataRepository)
{
DocumentDataRepository = documentDataRepository;
}
public Task<DocumentCreateResult> SaveDocumentAsync(DocumentCreateRequest request)
{
return DbContextHelper.TransactionalOperationAsync(() => SaveDocumentAsyncInternal(request));
}
public Task DeleteDocumentAsync(string documentIdentifier)
{
if (!Guid.TryParse(documentIdentifier, out Guid guid))
throw new ArgumentException("documentIdentifier not valid GUID!");
DocumentDataRepository.Delete(guid);
return Task.CompletedTask;
}
public Task<IEnumerable<DocumentData>> GetDocumentsAsync(List<string> documentIdentifiers, bool loadContent = false)
{
var docs = DocumentDataRepository.Search(new DocumentDataSearchCriteria()
{
Identifiers = documentIdentifiers
});
if (loadContent)
{
foreach (var doc in docs)
{
doc.Content = DocumentDataRepository.ReadContent(doc.Identifier);
}
}
return Task.FromResult(docs);
}
private Task<DocumentCreateResult> SaveDocumentAsyncInternal(DocumentCreateRequest request)
{
var documentData = new DocumentData()
{
Identifier = Guid.NewGuid().ToString(),
ContentType = request.ContentType,
Filename = request.Filename,
IsTemporal = true,
Content = request.Content
};
DocumentDataRepository.Create(documentData);
return Task.FromResult(new DocumentCreateResult()
{
DocumentDataID = documentData.DocID.Value,
DocumentIdentifier = documentData.Identifier.ToString()
});
}
}
}
<file_sep>/PropertyRegister.REAU/Persistence/DapperColumnAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Persistence
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class DapperColumnAttribute : Attribute
{
private string _name;
public DapperColumnAttribute(string name)
{
this._name = name;
}
public string Name { get { return _name; } }
}
}
<file_sep>/PropertyRegister.REAU/Common/ActionDispatcher.cs
using Rebus.Bus;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Common
{
public interface IActionDispatcher
{
Task SendAsync(object actionData);
}
public class DefaultActionDispatcher : IActionDispatcher
{
private readonly IBus Bus;
public DefaultActionDispatcher(IBus bus)
{
Bus = bus;
}
public Task SendAsync(object actionData) => Bus.Send(actionData);
}
}
<file_sep>/PropertyRegister.REAU/Applications/Persistence/ServiceInstanceRepository.cs
using System.Collections.Generic;
using PropertyRegister.REAU.Applications.Models;
using CNSys.Data;
namespace PropertyRegister.REAU.Applications.Persistence
{
public interface IServiceInstanceRepository : IRepository<ServiceInstance, long?, object>
{
}
public class ServiceInstanceRepository : RepositoryBase<ServiceInstance, long?, object, ApplicationProcessDataContext>, IServiceInstanceRepository
{
public ServiceInstanceRepository() : base(false)
{
}
protected override void CreateInternal(ApplicationProcessDataContext context, ServiceInstance item)
{
context.ServiceInstanceCreate(item.OfficeID, int.Parse(item.ApplicantCIN), out long serviceInstanceID);
item.ServiceInstanceID = serviceInstanceID;
}
protected override void UpdateInternal(ApplicationProcessDataContext context, ServiceInstance item)
{
context.ServiceInstanceUpdate(item.ServiceInstanceID.Value, item.OfficeID, int.Parse(item.ApplicantCIN));
}
protected override IEnumerable<ServiceInstance> SearchInternal(ApplicationProcessDataContext context, object searchCriteria)
{
IEnumerable<ServiceInstance> res;
using (var data = context.ServiceInstanceSearch(null, null, null, 1, 20, out int count))
{
res = data.ReadToList<ServiceInstance>();
}
return res;
}
}
}
<file_sep>/PropertyRegister.REAU.MessageProcessor/Program.cs
using Microsoft.Extensions.Hosting;
using PropertyRegister.REAU.Applications;
using PropertyRegister.REAU.Applications.MessageHandlers;
using PropertyRegister.REAU.Applications.Results;
using Rebus.Activation;
using Rebus.Config;
using Rebus.Handlers;
using Rebus.Retry.Simple;
using Rebus.Routing.TypeBased;
using Rebus.ServiceProvider;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace PropertyRegister.REAU.MessageProcessor
{
class Program
{
static void Main(string[] args)
{
IHost host = null;
var hostBuilder = new HostBuilder()
.ConfigureServices((context, services) =>
{
// applications DI
services.AddApplicationsPersistence()
.AddApplicationsProcessing()
.AddIntegrationClients()
.AddREAUInfrastructureServices();
services.AutoRegisterHandlersFromAssemblyOf<ApplicationAcceptedResultHandler>();
services.AddRebus(rconfig => rconfig
.Transport(t => t.UseOracle(System.Configuration.ConfigurationManager.ConnectionStrings["defaultRWConnectionString"].ConnectionString, "mbus_messages", "q_appl_processing"))
.Routing(r => r.TypeBased().Map<ApplicationAcceptedResult>("q_appl_processing")
.Map<ApplicationProcessedResult>("q_appl_processing")
));
});
try
{
host = hostBuilder.Build();
// start rebus
host.Services.UseRebus();
host.Start();
Console.WriteLine("Press ENTER to quit");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Quitting...");
host?.Dispose();
host = null;
}
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/Models/ServiceAction.cs
using PropertyRegister.REAU.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications.Models
{
/// <summary>
/// Класът описва действия/операции по промяна на състояние на Application/ServiceInstance
/// </summary>
public class ServiceAction
{
[DapperColumn("service_action_id")]
public long? ServiceActionID { get; set; }
[DapperColumn("operation_id")]
public long OperationID { get; set; }
[DapperColumn("service_inst_id")]
public long ServiceInstanceID { get; set; }
[DapperColumn("application_id")]
public long ApplicationID { get; set; }
[DapperColumn("application_status")]
public ApplicationStatuses ApplicationStatus { get; set; }
[DapperColumn("action_type_id")]
public ServicеActionTypes? ActionTypeID { get; set; }
}
}
<file_sep>/PropertyRegister.REAU.Test/ServiceApplicationsTests.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PropertyRegister.REAU.Applications;
using PropertyRegister.REAU.Applications.Persistence;
using PropertyRegister.REAU.Applications.Results;
using PropertyRegister.REAU.Common;
using PropertyRegister.REAU.Common.Persistence;
using PropertyRegister.REAU.Domain;
using PropertyRegister.REAU.Integration;
using PropertyRegister.REAU.Payments;
using PropertyRegister.REAU.Persistence;
using PropertyRegister.REAU.Test.Mocks;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace PropertyRegister.REAU.Test
{
[TestClass]
public class ServiceApplicationsTests
{
private ServiceProvider ServiceProvider;
private ServiceCollection Services;
public ServiceApplicationsTests()
{
var services = new ServiceCollection();
services.AddTransient<ApplicationService>();
services.AddTransient<IApplicationRepository, ApplicationRepository>();
services.AddTransient<IServiceInstanceRepository, ServiceInstanceRepository>();
services.AddTransient<IServiceOperationRepository, ServiceOperationRepository>();
services.AddTransient<IApplicationDocumentRepository, ApplicationDocumentRepository>();
services.AddTransient<IServiceActionRepository, ServiceInstanceActionEntityMock>();
services.AddTransient<IDocumentService, DocumentServiceMock>();
services.AddTransient<IPropertyRegisterClient, PropertyRegisterClientMock>();
services.AddTransient<IPaymentIntegrationClient, PaymentIntegrationClientMock>();
services.AddTransient<IIdempotentOperationExecutor, IdempotentOperationExecutor>();
services.AddTransient<IPaymentManager, PaymentManager>();
services.AddSingleton<IActionDispatcher, DummyActionDispatcherMock>();
services.AddSingleton<IApplicationInfoResolver, ApplicationInfoResolver>();
Services = services;
ServiceProvider = services.BuildServiceProvider();
}
[TestInitialize]
public void Init()
{
Thread.CurrentPrincipal = new TestPrincipal("1");
}
[TestCleanup]
public void CleanUp()
{
}
[TestMethod]
public async Task TestApplicationAcceptance()
{
ApplicationAcceptedResult response = null;
string filename = "sample0102.xml";
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(filename);
var applicationService = ServiceProvider.GetRequiredService<IApplicationAcceptanceService>();
using (var ms = new MemoryStream())
{
doc.Save(ms);
ms.Position = 0;
response = await DbContextHelper.TransactionalOperationAsync(() =>
{
return applicationService.AcceptApplicationAsync(Guid.NewGuid().ToString(), ms);
});
}
Assert.IsTrue(response.ApplicationStatus == Applications.Models.ApplicationStatuses.Accepted);
}
[TestMethod]
public async Task Test_MessageBus()
{
await ServiceProvider.GetRequiredService<IActionDispatcher>()
.SendAsync((long)100);
}
[TestMethod]
public void Test_ApplicationInfoResolver_AttachedDocuments()
{
var resolver = ServiceProvider.GetRequiredService<IApplicationInfoResolver>();
using (var ms = File.OpenRead(@"C:\Users\vachev\Desktop\xsd-xml\xml\CertificateForPersonFromPropertyRegister-test.xml"))
{
var info = resolver.GetApplicationInfoFromXml(ms);
Assert.IsTrue(info.AttachedDocumentIDs != null && info.AttachedDocumentIDs.Any());
}
}
}
}
<file_sep>/PropertyRegister.REAU/Applications/Persistence/ApplicationProcessDataContext.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
using PropertyRegister.REAU.Applications.Models;
using PropertyRegister.REAU.Persistence;
namespace PropertyRegister.REAU.Applications.Persistence
{
public class ApplicationProcessDataContext : BaseDataContext
{
public ApplicationProcessDataContext(DbConnection dbConnection) : base(dbConnection)
{
SqlMapper.SetTypeMap(typeof(Application), DataContextHelper.ColumnMap<Application>());
}
public void ApplicationCreate(long? mainApplicationID, long serviceInstanceID, bool isReport,
int status, DateTime statusTime, int applicationTypeID, DateTime registrationTime,
out long applicationID, out string applIdentifier, out string reportIdentifier)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_ServiceInstance_Id", OracleDbType.Int64, serviceInstanceID);
parameters.Add("p_MainApplication_Id", OracleDbType.Int64, mainApplicationID);
parameters.Add("p_Is_Report", OracleDbType.Int32, isReport);
parameters.Add("p_Status", OracleDbType.Int16, status);
parameters.Add("p_StatusTime", OracleDbType.TimeStamp, statusTime);
parameters.Add("p_ApplicationType_Id", OracleDbType.Int16, applicationTypeID);
parameters.Add("p_RegistrationTime", OracleDbType.TimeStamp, registrationTime);
parameters.Add("p_Application_Id_Out", OracleDbType.Int64, null, System.Data.ParameterDirection.Output);
parameters.Add("p_Application_Identifier_Out", OracleDbType.Varchar2, null, System.Data.ParameterDirection.Output, 100);
parameters.Add("p_Report_Identifier_Out", OracleDbType.Varchar2, null, System.Data.ParameterDirection.Output, 100);
DbConnection.SPExecute("pkg_services.p_Applications_Create", parameters);
applicationID = parameters.GetLongNumber("p_Application_Id_Out");
applIdentifier = parameters.GetString("p_Application_Identifier_Out");
reportIdentifier = parameters.GetString("p_Report_Identifier_Out");
}
public void ApplicationUpdate(long applicationID, long? mainApplicationID, long serviceInstanceID, string applIdentifier, string reportIdentifier,
int status, DateTime statusTime, int applicationTypeID, DateTime registrationTime)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_Application_Id", OracleDbType.Int64, applicationID);
parameters.Add("p_ServiceInstance_Id", OracleDbType.Int64, serviceInstanceID);
parameters.Add("p_MainApplication_Id", OracleDbType.Int64, mainApplicationID);
parameters.Add("p_ApplicationIdentifier", OracleDbType.Varchar2, applIdentifier);
parameters.Add("p_ReportIdentifier", OracleDbType.Varchar2, reportIdentifier);
parameters.Add("p_Status", OracleDbType.Int16, status);
parameters.Add("p_StatusTime", OracleDbType.TimeStamp, statusTime);
parameters.Add("p_ApplicationType_Id", OracleDbType.Int16, applicationTypeID);
parameters.Add("p_RegistrationTime", OracleDbType.TimeStamp, registrationTime);
DbConnection.SPExecute("pkg_services.p_Applications_Update", parameters);
}
public CnsysGridReader ApplicationSearch(
string applicationIDs, long? mainApplicationID, long? serviceInstanceID, string applIdentifier, string reportIdentifier,
int? status, int? applicationTypeID, int p_StartIndex, int p_PageSize, out int count)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_Application_Ids", OracleDbType.Varchar2, applicationIDs);
parameters.Add("p_ServiceInstance_Id", OracleDbType.Int64, serviceInstanceID);
parameters.Add("p_MainApplication_Id", OracleDbType.Int64, mainApplicationID);
parameters.Add("p_ApplicationIdentifier", OracleDbType.Varchar2, applIdentifier);
parameters.Add("p_ReportIdentifier", OracleDbType.Varchar2, reportIdentifier);
parameters.Add("p_Status", OracleDbType.Int16, status);
parameters.Add("p_ApplicationType_Id", OracleDbType.Int16, applicationTypeID);
parameters.Add("p_StartIndex", OracleDbType.Int32, p_StartIndex);
parameters.Add("p_PageSize", OracleDbType.Int32, p_PageSize);
parameters.Add("p_ResultsCount_out", OracleDbType.Int32, null, System.Data.ParameterDirection.Output);
parameters.Add("cv_1", OracleDbType.RefCursor, ParameterDirection.Output);
var result = DbConnection.SPExecuteReader("pkg_services.p_Applications_Search", parameters);
count = parameters.Get<OracleDecimal>("p_ResultsCount_out").ToInt32();
return result;
}
#region Service Instance
public void ServiceInstanceCreate(int officeID, int applicantCIN, out long serviceInstanceID)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_Office_Id", OracleDbType.Int32, officeID);
parameters.Add("p_Applicant_CIN", OracleDbType.Int32, applicantCIN);
parameters.Add("p_ServiceInstance_Id_Out", OracleDbType.Int32, null, System.Data.ParameterDirection.Output);
DbConnection.SPExecute("pkg_services.p_ServiceInstance_Create", parameters);
serviceInstanceID = parameters.GetLongNumber("p_ServiceInstance_Id_Out");
}
public void ServiceInstanceUpdate(long serviceInstanceID, int officeID, int applicantCIN)
{
var parameters = new OracleDynamicParameters();
parameters.Add("serviceInstanceID", OracleDbType.Int64, serviceInstanceID);
parameters.Add("p_Office_Id", OracleDbType.Int32, officeID);
parameters.Add("p_Applicant_CIN", OracleDbType.Int32, applicantCIN);
DbConnection.SPExecute("pkg_services.p_ServiceInstance_Update", parameters);
}
public CnsysGridReader ServiceInstanceSearch(string p_ServiceInstance_Ids, long? p_Office_Id, long? p_Applicant_CIN, int p_StartIndex, int p_PageSize, out int count)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_ServiceInstance_Ids", OracleDbType.Varchar2, p_ServiceInstance_Ids);
parameters.Add("p_Office_Id", OracleDbType.Int32, p_Office_Id);
parameters.Add("p_Applicant_CIN", OracleDbType.Int32, p_Applicant_CIN);
parameters.Add("p_StartIndex", OracleDbType.Int32, p_StartIndex);
parameters.Add("p_PageSize", OracleDbType.Int32, p_PageSize);
parameters.Add("p_ResultsCount_out", OracleDbType.Int32, null, System.Data.ParameterDirection.Output);
parameters.Add("cv_1", OracleDbType.RefCursor, ParameterDirection.Output);
var reader = DbConnection.SPExecuteReader("PKG_VELIN.p_ServiceInstance_Search", parameters);
count = parameters.GetIntNumber("p_ResultsCount_out");
return reader;
}
#endregion
#region Service Actions
public void ServiceActionCreate(long operationID, long serviceInstanceID, long applicationID, int applicationStatus, int actionTypeID, out long serviceActionID)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_OperationID", OracleDbType.Int64, operationID);
parameters.Add("p_ServiceInstID", OracleDbType.Int64, serviceInstanceID);
parameters.Add("p_ApplicationID", OracleDbType.Int64, applicationID);
parameters.Add("p_ApplicationStatus", OracleDbType.Int32, applicationStatus);
parameters.Add("p_ActionTypeID", OracleDbType.Int32, actionTypeID);
parameters.Add("p_ServiceActionID_out", OracleDbType.Int64, null, System.Data.ParameterDirection.Output);
DbConnection.SPExecute("pkg_velin.p_Service_Action_Create", parameters);
serviceActionID = parameters.GetLongNumber("p_ServiceActionID_out");
}
#endregion
#region Application Documents
public void ApplicationDocumentCreate(long applicationID, int documentTypeID, long documentID, out long appDocumentID)
{
var parameters = new OracleDynamicParameters();
parameters.Add("p_Application_Id", OracleDbType.Int64, applicationID);
parameters.Add("p_Document_Type", OracleDbType.Int32, documentTypeID);
parameters.Add("p_Document_Id", OracleDbType.Int64, documentID);
parameters.Add("p_App_Document_Id_Out", OracleDbType.Int64, null, System.Data.ParameterDirection.Output);
DbConnection.SPExecute("pkg_services.p_App_Documents_Create", parameters);
appDocumentID = parameters.GetLongNumber("p_App_Document_Id_Out");
}
#endregion
}
}
<file_sep>/PropertyRegister.REAU/Applications/Results/ApplicationProcessedResult.cs
using PropertyRegister.REAU.Applications.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications.Results
{
public class ApplicationProcessedResult
{
public long ApplicationID { get; set; }
public string ApplicationNumber { get; set; }
public ApplicationStatuses? ApplicationStatus { get; set; }
public decimal? PaymentAmount { get; set; }
public DateTime? PaymentDeadline { get; set; }
public string PaymentIdentifier { get; set; }
public string RegisterOutcomeNumber { get; set; }
public ICollection<string> Errors { get; set; }
}
}
<file_sep>/PropertyRegister.REAU.Test/Mocks/ServiceInstanceActionEntityMock.cs
using CNSys.Data;
using PropertyRegister.REAU.Applications.Models;
using PropertyRegister.REAU.Applications.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Test.Mocks
{
public class ServiceInstanceActionEntityMock : IServiceActionRepository
{
public bool IsReadOnly => throw new NotImplementedException();
public void Create(ServiceAction item)
{
item.ServiceActionID = new Random().Next(1, 100);
}
public void Delete(long? key)
{
throw new NotImplementedException();
}
public void Delete(ServiceAction item)
{
throw new NotImplementedException();
}
public ServiceAction Read(long? key)
{
throw new NotImplementedException();
}
public IEnumerable<ServiceAction> Search(ServiceActionSearchCriteria searchCriteria)
{
return Enumerable.Empty<ServiceAction>();
}
public IEnumerable<ServiceAction> Search(object state, ServiceActionSearchCriteria searchCriteria)
{
return Enumerable.Empty<ServiceAction>();
}
public IEnumerable<ServiceAction> Search(PagedDataState state, ServiceActionSearchCriteria searchCriteria)
{
throw new NotImplementedException();
}
public void Update(ServiceAction item)
{
throw new NotImplementedException();
}
}
}
<file_sep>/PropertyRegister.REAU.Web.Api/Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PropertyRegister.REAU.Applications;
using PropertyRegister.REAU.Nomenclatures;
using PropertyRegister.REAU.Web.Api.Test;
using Rebus.ServiceProvider;
using Serilog;
namespace PropertyRegister.REAU.Web.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services
.AddDocuments()
.AddApplicationsAcceptance()
.AddApplicationsPersistence()
.AddREAUInfrastructureServices();
// dummies ...
services.AddTransient<INomenclaturesProvider, NomenclaturesProviderDummy>();
services.AddLogging(loggingBuilder =>
{
loggingBuilder.AddSerilog(dispose: true);
});
services.AddRebusWithOracleTransport(Configuration);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UsePrincipalMiddleware();
app.UseHttpsRedirection();
app.UseRebus();
app.UseMvc();
}
}
}
<file_sep>/PropertyRegister.REAU/Domain/ApplicationServiceType.cs
using System;
namespace PropertyRegister.REAU.Domain
{
/// <summary>
/// Описание на предоставяна услуга от ИС на ПР.
/// </summary>
public class ApplicationServiceType
{
public int ApplicationTypeID { get; set; }
public string Title { get; set; }
public bool IsReport { get; set; }
public bool IsFree { get; set; }
public TimeSpan? PaymentDeadline { get; set; }
public decimal? PaymentAmount { get; set; }
/// <summary>
/// дължимата такса се заплаща след регистриране на заявлението в ИС на ИР
/// </summary>
public bool PaymentAfterRegistration { get; set; }
public string XmlNamespace { get; set; }
}
}
<file_sep>/PropertyRegister.REAU/Applications/Results/PaymentProcessedResult.cs
using PropertyRegister.REAU.Applications.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications.Results
{
public class PaymentProcessedResult
{
public ApplicationStatuses ApplicationStatus { get; set; }
public long ApplicationID { get; set; }
}
}
<file_sep>/PropertyRegister.REAU/Common/Models/DocumentData.cs
using PropertyRegister.REAU.Persistence;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Common.Models
{
/// <summary>
/// Документно съдържание + метаданни.
/// </summary>
public class DocumentData
{
[DapperColumn("document_id")]
public long? DocID { get; set; }
[DapperColumn("guid")]
public string Identifier { get; set; }
[DapperColumn("content_type")]
public string ContentType { get; set; }
[DapperColumn("filename")]
public string Filename { get; set; }
public string ContentHash { get; set; }
/// <summary>
/// Дали е наличен.
/// В процесът на заявявяне документът може да се изтрие, и само да се остави следа.
/// </summary>
public bool IsAvailable { get; set; }
[DapperColumn("is_temp")]
public bool IsTemporal { get; set; }
public Stream Content { get; set; }
}
}
<file_sep>/PropertyRegister.REAU.Test/DbAccessTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Oracle.ManagedDataAccess.Client;
using PropertyRegister.REAU.Persistence;
using System.Data;
using System.Data.Common;
using System.Linq;
namespace PropertyRegister.REAU.Test
{
[TestClass]
public class DbAccessTests
{
[TestMethod]
public void Test_Oracle_Access()
{
string connString = "Data Source=comreg;User ID=comreg_dev2;Password=<PASSWORD>;Pooling=true;HA Events=false;Connection Timeout=60";
string ProviderName = "Oracle.ManagedDataAccess.Client";
using (var con = DbProviderFactories.GetFactory(ProviderName).CreateConnection())
{
con.ConnectionString = connString;
con.Open();
// 01
var dyParam = new OracleDynamicParameters();
dyParam.Add("res", OracleDbType.RefCursor, ParameterDirection.Output);
var query = "PKG_USERS.GetAllRoles";
var reader = con.SPExecuteReader(query, dyParam);
var data = reader.Read<Role>().ToList();
// 02
query = "PKG_USERS.getuserrolesbyid";
dyParam = new OracleDynamicParameters();
dyParam.Add("puser_id", OracleDbType.Int32, 835);
dyParam.Add("res", OracleDbType.RefCursor, ParameterDirection.Output);
reader = con.SPExecuteReader(query, dyParam);
var userroles = reader.Read<UserRole>().ToList();
// 03
query = "pkg_integration_epzeu.p_indexedfields_search";
dyParam = new OracleDynamicParameters();
dyParam.Add("p_resultscount_out", OracleDbType.Int32, ParameterDirection.Output);
dyParam.Add("p_startindex", OracleDbType.Int32, 1);
dyParam.Add("p_pagesize", OracleDbType.Int32, 20);
dyParam.Add("p_uic", OracleDbType.NVarchar2, null);
dyParam.Add("p_name", OracleDbType.NVarchar2, "БЪЛГАРИЯ");
dyParam.Add("p_typeid", OracleDbType.Int32, null);
dyParam.Add("res", OracleDbType.RefCursor, ParameterDirection.Output);
reader = con.SPExecuteReader(query, dyParam);
var idxFields = reader.Read<IndexedField>().ToList();
// 04
dyParam = new OracleDynamicParameters();
dyParam.Add("res1", OracleDbType.RefCursor, ParameterDirection.Output);
dyParam.Add("res2", OracleDbType.RefCursor, ParameterDirection.Output);
query = "pkg_test_2.GetAllRoles2";
reader = con.SPExecuteReader(query, dyParam);
var roles1 = reader.Read<Role>().ToList();
var userroles1 = reader.Read<UserRole>().ToList();
}
Assert.IsTrue(true);
}
}
public class Role
{
//[DapperColumn("code")]
public string Role_name { get; set; }
}
public class UserRole
{
public int Role_ID { get; set; }
}
public class IndexedField
{
public string Name { get; set; }
}
}
<file_sep>/PropertyRegister.REAU/Applications/Models/ServiceDocument.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications.Models
{
/// <summary>
/// Документи по услуга.
/// </summary>
public class ServiceDocument
{
public long? ServiceInstanceDocumentID { get; set; }
/// <summary>
/// Заявена услуга
/// </summary>
public long ServiceInstanceID { get; set; }
/// <summary>
/// електронно издадено удостоверение за лице/имот/период;
/// сканирана резолюция на съдия по вписвания за открити нередовности в заявление за удостоверение;
/// електронен незаверен препис на документ;
/// резултат от електронна справка;
/// </summary>
public int? ServiceDocumentTypeID { get; set; }
/// <summary>
/// идентификатор/връзка към DocumentData
/// </summary>
public long DocumentID { get; set; }
}
}
<file_sep>/PropertyRegister.REAU/Applications/Models/ApplicationDocument.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyRegister.REAU.Applications.Models
{
/// <summary>
/// Документи към заявление
/// </summary>
public class ApplicationDocument
{
public long? ApplicationDocumentID { get; set; }
/// <summary>
/// идентификатор на заявление
/// </summary>
public long ApplicationID { get; set; }
/// <summary>
/// 0 - application xml
/// 1 - attached document
/// </summary>
public int? DocumentType { get; set; }
/// <summary>
/// идентификатор/връзка към DocumentData
/// </summary>
public long DocumentID { get; set; }
}
}
| 853b2dd2f4367ec04e1101e3f21687acbffd7552 | [
"C#"
] | 66 | C# | apacherose/pr.reau | eaccf443034c613d2c541ad9fdbae00ec8be951b | e6c4fce8a06b395d2e0567a60aa44062f6b2dd6c | |
refs/heads/main | <repo_name>clemiblac/ExporatoryDataAnalysis_with_SQL<file_sep>/Scripts/insert_data.sql
/* Important to pull data directory from C folder not in documents or other folders*/
COPY daly
FROM 'C:\sql_data\envdaly.csv'
DELIMITER ','
CSV HEADER;
COPY f_life_exp
FROM 'C:\sql_data\lifexfemale.csv'
DELIMITER ','
CSV HEADER;
COPY gdp
FROM 'C:\sql_data\gdpcapita.csv'
DELIMITER ','
CSV HEADER;
COPY malaria
FROM 'C:\sql_data\malaria.csv'
DELIMITER ','
CSV HEADER;
COPY transparency
FROM 'C:\sql_data\transparency.csv'
DELIMITER ','
CSV HEADER;
<file_sep>/Scripts/create_tables.sql
DROP TABLE IF EXISTS daly;
CREATE TABLE daly (
Country VARCHAR(80) PRIMARY KEY NOT NULL,
total_env_DALYs NUMERIC
);
DROP TABLE IF EXISTS gdp;
CREATE TABLE gdp (
Country VARCHAR(80) PRIMARY KEY NOT NULL,
gdp_capita NUMERIC
);
DROP TABLE IF EXISTS f_life_exp;
CREATE TABLE f_life_exp (
Country VARCHAR(80) PRIMARY KEY NOT NULL,
years NUMERIC
);
DROP TABLE IF EXISTS malaria;
CREATE TABLE malaria (
Country VARCHAR(80) PRIMARY KEY NOT NULL,
malaria_deaths NUMERIC
);
DROP TABLE IF EXISTS transparency;
CREATE TABLE transparency (
Country VARCHAR(80) PRIMARY KEY NOT NULL,
cpia NUMERIC
);
<file_sep>/README.md
# ExporatoryDataAnalysis_with_SQL
### Background
Six tables from the World Bank website and the WHO website were downloaded and cleaned for data exploration purposes.
All data is 2012 data
1. Malaria deaths
2. disability adjusted life years attributed to the environment
3. female life expectancy at birth (Years)
4. GDP per capita (current US $)
5. CPIA transparency, accountability, and corruption in the public sector rating (1=low to 6=high)
### Data Sources
The World Bank. (n.d.). The World Bank Data Bank World Development Indicators. Retrieved from The World Bank Website: https://databank.worldbank.org/source/world-development-indicators#
World Health Organization. (2016, 03 09). Burden of disease attributable to the environment. Retrieved from World Health Organization Website: https://apps.who.int/gho/data/view.main.ENVDALYSBYCOUNTRYv
World Health Organization. (2019, 02 19). Estimated number of malaria deaths (Malaria). Retrieved from World Health Organization Website: https://apps.who.int/gho/data/view.main.14119
* Female life expectancy at birth, GDP and CPIA transparency data were all retreived from The World Bank Data Bank
<file_sep>/Scripts/data_exploration.sql
select * from daly FETCH FIRST 5 ROWS ONLY;
select * from f_life_exp FETCH FIRST 5 ROWS ONLY;
select * from gdp FETCH FIRST 5 ROWS ONLY;
select * from malaria FETCH FIRST 5 ROWS ONLY;
select * from transparency FETCH FIRST 5 ROWS ONLY;
--Joining all five tables to make a single dataset and creating a table from the result
select * from
(select daly.country,daly.total_env_dalys,f_life_exp.years,gdp.gdp_capita,malaria.malaria_deaths,transparency.cpia
from daly inner join f_life_exp on daly.country=f_life_exp.country
inner join gdp on daly.country=gdp.country
inner join malaria on daly.country=malaria.country
inner join transparency on daly.country=transparency.country) as new;
COPY
(select daly.country,daly.total_env_dalys,f_life_exp.years,gdp.gdp_capita,malaria.malaria_deaths,transparency.cpia
from daly inner join f_life_exp on daly.country=f_life_exp.country
inner join gdp on daly.country=gdp.country
inner join malaria on daly.country=malaria.country
inner join transparency on daly.country=transparency.country)
TO 'C:\sql_data\new.csv' DELIMITER ',' CSV HEADER;
| 79a6bf3d2af2d7eed76e04408e0e4f4f0df6addd | [
"Markdown",
"SQL"
] | 4 | SQL | clemiblac/ExporatoryDataAnalysis_with_SQL | 8d0e1832eb3a3752d10cd26211d006a11483224f | 357b895422819ea609f36e27b6dfacf9e1487520 | |
refs/heads/master | <file_sep>import { Component, Input, OnInit } from '@angular/core';
//import { read } from 'fs';
@Component({
selector: 'app-post-list-item',
templateUrl: './post-list-item.component.html',
styleUrls: ['./post-list-item.component.scss']
})
export class PostListItemComponent implements OnInit {
@Input() postTitle: string; // 1* permet de rendre définisable la variable par le component parent html
@Input() postContent: string; // Permet de créer des propriétes personalisées
@Input() postLoveIts: number;
@Input() postCreated_at: Date;
totalLoves = 0;
onLoveIts() {
this.totalLoves++;
}
totalHates = 0;
onHateIts() {
this.totalHates++;
}
getColor() {
if(this.totalLoves == this.totalHates){
return 'black';
} else if(this.totalLoves > this.totalHates){
return 'green';
} else if (this.totalLoves < this.totalHates){
return 'red';
}
}
constructor() { }
ngOnInit() {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.scss']
})
export class PostListComponent implements OnInit {
posts = [ // 1' On crée la liste posts, qui permettra au html de créer une *ngFor
{
title: 'Post Numero 1',
content: 'Es un hecho establecido hace demasiado tiempo que un lector se distraerá con el contenido del texto de un sitio mientras que mira su diseño. El punto de usar Lorem Ipsum es que tiene una distribución más o menos normal de las letras, al contrario de usar textos como por ejemplo "Contenido aquí, contenido aquí". Estos textos hacen parecerlo un español que se puede leer. Muchos paquetes de autoedición y editores de páginas web usan el Lorem Ipsum como su texto por defecto, y al hacer una búsqueda de "Lorem Ipsum" va a dar por resultado muchos sitios web que usan este texto si se encuentran en estado de desarrollo. Muchas versiones han evolucionado a través de los años, algunas veces por accidente, otras veces a propósito (por ejemplo insertándole humor y cosas por el estilo).',
loveIts: 0,
created_at: new Date()
},
{
title: 'Post Numero 2',
content: 'Es un hecho establecido hace demasiado tiempo que un lector se distraerá con el contenido del texto de un sitio mientras que mira su diseño. El punto de usar Lorem Ipsum es que tiene una distribución más o menos normal de las letras, al contrario de usar textos como por ejemplo "Contenido aquí, contenido aquí". Estos textos hacen parecerlo un español que se puede leer. Muchos paquetes de autoedición y editores de páginas web usan el Lorem Ipsum como su texto por defecto, y al hacer una búsqueda de "Lorem Ipsum" va a dar por resultado muchos sitios web que usan este texto si se encuentran en estado de desarrollo. Muchas versiones han evolucionado a través de los años, algunas veces por accidente, otras veces a propósito (por ejemplo insertándole humor y cosas por el estilo).',
loveIts: 0,
created_at: new Date()
},
{
title: 'Post Numero 3',
content: 'Es un hecho establecido hace demasiado tiempo que un lector se distraerá con el contenido del texto de un sitio mientras que mira su diseño. El punto de usar Lorem Ipsum es que tiene una distribución más o menos normal de las letras, al contrario de usar textos como por ejemplo "Contenido aquí, contenido aquí". Estos textos hacen parecerlo un español que se puede leer. Muchos paquetes de autoedición y editores de páginas web usan el Lorem Ipsum como su texto por defecto, y al hacer una búsqueda de "Lorem Ipsum" va a dar por resultado muchos sitios web que usan este texto si se encuentran en estado de desarrollo. Muchas versiones han evolucionado a través de los años, algunas veces por accidente, otras veces a propósito (por ejemplo insertándole humor y cosas por el estilo).',
loveIts: 0,
created_at: new Date()
}
];
constructor() { }
ngOnInit() {
}
}
| 9d5fde3ff34c1b917ef62b0f9e81276f4412f198 | [
"TypeScript"
] | 2 | TypeScript | OttoCHWADAGIANI/blog_angular | 3488677abd3b671b579a513ee7aaa3758f3acdcb | 2b26ae63f428d79802af6a0e6c5fdf7d7eecd5cd | |
refs/heads/master | <repo_name>emittam/PamphletMaker<file_sep>/app/src/main/java/net/emittam/pamphletmaker/utils/BindingUtils.java
package net.emittam.pamphletmaker.utils;
import android.databinding.BindingAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import net.emittam.pamphletmaker.R;
/**
* Created by kato-h on 16/11/26.
*/
public class BindingUtils {
@BindingAdapter({"imageUrl"})
public static void loadImage(ImageView view, String url) {
Picasso.with(view.getContext()).load(url).placeholder(R.drawable.noimage).resize(480, 270).centerInside().into(view);
}
}
<file_sep>/app/src/main/java/net/emittam/pamphletmaker/ImageCollectBroadcastReceiver.java
package net.emittam.pamphletmaker;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.util.HashSet;
import java.util.Set;
/**
* Created by kato-h on 16/11/26.
*/
public class ImageCollectBroadcastReceiver extends BroadcastReceiver {
private static final String NEW_PHOTO_ACTION = "android.hardware.action.NEW_PICTURE";
public static final String SAVE_IMAGE_URL_KEY = "image.url.set";
public static final String SAVE_FILE_PATH_KEY = "save.filepath.key";
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(context);
String saveKey = defaultPref.getString(SAVE_FILE_PATH_KEY, null);
int permissionCheck = ContextCompat.checkSelfPermission(
context,
Manifest.permission.READ_EXTERNAL_STORAGE
);
if (intent.getAction().equals(NEW_PHOTO_ACTION)
&& saveKey != null
&& android.content.pm.PackageManager.PERMISSION_GRANTED == permissionCheck) {
SharedPreferences prefs = context.getSharedPreferences(saveKey, Context.MODE_PRIVATE);
Set<String> savedSet = prefs.getStringSet(SAVE_IMAGE_URL_KEY, new HashSet<String>());
savedSet = new HashSet<>(savedSet);
String[] CONTENT_PROJECTION = {
MediaStore.Images.Media.DATA,
};
Cursor c = context.getContentResolver().query(intent.getData(), CONTENT_PROJECTION, null, null, null);
if (c == null || !c.moveToFirst()) {
if (c != null) {
c.close();
}
}
String localPath = c.getString(c.getColumnIndex(MediaStore.Images.Media.DATA));
c.close();
String url = "file://" + localPath;
if (!savedSet.contains(url)) {
savedSet.add(url);
}
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(SAVE_IMAGE_URL_KEY, savedSet);
editor.commit();
}
}
}
<file_sep>/app/src/main/java/net/emittam/pamphletmaker/PamphletViewerActivity.java
package net.emittam.pamphletmaker;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.Toast;
/**
* Created by kato-h on 16/11/26.
*/
public class PamphletViewerActivity extends AppCompatActivity {
// X軸最低スワイプ距離
private static final int SWIPE_MIN_DISTANCE = 50;
// X軸最低スワイプスピード
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
// Y軸の移動距離 これ以上なら横移動を判定しない
private static final int SWIPE_MAX_OFF_PATH = 250;
private GestureDetector mGestureDetector;
private int mCurrentPage = 0;
private String mKey;
private String mText;
public static void startActivity(Activity base, String key, String text) {
Intent intent = new Intent(base, PamphletViewerActivity.class);
intent.putExtra("key", key);
intent.putExtra("text", text);
base.startActivity(intent);
}
private static final int NOTIFICATION_ID = 998;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("パンフレット");
setContentView(R.layout.activity_pamphlet_viewer);
mKey = getIntent().getStringExtra("key");
mText = getIntent().getStringExtra("text");
LeftPamphletViewerFragment fragment = LeftPamphletViewerFragment.createInstance(mCurrentPage);
LeftPamphletViewerModel model = ImageRepository.getInstance(getApplicationContext(), mKey).getLeftModel(mCurrentPage);
model.setText(mText);
fragment.setViewModel(model);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.pamphlet_fragment, fragment);
transaction.commit();
mGestureDetector = new GestureDetector(this, mOnGestureListener);
NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
manager.cancel(NOTIFICATION_ID);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
private final GestureDetector.SimpleOnGestureListener mOnGestureListener = new GestureDetector.SimpleOnGestureListener() {
// フリックイベント
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
Log.d("debug", "onFling");
try {
float distance_x = Math.abs((event1.getX() - event2.getX()));
float velocity_x = Math.abs(velocityX);
// Y軸の移動距離が大きすぎる場合
if (Math.abs(event1.getY() - event2.getY()) > SWIPE_MAX_OFF_PATH) {
}
// 開始位置から終了位置の移動距離が指定値より大きい
// X軸の移動速度が指定値より大きい
else if (event1.getX() - event2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//Toast.makeText(PamphletViewerActivity.this, "左から右", Toast.LENGTH_SHORT).show();
if (mCurrentPage >= 0) {
mCurrentPage--;
LeftPamphletViewerFragment fragment = LeftPamphletViewerFragment.createInstance(mCurrentPage);
LeftPamphletViewerModel model = ImageRepository.getInstance(getApplicationContext(), mKey).getLeftModel(mCurrentPage);
model.setText(mText);
fragment.setViewModel(model);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pamphlet_fragment, fragment);
transaction.commit();
}
}
// 終了位置から開始位置の移動距離が指定値より大きい
// X軸の移動速度が指定値より大きい
else if (event2.getX() - event1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//Toast.makeText(PamphletViewerActivity.this, "右から左", Toast.LENGTH_SHORT).show();
if (mCurrentPage < ImageRepository.getInstance(getApplicationContext(), mKey).getImageCount() / 2) {
mCurrentPage++;
LeftPamphletViewerFragment fragment = LeftPamphletViewerFragment.createInstance(mCurrentPage);
LeftPamphletViewerModel model = ImageRepository.getInstance(getApplicationContext(), mKey).getLeftModel(mCurrentPage);
model.setText(mText);
fragment.setViewModel(model);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pamphlet_fragment, fragment);
transaction.commit();
}
}
} catch (Exception e) {
// TODO
}
return false;
}
};
}
<file_sep>/app/src/main/java/net/emittam/pamphletmaker/MainActivity.java
package net.emittam.pamphletmaker;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.databinding.BaseObservable;
import android.databinding.DataBindingUtil;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import net.emittam.pamphletmaker.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
public class MainPresenter extends BaseObservable {
public void onButtonClick() {
// SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// SharedPreferences.Editor editor = defaultPref.edit();
// editor.putString(ImageCollectBroadcastReceiver.SAVE_FILE_PATH_KEY, "test2");
// editor.commit();
// Toast.makeText(MainActivity.this, "好きなカメラアプリで写真を撮ってください", Toast.LENGTH_LONG).show();
// finish();
SelectorActivity.startActivity(MainActivity.this, false);
}
public void onTestButtonClick() {
SelectorActivity.startActivity(MainActivity.this, true);
}
}
private MainPresenter mMainPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("パンフレットメーカー");
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
mMainPresenter = new MainPresenter();
binding.setPresenter(mMainPresenter);
}
}
| fc36ff1f8b83d11617a8d5a4145d9b430bc5ba0a | [
"Java"
] | 4 | Java | emittam/PamphletMaker | 6918ef7a859b14086e3da04362fc5a20db478aef | f029d44e85c44b34d27cec8f9da243141743093f | |
refs/heads/main | <file_sep>-- phpMyAdmin SQL Dump
-- version 5.2.0
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Jul 13, 2022 at 05:25 PM
-- Server version: 10.4.21-MariaDB
-- PHP Version: 7.4.29
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: `antrian`
--
-- --------------------------------------------------------
--
-- Table structure for table `antrian`
--
CREATE TABLE `antrian` (
`id` int(11) NOT NULL,
`tanggal` varchar(50) DEFAULT NULL,
`status` varchar(50) NOT NULL,
`waktu_panggil` varchar(50) DEFAULT current_timestamp(),
`waktu_selesai` varchar(50) DEFAULT NULL,
`pelayanan_id` int(11) NOT NULL,
`loket_id` int(11) NOT NULL,
`antrian_last` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT;
--
-- Dumping data for table `antrian`
--
INSERT INTO `antrian` (`id`, `tanggal`, `status`, `waktu_panggil`, `waktu_selesai`, `pelayanan_id`, `loket_id`, `antrian_last`) VALUES
(1, '22-07-06 08:16:25', 'selesai', NULL, NULL, 4, 1, NULL),
(2, '22-07-06 08:28:44', 'selesai', NULL, NULL, 4, 1, NULL),
(3, '22-07-06 08:28:45', 'selesai', NULL, NULL, 4, 1, NULL),
(4, '22-07-06 08:28:45', 'selesai', NULL, NULL, 4, 1, NULL),
(5, '22-07-06 08:28:46', 'selesai', NULL, NULL, 4, 1, NULL),
(6, '22-07-06 08:28:47', 'selesai', NULL, NULL, 4, 1, NULL),
(7, '22-07-06 08:28:48', 'selesai', NULL, NULL, 5, 1, NULL),
(8, '22-07-06 08:28:50', 'selesai', NULL, NULL, 5, 1, NULL),
(9, '22-07-06 08:28:50', 'selesai', NULL, NULL, 5, 1, NULL),
(10, '22-07-06 08:28:52', 'selesai', NULL, NULL, 6, 1, NULL),
(11, '22-07-06 08:28:54', 'selesai', NULL, NULL, 6, 1, NULL),
(12, '22-07-06 08:28:56', 'selesai', NULL, NULL, 7, 1, NULL),
(13, '22-07-06 08:28:57', 'selesai', NULL, NULL, 7, 1, NULL),
(14, '22-07-06 09:15:24', 'selesai', NULL, NULL, 4, 1, NULL),
(15, '22-07-06 10:29:15', 'selesai', NULL, NULL, 7, 1, NULL),
(16, '22-07-06 10:29:44', 'selesai', NULL, NULL, 7, 1, NULL),
(17, '22-07-06 10:30:19', 'selesai', NULL, NULL, 4, 1, NULL),
(18, '22-07-06 10:31:28', 'selesai', NULL, NULL, 4, 1, NULL),
(19, '22-07-06 10:31:29', 'selesai', NULL, NULL, 4, 1, NULL),
(20, '22-07-06 10:31:30', 'selesai', NULL, NULL, 4, 1, NULL),
(21, '22-07-06 10:58:00', 'selesai', NULL, NULL, 6, 1, NULL),
(22, '22-07-06 10:58:01', 'selesai', NULL, NULL, 6, 1, NULL),
(23, '22-07-06 10:58:02', 'selesai', NULL, NULL, 6, 1, NULL),
(24, '22-07-06 10:58:04', 'selesai', NULL, NULL, 7, 1, NULL),
(25, '22-07-06 11:00:53', 'selesai', NULL, NULL, 4, 1, NULL),
(26, '22-07-06 11:02:22', 'selesai', NULL, NULL, 4, 1, NULL),
(27, '22-07-06 11:02:40', 'selesai', NULL, NULL, 4, 1, NULL),
(28, '22-07-06 11:03:17', 'selesai', NULL, NULL, 4, 1, NULL),
(29, '22-07-06 11:03:27', 'selesai', NULL, NULL, 4, 1, NULL),
(30, '22-07-06 11:03:32', 'selesai', NULL, NULL, 5, 1, NULL),
(31, '22-07-06 11:31:40', 'selesai', NULL, NULL, 4, 1, NULL),
(32, '22-07-06 11:32:59', 'selesai', NULL, NULL, 5, 1, NULL),
(33, '22-07-06 21:54:52', 'selesai', NULL, NULL, 4, 1, NULL),
(34, '22-07-06 21:57:11', 'selesai', NULL, NULL, 5, 1, NULL),
(35, '22-07-06 21:57:15', 'selesai', NULL, NULL, 6, 1, NULL),
(36, '22-07-06 21:57:18', 'berlansung', NULL, NULL, 7, 1, NULL),
(37, '22-07-06 21:57:27', 'selesai', NULL, NULL, 4, 1, NULL),
(38, '22-07-06 21:57:30', 'selesai', NULL, NULL, 4, 1, NULL),
(39, '22-07-06 21:57:33', 'selesai', NULL, NULL, 4, 1, NULL),
(40, '22-07-06 22:26:02', 'selesai', NULL, NULL, 4, 1, NULL),
(41, '22-07-06 22:38:01', 'selesai', NULL, NULL, 4, 1, NULL),
(42, '22-07-07 02:18:42', 'selesai', NULL, NULL, 4, 1, NULL),
(43, '22-07-07 02:18:45', 'selesai', NULL, NULL, 4, 1, NULL),
(44, '22-07-07 02:19:22', 'selesai', NULL, NULL, 4, 1, NULL),
(45, '22-07-07 02:19:25', 'selesai', NULL, NULL, 4, 1, NULL),
(46, '22-07-07 02:19:27', 'selesai', NULL, NULL, 4, 1, NULL),
(47, '22-07-07 02:19:30', 'selesai', NULL, NULL, 4, 1, NULL),
(48, '22-07-07 02:22:47', 'selesai', NULL, NULL, 4, 1, NULL),
(49, '22-07-07 02:23:18', 'selesai', NULL, NULL, 4, 1, NULL),
(50, '22-07-07 04:23:08', 'selesai', NULL, NULL, 4, 1, NULL),
(51, '22-07-07 04:23:08', 'selesai', NULL, NULL, 4, 1, NULL),
(52, '22-07-07 05:25:43', 'selesai', NULL, NULL, 4, 1, NULL),
(53, '22-07-07 05:25:43', 'selesai', NULL, NULL, 4, 1, NULL),
(54, '22-07-07 05:39:27', 'selesai', NULL, NULL, 4, 1, NULL),
(55, '22-07-07 05:39:27', 'selesai', NULL, NULL, 4, 1, NULL),
(56, '22-07-07 05:44:05', 'berlansung', NULL, NULL, 5, 1, NULL),
(57, '22-07-07 05:44:05', 'mengantri', NULL, NULL, 5, 1, NULL),
(58, '22-07-07 05:46:43', 'mengantri', NULL, NULL, 5, 1, NULL),
(59, '22-07-07 05:46:43', 'mengantri', NULL, NULL, 5, 1, NULL),
(60, '22-07-07 08:07:04', 'selesai', NULL, NULL, 4, 1, NULL),
(61, '22-07-07 08:07:04', 'selesai', NULL, NULL, 4, 1, NULL),
(62, '22-07-08 01:49:22', 'selesai', NULL, NULL, 4, 1, NULL),
(63, '22-07-08 01:49:22', 'selesai', NULL, NULL, 4, 1, NULL),
(64, '22-07-08 07:33:06', 'selesai', NULL, NULL, 4, 1, NULL),
(65, '22-07-08 07:33:06', 'selesai', NULL, NULL, 4, 1, NULL),
(66, '22-07-08 07:49:14', 'selesai', NULL, NULL, 4, 1, NULL),
(67, '22-07-08 07:49:14', 'selesai', NULL, NULL, 4, 1, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `loket`
--
CREATE TABLE `loket` (
`id` int(11) NOT NULL,
`nama` varchar(100) NOT NULL,
`keterangan` tinytext NOT NULL,
`pelayanan_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `loket`
--
INSERT INTO `loket` (`id`, `nama`, `keterangan`, `pelayanan_id`) VALUES
(2, 'Loket 1', 'Pelayanan Customer Services', 0),
(3, 'Loket 2', 'Pelayanan Pengaduan', 5),
(4, 'Loket 3', 'Pelayanan Permohonan Baru', 6),
(5, 'Loket 4', 'Pelayanan Perpanjangan', 0);
-- --------------------------------------------------------
--
-- Table structure for table `pelayanan`
--
CREATE TABLE `pelayanan` (
`id` int(11) UNSIGNED NOT NULL,
`nama` varchar(100) NOT NULL,
`kode` varchar(100) NOT NULL,
`keterangan` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `pelayanan`
--
INSERT INTO `pelayanan` (`id`, `nama`, `kode`, `keterangan`) VALUES
(4, 'Customer Services', 'A', 'Layanan konsumen'),
(5, 'Pengaduan', 'B', 'Layanan pengaduan'),
(6, 'Permohonan Baru', 'C', 'Layanan permohonan baru'),
(7, 'Perpanjangan', 'D', 'Layanan Perpanjangan');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `antrian`
--
ALTER TABLE `antrian`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `loket`
--
ALTER TABLE `loket`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `pelayanan`
--
ALTER TABLE `pelayanan`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `antrian`
--
ALTER TABLE `antrian`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=68;
--
-- AUTO_INCREMENT for table `loket`
--
ALTER TABLE `loket`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT for table `pelayanan`
--
ALTER TABLE `pelayanan`
MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;
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><?= $this->extend('/layouts/tempelate-admin'); ?>
<?= $this->section('content'); ?>
<div class="container">
<?php
if (!empty(session()->getFlashdata('success'))) { ?>
<div class="alert alert-success">
<?php echo session()->getFlashdata('success'); ?> </div>
<?php } ?> <?php if (!empty(session()->getFlashdata('info'))) { ?>
<div class="alert alert-info"> <?php echo session()->getFlashdata('info'); ?>
</div> <?php } ?>
<?php if (!empty(session()->getFlashdata('warning'))) { ?>
<div class="alert alert-warning"> <?php echo session()->getFlashdata('warning'); ?>
</div>
<?php } ?>
<?php if (!empty(session()->getFlashdata('danger'))) { ?>
<div class="alert alert-danger"> <?php echo session()->getFlashdata('danger'); ?>
</div>
<?php } ?>
</div>
<div class="container">
<a href="
<?php echo base_url();?>/pelayanan/create" class="btn btn-success float-right mb-3">Tambah Pelayanan </a>
<h4>Pelayanan</h4>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<th>No</th>
<th>Name</th>
<th>Kode</th>
<th>Keterangan</th>
<th>Aksi</th>
</thead>
<tbody>
<?php foreach ($pelayanan as $key => $data) { ?>
<tr>
<td> <?php echo $key + 1; ?> </td>
<td> <?php echo $data['nama']; ?> </td>
<td> <?php echo $data['kode']; ?> </td>
<td> <?php echo $data['keterangan']; ?> </td>
<td>
<div class="btn-group">
<a href="<?php echo base_url('pelayanan/edit/' . $data['id']); ?>" class="btn btn-warning btn-sm">
<i class="fas fa-edit"></i>
</a>   <a href="<?php echo base_url('pelayanan/delete/' . $data['id']); ?>" class="btn btn-danger btn-sm" onclick="return confirm('Apakah Anda yakin ingin menghapus pelayanan <?php echo $data['nama']; ?> ini?')">
<i class="fas fa-trash-alt"></i>
</a>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<?= $this->endSection(); ?><file_sep>
//check localstorage
if(localStorage.getItem('preferredTheme') == 'dark') {
setDarkMode(true)
}
function setDarkMode(isDark) {
var darkBtn = document.getElementById('darkBtn')
var lightBtn = document.getElementById('lightBtn')
if(isDark) {
lightBtn.style.display = "block"
darkBtn.style.display = "none"
localStorage.setItem('preferredTheme', 'dark');
} else {
lightBtn.style.display = "none"
darkBtn.style.display = "block"
localStorage.removeItem('preferredTheme');
}
document.body.classList.toggle("darkmode");
}<file_sep><?php namespace App\Models;
use CodeIgniter\Model;
class LoketModel extends Model
{
protected $table = "loket";
public function getLoket($id = false)
{
if($id === false){
return $this->table('loket')
->get()
->getResultArray();
} else {
return $this->table('loket')
->where('id', $id)
->get()
->getRowArray();
}
}
public function insert_loket($data)
{
return $this->db->table($this->table)->insert($data);
}
public function update_loket($data, $id)
{
return $this->db->table($this->table)->update($data, ['id' => $id]);
}
public function delete_loket($id)
{
return $this->db->table($this->table)->delete(['id' => $id]);
}
}<file_sep><?php foreach ($antrian4 as $key => $data4) {
$aa = $data4["id"];
} ?>
<?php foreach ($antrian5 as $key => $data5) {
$bb = $data5["id"];
} ?>
<?php foreach ($antrian6 as $key => $data6) {
$cc = $data6["id"];
} ?>
<?php foreach ($antrian7 as $key => $data7) {
$dd = $data7["id"];
} ?>
<?= $this->extend('layouts/tempelate'); ?>
<?= $this->section('content'); ?>
<!-- Begin Page Content -->
<div class="container">
<div class="card-body">
<div class="row">
<!-- Page Heading -->
<div class="col-12"> Dashboard Antrian </div>
<div class="antrian">
<h5>Panggilan Antrian</h5>
<p> A <?php echo $aa; ?> </p>
<h5>Loket 1</h5>
</div>
<div class="antrian-layar">
<p id="time"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var timestamp = '<?= time(); ?>';
function updateTime() {
$('#time').html(Date(timestamp));
timestamp++;
}
$(function() {
setInterval(updateTime, 1000);
});
</script>
<tr>
<marquee behavior="" direction="">
<td>
<h2>Antrian saat ini : Loket 1 : A <?php echo $aa; ?>, Loket 2 : B <?php echo $bb; ?>, Loket 3 : C <?php echo $cc; ?>, Loket 4 : D <?php echo $dd; ?> </h2>
</td>
</marquee>
<td><img width="200" src="https://c.tenor.com/kvXMS__Bkd8AAAAC/hello-hi.gif" alt=""></td>
</tr>
</div>
<br>
<!-- <div class="antrian"><h5><NAME></h5><p>A03</p><h5>Loket 1</h5></div> -->
<br>
<div class="loket">
<p>A <?php echo $aa; ?> </p>
<h5>Loket 1</h5>
</div>
<div class="loket">
<p>B <?php echo $bb; ?> </p>
<h5>Loket 2</h5>
</div>
<div class="loket">
<p>C <?php echo $cc; ?> </p>
<h5>Loket 3</h5>
</div>
<div class="loket">
<p>D <?php echo $dd; ?> </p>
<h5>Loket 4</h5>
</div>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<?= $this->endSection(); ?><file_sep><?php foreach ($antrianlast as $key => $data40) {
echo $data40["id"];
}
<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.0">
<!-- My Style -->
<link href="<?php echo base_url('assets/css/style.css'); ?> " rel="stylesheet">
<!-- BOOTSTRAP /-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" />
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<title><?= $title; ?> - Sistem Antrian</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light mb-5">
<div class="container">
<a class="navbar-brand" href="#">
<i class="fa-solid fa-clock"></i>
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link" href="<?php base_url(); ?>antrian">Ambil antrian</a>
<a class="nav-link" href="<?php base_url(); ?>antrianno">Layar antrian</a>
<a class="nav-link" href="<?php base_url(); ?>loketpanggil">Loket Panggil</a>
<a class="nav-link" href="<?php base_url(); ?>loket">Loket</a>
<a class="nav-link" href="<?php base_url(); ?>pelayanan">Pelayanan</a>
</div>
</div>
</div>
</nav>
<?= $this->renderSection('content'); ?>
<footer class="footer mt-5 py-3 text-center">
<div class="container">
<span>
<p><i class="fa-solid fa-smile"></i> TERIMAKASIH <i class="fa-solid fa-smile"></i></p>
<i class="fa-solid fa-heart"></i> LYDIA DIFFANI <i class="fa-solid fa-heart"></i></p>
<p>© <script>
document.write(new Date().getFullYear());
</script>
</p>
</span>
</div>
</footer>
<script src="assets/js/main.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep><?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\AntrianModel;
class Antrianno extends Controller
{
public function __construct()
{
// Mendeklarasikan class AntrianModel menggunakan $this->antrian
$this->antrian = new AntrianModel();
}
public function index()
{
$data = [
'title' => 'Layar Antrian'
];
$data['antrian4'] = $this->antrian->getAntrianno(4);
$data['antrian5'] = $this->antrian->getAntrianno(5);
$data['antrian6'] = $this->antrian->getAntrianno(6);
$data['antrian7'] = $this->antrian->getAntrianno(7);
$data['antrianlast'] = $this->antrian->getAntrianlast(7);
echo view('pages/antrianno/index', $data);
}
public function edite()
{
$data = [
'title' => 'Edit'
];
$data['antrian4'] = $this->antrian->getAntrianno(4);
$data['antrian5'] = $this->antrian->getAntrianno(5);
$data['antrian6'] = $this->antrian->getAntrianno(6);
$data['antrian7'] = $this->antrian->getAntrianno(1);
echo view('antrian/edit2', $data);
}
public function cek()
{
$data = [
'title' => 'Cek'
];
$data['antrianlast'] = $this->antrian->getAntrianlast(7);
echo view('antrian/cek', $data);
}
}
<file_sep><?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\AntrianModel;
class Antrian extends Controller
{
public function __construct()
{
// Mendeklarasikan class AntrianModel menggunakan $this->antrian
$this->antrian = new AntrianModel();
}
public function index()
{
$data = [
'title' => 'Ambil Antrian'
];
return view('pages/antrian/index', $data);
}
public function edite()
{
$data['antrian'] = $this->antrian->getAntrian();
echo view('pages/antrian/edit2', $data);
}
public function a()
{
// Mengambil value dari form dengan method POST
$oke = date('y-m-d H:i:s');
// Membuat array collection yang disiapkan untuk insert ke tablehttps://codeigniter.com/user_guide/database/index.html
$data = [
'tanggal' => $oke,
'status' => 'mengantri',
'waktu_panggil' => null,
'waktu_selesai' => null,
'pelayanan_id' => '4',
'loket_id' => '1'
];
$dataaa = [
'tanggal' => $oke,
'status' => 'berlansung',
'waktu_panggil' => null,
'waktu_selesai' => null,
'pelayanan_id' => '4',
'loket_id' => '1'
];
$dataa['antrianstatus'] = $this->antrian->getAntrianstatus('4');
if ($dataa['antrianstatus'] != null) {
$simpan = $this->antrian->insert_antrian($data);
} else {
$simpan = $this->antrian->insert_antrian($dataaa);
}
// Jika simpan berhasil, maka ...
if ($simpan) {
// Deklarasikan session flashdata dengan tipe success
session()->setFlashdata('success', 'Anda telah melakukan pengambilan no antrian, no antrian anda adalah $last_id');
$data['antrian'] = $this->antrian->getAntrian();
echo view('pages/antrian/antrian', $data);
}
}
public function b()
{
// Mengambil value dari form dengan method POST
$oke = date('y-m-d H:i:s');
// Membuat array collection yang disiapkan untuk insert ke table
$data = [
'tanggal' => $oke,
'status' => 'mengantri',
'waktu_panggil' => null,
'waktu_selesai' => null,
'pelayanan_id' => '5',
'loket_id' => '1'
];
$dataaa = [
'tanggal' => $oke,
'status' => 'berlansung',
'waktu_panggil' => null,
'waktu_selesai' => null,
'pelayanan_id' => '5',
'loket_id' => '1'
];
$dataa['antrianstatus'] = $this->antrian->getAntrianstatus('5');
if ($dataa['antrianstatus'] != null) {
$simpan = $this->antrian->insert_antrian($data);
} else {
$simpan = $this->antrian->insert_antrian($dataaa);
}
// Jika simpan berhasil, maka ...
if ($simpan) {
// Deklarasikan session flashdata dengan tipe success
session()->setFlashdata('success', 'Anda telah melakukan pengambilan no antrian, no antrian anda adalah $last_id');
$data['antrian'] = $this->antrian->getAntrian();
echo view('pages/antrian/antrian', $data);
}
}
public function c()
{
// Mengambil value dari form dengan method POST
$oke = date('y-m-d H:i:s');
// Membuat array collection yang disiapkan untuk insert ke table
$data = [
'tanggal' => $oke,
'status' => 'mengantri',
'waktu_panggil' => null,
'waktu_selesai' => null,
'pelayanan_id' => '6',
'loket_id' => '1'
];
$dataaa = [
'tanggal' => $oke,
'status' => 'berlansung',
'waktu_panggil' => null,
'waktu_selesai' => null,
'pelayanan_id' => '6',
'loket_id' => '1'
];
$dataa['antrianstatus'] = $this->antrian->getAntrianstatus('6');
if ($dataa['antrianstatus'] != null) {
$simpan = $this->antrian->insert_antrian($data);
} else {
$simpan = $this->antrian->insert_antrian($dataaa);
}
// Jika simpan berhasil, maka ...
if ($simpan) {
// Deklarasikan session flashdata dengan tipe success
session()->setFlashdata('success', 'Anda telah melakukan pengambilan no antrian, no antrian anda adalah $last_id');
$data['antrian'] = $this->antrian->getAntrian();
echo view('pages/antrian/antrian', $data);
}
}
public function d()
{
// Mengambil value dari form dengan method POST
$oke = date('y-m-d H:i:s');
// Membuat array collection yang disiapkan untuk insert ke table
$data = [
'tanggal' => $oke,
'status' => 'mengantri',
'waktu_panggil' => null,
'waktu_selesai' => null,
'pelayanan_id' => '7',
'loket_id' => '1'
];
$dataaa = [
'tanggal' => $oke,
'status' => 'berlansung',
'waktu_panggil' => null,
'waktu_selesai' => null,
'pelayanan_id' => '7',
'loket_id' => '1'
];
$dataa['antrianstatus'] = $this->antrian->getAntrianstatus('7');
if ($dataa['antrianstatus'] != null) {
$simpan = $this->antrian->insert_antrian($data);
} else {
$simpan = $this->antrian->insert_antrian($dataaa);
}
// Jika simpan berhasil, maka ...
if ($simpan) {
// Deklarasikan session flashdata dengan tipe success
session()->setFlashdata('success', 'Anda telah melakukan pengambilan no antrian, no antrian anda adalah $last_id');
$data['antrian'] = $this->antrian->getAntrian();
echo view('pages/antrian/antrian', $data);
}
}
}
<file_sep><?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\LoketModel;
use App\Models\PelayananModel;
class Loket extends Controller
{
public function __construct()
{
// Mendeklarasikan class LoketModel menggunakan $this->loket
$this->loket = new LoketModel();
$this->pelayanan = new PelayananModel();
}
public function index()
{
$data = [
'title' => 'Loket'
];
$data['loket'] = $this->loket->getLoket();
echo view('admin/loket/index', $data);
}
public function edit($id)
{
$data = [
'title' => 'Edit Loket'
];
// Memanggil function getLoket($id) dengan parameter $id di dalam LoketModel dan menampungnya di variabel array loket
$data['loket'] = $this->loket->getLoket($id);
$data['pelayanan'] = $this->pelayanan->getPelayanan();
// Mengirim data ke dalam view
return view('admin/loket/edit', $data);
}
public function create()
{
$data = [
'title' => 'Tambah Loket'
];
$data['pelayanan'] = $this->pelayanan->getPelayanan();
return view('admin/loket/create', $data);
}
public function delete($id)
{
// Memanggil function delete() dengan parameter $id di dalam LoketModel dan menampungnya di variabel hapus
$hapus = $this->loket->delete_loket($id);
// Jika berhasil melakukan hapus
if ($hapus) {
// Deklarasikan session flashdata dengan tipe warning
session()->setFlashdata('danger', 'Hapus Loket berhasil!');
// Redirect
return redirect()->to(base_url('loket'));
}
}
public function update($id)
{
// Mengambil value dari form dengan method POST
$name = $this->request->getPost('nama');
$code = $this->request->getPost('pelayanan_id');
$desc = $this->request->getPost('keterangan');
// Membuat array collection yang disiapkan untuk insert ke table
$data = [
'nama' => $name,
'keterangan' => $desc,
'pelayanan_id' => $code
];
/*
Membuat variabel ubah yang isinya merupakan memanggil function
update_loket dan membawa parameter data beserta id
*/
$ubah = $this->loket->update_loket($data, $id);
// Jika berhasil melakukan ubah
if ($ubah) {
// Deklarasikan session flashdata dengan tipe info
session()->setFlashdata('warning', 'Updated loket berhasil!');
// Redirect ke halaman loket
return redirect()->to(base_url('loket'));
}
}
public function store()
{
// Mengambil value dari form dengan method POST
$name = $this->request->getPost('nama');
$desc = $this->request->getPost('keterangan');
$code = $this->request->getPost('pelayanan_id');
// Membuat array collection yang disiapkan untuk insert ke table
$data = [
'nama' => $name,
'keterangan' => $desc,
'pelayanan_id' => $code
];
/*
Membuat variabel simpan yang isinya merupakan memanggil function
insert_loket dan membawa parameter data
*/
$simpan = $this->loket->insert_loket($data);
// Jika simpan berhasil, maka ...
if ($simpan) {
// Deklarasikan session flashdata dengan tipe success
session()->setFlashdata('success', 'Tambah Loket berhasil!');
// Redirect halaman ke loket
return redirect()->to(base_url('loket'));
}
}
function action()
{
$data['loket'] = $this->loket->getLoket();
echo json_encode($data);
}
}
<file_sep><?= $this->extend('/layouts/tempelate'); ?>
<?= $this->section('content'); ?>
<div class="container">
<main>
<section class="mb-4">
<div class="container">
<div class="hero-inner">
<div class="hero-copy">
<div class="card text-center bg-light">
<div class="card-body bg-warning">
<h1 style="text-align: center;">Menu Antrian</h1>
</div>
</div>
</div>
</div>
</div>
</section>
<div class="container">
<div class="row row-cols-1 row-cols-md-2">
<?php foreach ($pelayanan->getResultArray() as $row) : ?>
<div class="col mb-4">
<div class="card bg-primary mb-3">
<a style="color:white; text-decoration:none; text-align:center;" href="
<?php echo base_url(); ?>/antrian/<?= $row['kode']; ?>/<?= $row['id']; ?>">
<div class="card-body" style="text-align: center; font-weight: bold;"></div>
<div class="card-body">
<h1 class="card-title"><?= $row['nama']; ?></h1>
</div>
<div class="card-body" style="text-align: center; font-weight: bold;"></div>
</a>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</main>
<?= $this->endSection(); ?><file_sep><?= $this->extend('/layouts/tempelate'); ?>
<?= $this->section('content'); ?>
<div class="container">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQn2fooM3tyt2t_WmQ3r42h4JMHxZWCLT2NDw&usqp=CAU" height="180px"
align="right" border="5">
<h1>SELAMAT DATANG DI COFFEE SHOP!</h1>
<p>Silahkan mengambil antrian</p>
</div>
<?= $this->endSection(); ?><file_sep><?php namespace App\Models;
use CodeIgniter\Model;
class PelayananModel extends Model
{
protected $table = "pelayanan";
protected $primaryKey = 'id';
protected $allowedFields = ['id','nama', 'kode', 'keterangan'];
// Menampilkan data
public function getAll($id = false)
{
if ($id === false) {
return $this->paginate(10, 'pelayanan');
}
return $this->where([
'id' => $id
])->first();
}
public function getPelayanan($id = false)
{
if($id === false){
return $this->table('pelayanan')
->get()
->getResultArray();
} else {
return $this->table('pelayanan')
->where('id', $id)
->get()
->getRowArray();
}
}
public function insert_pelayanan($data)
{
return $this->db->table($this->table)->insert($data);
}
public function update_pelayanan($data, $id)
{
return $this->db->table($this->table)->update($data, ['id' => $id]);
}
public function delete_pelayanan($id)
{
return $this->db->table($this->table)->delete(['id' => $id]);
}
}<file_sep><?php
namespace App\Models;
use CodeIgniter\Model;
class TampilpelayananModel extends Model
{
protected $table = 'pelayanan';
public function __construct()
{
$this->db = db_connect();
$this->builder = $this->db->table($this->table);
}
public function getAllData($id = null)
{
if ($id == null) {
return $this->builder->get();
} else {
$this->builder->where('id', $id);
return $this->builder->get()->getRowArray();
}
}
}
<file_sep><?= $this->extend('/layouts/tempelate-antrian'); ?>
<?= $this->section('content'); ?>
<div class="container">
<div class="body-wrap boxed-container">
<?php foreach ($antrian as $key => $data) {
$a = $data["id"];
} ?>
<main>
<section class="hero">
<div class="container">
<div class="hero-inner">
<div class="hero-copy">
<br>
<div class="container">
<div class="card text-center">
<div class="card-header bg-primary"> NOMOR ANTRIAN </div>
<div class="card-body">
<h1 class="hero-paragraph is-revealing">
<?php
$request = \Config\Services::request();
$s = $request->uri->getSegment(3);
if ($s == "4") {
echo "A" .
$a;
} elseif ($s == "5") {
echo "B" .
$a;
} elseif ($s == "6") {
echo "C" .
$a;
} elseif ($s == "7") {
echo "D" .
$a;
}
?> </h1>
<h3>Akan tercetak otomatis . . . </h3>
</div>
</div>
</div>
<p class="hero-cta is-revealing">
<a class="button button-primary button-shadow" href="#">.</a>
</p>
</div>
<div class="container mt-5 mb-5 text-center"></div>
<!-- <div class="container">
<?php if (!empty(session()->getFlashdata("success"))) { ?><div class="alert alert-success">
<?php echo session()->getFlashdata("success"); ?></div>
<?php } ?>
<?php if (!empty(session()->getFlashdata("info"))) { ?><div class="alert alert-info">
<?php echo session()->getFlashdata("info"); ?></div>
<?php } ?>
<?php if (!empty(session()->getFlashdata("warning"))) { ?><div class="alert alert-warning">
<?php echo session()->getFlashdata("warning"); ?></div>
<?php } ?></div> -->
</div>
</div>
</section>
</main>
</div>
<script src="<?php echo base_url("dist/js/main.min.js"); ?>">
</script>
</div> <?= $this->endSection(); ?><file_sep><?php namespace App\Models;
use CodeIgniter\Model;
class AntrianModel extends Model
{
protected $table = "antrian";
public function getAntrian($id = false)
{
if($id === false){
$request = \Config\Services::request();
$loktt = $request->uri->getSegment(3);
return $this->table('antrian')
->where('pelayanan_id', $loktt)
->selectMax('id')
->limit(1)
->get()
->getResultArray();
} else {
return $this->table('antrian')
->where('antrian_loket_id', $id)
->where('pelayanan_id', $id)
->get()
->getRowArray();
}
}
public function getAntrianstatus($id = false)
{
if($id === false){
return $this->table('antrian')
->where('status', 'berlansung')
->get()
->getResultArray();
} else {
return $this->table('antrian')
->where('status', 'berlansung')
->where('pelayanan_id', $id)
->get()
->getRowArray();
}
}
public function getAntrianno($id = false)
{
if($id != 0){
return $this->table('antrian')
->where('pelayanan_id', $id)
->where('status', 'berlansung')
->selectMin('id')
->limit(1)
->get()
->getResultArray();
} else {
return $this->table('antrian')
->where('antrian_loket_id', $id)
->where('pelayanan_id', $id)
->get()
->getRowArray();
}
}
public function getAntrianlast($id = false)
{
if($id != 0){
return $this->table('antrian')
->where('status', 'berlansung')
->selectMax('id')
->limit(1)
->get()
->getResultArray();
} else {
return $this->table('antrian')
->where('antrian_loket_id', $id)
->where('pelayanan_id', $id)
->get()
->getRowArray();
}
}
public function insert_antrian($data)
{
return $this->db->table($this->table)->insert($data);
}
public function update_antrian($data, $id)
{
return $this->db->table($this->table)->update($data, ['id' => $id]);
}
public function delete_antrian($id)
{
return $this->db->table($this->table)->delete(['id' => $id]);
}
public function update_antrian_data($data, $id)
{
$request = \Config\Services::request();
$rr = $request->uri->getSegment(3);
$this->db->table($this->table)->update($data, ['id' => $id]);
return $this->db->query("UPDATE antrian SET status = 'berlansung' WHERE id = ( SELECT MIN(id) AS min FROM antrian WHERE pelayanan_id = (select pelayanan_id from antrian where id = '" .$id." ') and status = 'mengantri' )");
}
}<file_sep><?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\AntrianModel;
class Loketpanggil extends Controller
{
public function __construct()
{
$this->antrian = new AntrianModel();
}
public function index()
{
$data = [
'title' => 'Loket panggil'
];
$data['antrian4'] = $this->antrian->getAntrianno(4);
$data['antrian5'] = $this->antrian->getAntrianno(5);
$data['antrian6'] = $this->antrian->getAntrianno(6);
$data['antrian7'] = $this->antrian->getAntrianno(7);
$data['antrianlast'] = $this->antrian->getAntrianlast(7);
echo view('admin/loketpanggil/index', $data);
}
public function dua()
{
$data = [
'title' => 'Loket panggil 2'
];
$data['antrian4'] = $this->antrian->getAntrianno(4);
$data['antrian5'] = $this->antrian->getAntrianno(5);
$data['antrian6'] = $this->antrian->getAntrianno(6);
$data['antrian7'] = $this->antrian->getAntrianno(7);
$data['antrianlast'] = $this->antrian->getAntrianlast(7);
echo view('admin/loketpanggil/dua', $data);
}
public function tiga()
{
$data = [
'title' => 'Loket panggil 3'
];
$data['antrian4'] = $this->antrian->getAntrianno(4);
$data['antrian5'] = $this->antrian->getAntrianno(5);
$data['antrian6'] = $this->antrian->getAntrianno(6);
$data['antrian7'] = $this->antrian->getAntrianno(7);
$data['antrianlast'] = $this->antrian->getAntrianlast(7);
echo view('admin/loketpanggil/tiga', $data);
}
public function empat()
{
$data = [
'title' => 'Loket panggil 4'
];
$data['antrian4'] = $this->antrian->getAntrianno(4);
$data['antrian5'] = $this->antrian->getAntrianno(5);
$data['antrian6'] = $this->antrian->getAntrianno(6);
$data['antrian7'] = $this->antrian->getAntrianno(7);
$data['antrianlast'] = $this->antrian->getAntrianlast(7);
echo view('admin/loketpanggil/empat', $data);
}
public function edit($id)
{
$desc = 'selesai';
// Membuat array collection yang disiapkan untuk insert ke table
$data = [
'status' => $desc
];
/*
Membuat variabel ubah yang isinya merupakan memanggil function
update_loket dan membawa parameter data beserta id
*/
$ubah = $this->antrian->update_antrian_data($data, $id);
// Jika berhasil melakukan ubah
if ($ubah) {
// Deklarasikan session flashdata dengan tipe info
session()->setFlashdata('info', 'Nomor antrian ' . $id . ' Selesai!');
// Redirect ke halaman antrian
return redirect()->to(base_url('loketpanggil'));
}
}
}
<file_sep><?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\TampilpelayananModel;
class Tpelayanan extends Controller
{
public function __construct()
{
// Mendeklarasikan class ProductModel menggunakan $this->pelayanan
$this->pelayanan = new TampilpelayananModel();
}
public function antrianindex()
{
$data = [
'title' => 'Ambil Antrian'
];
$data['pelayanan'] = $this->pelayanan->getAllData();
echo view('pages/antrian/index', $data);
}
}
<file_sep>Repository ini dibuat untuk memenuhi tugas Pemrograman Web
| Nama | <NAME> |
| ----------- | ----------- |
| NIM | 312010498 |
| Kelas | TI.20.A.1 |
# UAS <NAME> (Genap)
<b>Link</b>
- [Dokumentasi](https://youtu.be/FBTE4BXdMFc)
- [Demo program](http://antriansistemlydia.epizy.com/)
<p>Untuk melakukan Program ini harus instalasi Codeigniter 4 dapat dilakukan dengan dua cara, yaitu cara manual dan menggunakan <b>composer</b>. Pada praktikum ini kita menggunakan cara composer.</p>

<P>Setelah itu buka ``XAMPP``</P>
klik shell, kemudian ketik:
```php
cd C:\xampp\htdocs\UAS
```
Setelah itu ketik:
```php
shell php spark serve
```
<p>Kemudian ketik:</p>
```php
http://localhost:8080
```
Saya membuat webhosting dari ( https://app.infinityfree.net/ )
Untuk Upload data ke webhosting saya menggunakan filezilla Client

<file_sep><?= $this->extend('/layouts/tempelate-admin'); ?>
<?= $this->section('content'); ?>
<div class="container">
<h4>Edit Loket</h4>
<hr>
<form action="<?php echo base_url('loket/update/' . $loket['id']); ?>" method="post">
<div class="form-group">
<label for="">Nama Loket</label>
<input type="text" name="nama" value="<?php echo $loket['nama']; ?>" class="form-control" placeholder="Nama Loket">
</div>
<div class="form-group">
<label for="">Jenis Loket</label>
<select name="id" class="form-control" placeholder="Jenis Pelayanan">>
<?php
foreach ($pelayanan as $key => $data) { ?>
<option value="<?php echo $data['id']; ?>">
<?php echo $data['nama']; ?> </option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="">Keterangan Loket</label>
<input type="text" name="keterangan" value="<?php echo $loket['keterangan']; ?>" class="form-control" placeholder="Nama description">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
<?= $this->endSection(); ?><file_sep><?php
foreach ($antrian4 as $key => $data) { ?>
<tr>
<td><?php echo $key + 1; ?></td>
<td><?php echo $data["id"]; ?></td>
<td><?php echo $data["loket_id"]; ?></td>
</tr>
<?php } ?>
<?php foreach ($antrian5 as $key => $data) { ?>
<tr>
<td><?php echo $key + 1; ?></td>
<td><?php echo $data["id"]; ?></td>
<td><?php echo $data["loket_id"]; ?></td>
</tr>
<?php } ?><file_sep><?= $this->extend('/layouts/tempelate-admin'); ?>
<?= $this->section('content'); ?>
<div class="container">
<h4>Tambah Loket</h4>
<hr>
<form action="<?php echo base_url('loket/store'); ?>" method="post">
<div class="form-group">
<label for="">Nama Loket</label>
<input type="text" name="nama" class="form-control" placeholder="Nama Keterangan">
</div>
<div class="form-group">
<label for="">Jenis Layanan</label>
<select name="pelayanan_id" class="form-control" placeholder="Jenis Pelayanan">>
<?php
foreach ($pelayanan as $key => $data) { ?>
<option value="<?php echo $data['id']; ?>">
<?php echo $data['nama']; ?> </option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="">Keterangan Loket</label>
<input type="text" name="keterangan" class="form-control" placeholder="Keterangan Loket">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Simpan</button>
</div>
</form>
</div>
<?= $this->endSection(); ?><file_sep><?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\PelayananModel;
class Pelayanan extends Controller
{
public function __construct()
{
// Mendeklarasikan class PelayananModel menggunakan $this->pelayanan
$this->pelayanan = new PelayananModel();
}
public function index()
{
$data = [
'title' => '<NAME>'
];
$data['pelayanan'] = $this->pelayanan->getPelayanan();
echo view('admin/pelayanan/index', $data);
}
public function edit($id)
{
$data = [
'title' => 'Edit Pelayanan'
];
// Memanggil function getPelayanan($id) dengan parameter $id di dalam PelayananModel dan menampungnya di variabel array pelayanan
$data['pelayanan'] = $this->pelayanan->getPelayanan($id);
// Mengirim data ke dalam view
return view('admin/pelayanan/edit', $data);
}
public function create()
{
$data = [
'title' => 'Tambah Pelayanan'
];
return view('admin/pelayanan/create', $data);
}
public function delete($id)
{
// Memanggil function delete_pelayanan() dengan parameter $id di dalam PelayananModel dan menampungnya di variabel hapus
$hapus = $this->pelayanan->delete_pelayanan($id);
// Jika berhasil melakukan hapus
if ($hapus) {
// Deklarasikan session flashdata
session()->setFlashdata('danger', 'Deleted pelayanan berhasil!');
// Redirect ke halaman Pelayanan
return redirect()->to(base_url('pelayanan'));
}
}
public function update($id)
{
// Mengambil value dari form dengan method POST
$name = $this->request->getPost('nama');
$code = $this->request->getPost('kode');
$desc = $this->request->getPost('keterangan');
// Membuat array collection yang disiapkan untuk insert ke table
$data = [
'nama' => $name,
'kode' => $code,
'keterangan' => $desc
];
/*
Membuat variabel ubah yang isinya merupakan memanggil function
update_pelayanan dan membawa parameter data beserta id
*/
$ubah = $this->pelayanan->update_pelayanan($data, $id);
// Jika berhasil melakukan ubah
if ($ubah) {
// Deklarasikan session flashdata
session()->setFlashdata('warning', 'Updated pelayanan berhasil!');
// Redirect ke halaman pelayanan
return redirect()->to(base_url('pelayanan'));
}
}
public function store()
{
// Mengambil value dari form dengan method POST
$name = $this->request->getPost('nama');
$code = $this->request->getPost('kode');
$desc = $this->request->getPost('keterangan');
// Membuat array collection yang disiapkan untuk insert ke table
$data = [
'nama' => $name,
'kode' => $code,
'keterangan' => $desc
];
/*
Membuat variabel simpan yang isinya merupakan memanggil function
insert_pelayanan dan membawa parameter data
*/
$simpan = $this->pelayanan->insert_pelayanan($data);
// Jika simpan berhasil, maka ...
if ($simpan) {
// Deklarasikan session flashdata dengan tipe success
session()->setFlashdata('success', 'Created pelayanan successfully');
// Redirect halaman ke pelayanan
return redirect()->to(base_url('pelayanan'));
}
}
}
<file_sep><?php foreach ($antrian4 as $key => $data4) {
$aa = $data4["id"];
} ?>
<?php foreach ($antrian5 as $key => $data5) {
$bb = $data5["id"];
} ?>
<?php foreach ($antrian6 as $key => $data6) {
$cc = $data6["id"];
} ?>
<?php foreach ($antrian7 as $key => $data7) {
$dd = $data7["id"];
} ?>
<?= $this->extend('/layouts/tempelate-admin'); ?>
<?= $this->section('content'); ?>
<!-- Begin Page Content -->
<div class="container pb-5">
<?php if (!empty(session()->getFlashdata("success"))) { ?>
<div class="alert alert-success">
<?php echo session()->getFlashdata("success"); ?>
</div>
<?php } ?>
<?php if (!empty(session()->getFlashdata("info"))) { ?>
<div class="alert alert-info">
<?php echo session()->getFlashdata("info"); ?>
</div>
<?php } ?>
<?php if (!empty(session()->getFlashdata("warning"))) { ?>
<div class="alert alert-warning">
<?php echo session()->getFlashdata("warning"); ?>
</div>
<?php } ?>
<!-- Begin Page Content -->
<div id="loket2">
<!-- Page Heading -->
<div class="col-12">
Pelayanan Loket 2 (Pengaduan)
</div>
<div class="card">
<div class="">
<div class="container">
<div class="row">
<div class="col-dilayani">
<div class="dilayani">
<h5>Sedang Dilayani</h5>
<p>B<?php echo $bb; ?></p>
</div>
<?php if (is_numeric($bb)) {
echo "<a href='" .
base_url("loketpanggil/edit/" . $bb) .
"' class='btn btn-lg col-11 btn-warning'>Selesai</a>";
} else {
echo "<a class='btn btn-lg col-11 btn-danger'>Tidak ada antrian</a>";
} ?>
</div>
<div class="daftar">
<h4>Daftar Antrian Selanjutnya</h4>
<table class="table" border="1" cellspacing="0">
<thead>
<tr>
<th>No Antrian</th>
<th>Panggil</th>
<th>Keterangan</th>
</tr>
</thead>
<tbody>
<tr>
<td>B<?php echo $bb; ?></td>
<td>
<?php if (is_numeric($bb)) {
echo "<a href='' class='btn btn-sm col-11 btn-success'>Panggil</a>";
} else {
echo "<a class='btn btn-sm col-11 btn-danger'>kosong</a>";
} ?>
</td>
<td>Ada</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
<!-- End of Main Content -->
<?= $this->endSection(); ?> | 030e1cb9d56cc2172635125a43b7cfe0fcc9dd95 | [
"JavaScript",
"SQL",
"Markdown",
"PHP"
] | 24 | SQL | Lydiadiffanisiregar/UAS | de82c1d4c30b877ac7df69173d8de1d91bbca53a | 5be1b68a8171f1ab1e3e6c3152193801c6caa9f1 | |
refs/heads/master | <repo_name>Kaylee2319/Outpost<file_sep>/client/src/components/PolicyGuide.jsx
import React from 'react';
import '../css/PolicyGuide.css';
import NavBar from './NavBar';
import Footer from './Footer';
import { BsPeople } from 'react-icons/bs';
import { IoIosSearch } from 'react-icons/io';
import { FaRegHandshake } from 'react-icons/fa';
const PolicyGuide = ({ history }) => {
const handleClick = () => {
history.push('/signup');
};
return (
<>
<NavBar />
<div>
<h1 className="policyTitle">How It Works</h1>
<h3 className="policyTitle1">Join a community of veteran gamers</h3>
</div>
<div className="iconbar2">
<div className="howtoSearch">
<div className="howSearch">
Search
<IoIosSearch size={55} style={{ color: 'black' }} />
</div>
<p className="howSearch1">
Search for military veteran players and chat through 1-1 or group
chats of your favorite games
</p>
</div>
<div className="howtoconnect">
<p className="howConnect1">
Connect through the app, add your friends and schedule a game time.
</p>
<div className="howConnect">
Connect
<BsPeople size={55} style={{ color: 'black' }} />
</div>
</div>
<div className="howtoGameon">
<div className="howGameOn">
Game On!
<FaRegHandshake size={55} style={{ color: 'black' }} />
</div>
<p className="howGameOn1">
Meet players at the platform of your choice & Game On!
</p>
</div>
</div>
<div className="howButton">
<button onClick={handleClick} className="howtoButton">
BECOME A MEMBER
</button>
</div>
<Footer />
</>
);
};
export default PolicyGuide;
<file_sep>/client/src/components/LoginPage.jsx
import React, { useState, useContext } from 'react';
import '../css/LoginPage.css';
import NavBar from './NavBar';
import Footer from './Footer';
import { Link } from 'react-router-dom';
import { FaXbox } from 'react-icons/fa';
import { FaPlaystation } from 'react-icons/fa';
import { SiNintendoswitch } from 'react-icons/si';
import { SiSteam } from 'react-icons/si';
import { SiTwitch } from 'react-icons/si';
import { AppContext } from '../context/AppContext';
import axios from 'axios';
import swal from 'sweetalert';
const LoginPage = ({ history }) => {
const { setCurrentUser } = useContext(AppContext);
const [formData, setFormData] = useState(null);
const handleChange = (event) => {
setFormData({ ...formData, [event.target.name]: event.target.value });
};
const handleLogin = async (event) => {
event.preventDefault();
try {
const response = await axios.post('/api/login', formData);
setCurrentUser(response.data);
sessionStorage.setItem('user', response.data);
history.push('/profile');
} catch (error) {
swal(`Oops!`, 'Something went wrong.');
}
};
return (
<>
<NavBar />
<div className="topTitle">
<p className="gameUp">Choose your rally point</p>
</div>
<div className="signInTitle">
<p className="signIn">Game up with veterans!</p>
</div>
<div className="signinWith">
<h1 className="signButton">
<FaXbox size={30} style={{ color: 'black' }} />
</h1>
<h1 className="signButton">
<FaPlaystation size={30} style={{ color: 'black' }} />
</h1>
<h1 className="signButton">
<SiNintendoswitch size={30} style={{ color: 'black' }} />
</h1>
<h1 className="signButton">
<SiSteam size={30} style={{ color: 'black' }} />
</h1>
<h1 className="signButton">
<SiTwitch size={30} style={{ color: 'black' }} />
</h1>
</div>
<div className="or">
<p className="or">OR</p>
</div>
<form className="loginForm" onSubmit={handleLogin}>
<p className="email">Email:</p>
<input
className="emailBox"
id="email"
type="email"
name="email"
onChange={handleChange}
/>
<p className="passwords">Password:</p>
<input
className="passwordBox"
type="password"
name="password"
onChange={handleChange}
/>
<Link to="/passwordreset" className="forgot">
<span className="forgotten">Forgot Password?</span>
</Link>
<input className="loginButton" type="submit" value="SIGN IN" />
</form>
<div className="noAccountTitle">
<p className="noAccountTitle">Don't have an account?</p>
</div>
<div className="signupLink">
<Link to="/signup" className="signupLink">
<span className="signLink">Sign up</span>
</Link>
</div>
<Footer />
</>
);
};
export default LoginPage;
<file_sep>/client/src/components/NavBar.jsx
import React, { useContext } from 'react';
import { Link } from 'react-router-dom';
import { AppContext } from '../context/AppContext';
import '../css/NavBar.css';
import { FiMenu } from 'react-icons/fi';
import { MdPersonPin } from 'react-icons/md';
import { AiOutlineUserAdd } from 'react-icons/ai';
const NavBar = () => {
const { currentUser } = useContext(AppContext);
return (
<>
<div className="navbar">
<Link to="/menu" className="menu">
<FiMenu size={30} style={{ color: '055F9E' }} />
</Link>
<Link to="/" className="name">
Outpost
</Link>
<div>
{!currentUser ? (
<Link to="/login" className="signup">
<AiOutlineUserAdd size={27} style={{ color: '055F9E' }} />
</Link>
) : (
<Link to="/profile" className="profile">
<MdPersonPin size={27} style={{ color: '055F9E' }} />
</Link>
)}
</div>
</div>
</>
);
};
export default NavBar;
<file_sep>/server/routes/secure/users.js
const router = require('express').Router(),
{
getUserProfile,
getUserByID,
updateUserProfile,
uploadAvatar,
updatePassword,
logoutUser,
deleteUser
} = require('../../controllers/users');
router.get('/profile', getUserProfile);
router.get('/allusers/:id', getUserByID);
router.patch('/profile', updateUserProfile);
router.post('/avatar', uploadAvatar);
router.put('/password', updatePassword);
router.post('/logout', logoutUser);
router.delete('/', deleteUser);
module.exports = router;
<file_sep>/README.md
# Outpost-Gaming
## About us
- We are a team of veterans and students at Wyncode in Miami, FL.
- The purpose for Outpost is to address suicide among veterans which is currently at an average of 22 veterans per day. With this app, we can help provide a safe space outlet for veterans to come together, schedule gaming days, attend online group chats and talk about whatever is on their mind.
- Additionally, we want to provide resources to other military communities and mental health support/therapy.
## Link to Site
- https://outpost-gaming.herokuapp.com/
## How to View in Phone View
- This is a cellphone app only
- to view it as a cellphone on chrome use your developer tools, follow the steps below
- Right Click
- select inspect
- 
- click the toggle device button in the top left of the console.
- 
- click the 3 dots in the top right corner
- click more tools
- 
- click developer tools
- 
- click the toggle device button in the top left of the console.
- 
## Setup to Clone the Repo
- `git clone` this repo
- `cd` into it.
- `yarn install`
- `cd client && yarn install`
- `cp .env.sample .env`
## Available Build Commands
- `yarn dev`: Runs BOTH your Express.JS and React developer environment locally at the same time. Any logs coming from Express will be prefaced with `[0]`, any logs from `create-react-app` will be prefaced with `[1]`.
- `yarn server`: Runs JUST your Express.JS server.
- `yarn client`: Runs JUST your front-end React app.
Open [http://localhost:3000](http://localhost:3000) to view your local React app in the browser. The page will reload if you make edits.
<file_sep>/client/src/components/VeteranPrograms.jsx
import React from 'react';
import '../css/VeteranPrograms.css';
import NavBar from './NavBar';
import Footer from './Footer';
const VeteranPrograms = () => {
return (
<>
<NavBar />
<div>
<div className="VaTitle">Veteran Programs</div>
<p className="aboutVaPg">Thank you for your service.</p>
<p className="aboutVaPg">We're here to guide.</p>
</div>
<div className="mission22">
<div className="m22img"></div>
<div className="aboutMission">
<p className="aboutMission1">
Recovery + Resiliency is a 12-month program available to combat
Veterans
</p>
<a href="https://mission22.com/">
<button className="missionbutton">Go</button>
</a>
</div>
</div>
<div className="talkspace">
<div className="talkimg"></div>
<div className="aboutTs">
<p className="aboutTs1">
TalkSpace: Online Counseling & Therapy for Veterans. HIPPA Compliant
& Secure SSL
</p>
<a href="https://www.talkspace.com/online-therapy/veterans/">
<button className="tsbutton">Go</button>
</a>
</div>
</div>
<div className="feedvets">
<div className="feedimg"></div>
<div className="aboutFeedvet">
<p className="aboutFeedvet1">
Since 2009, Feed Our Vets has provided free food assistance to more
than 25,000 Veterans.
</p>
<a href="https://feedourvets.org/">
<button className="feedvetbutton">Go</button>
</a>
</div>
</div>
<div className="nva">
<div className="nvaimg"></div>
<div className="aboutNva">
<p className="aboutNva1">
{' '}
We help Veterans and their families who are enduring a crisis or who
have a critical need for help.
</p>
<a href="https://nvf.org/">
<button className="nvabutton">Go</button>
</a>
</div>
</div>
<div className="wounded">
<div className="woundedimg"></div>
<div className="aboutWounded">
<p className="aboutWounded1">
Veterans and service members who incurred a physical or mental
injury, while serving in the military. You are our focus. You are
our mission.
</p>
<a href="https://www.woundedwarriorproject.org/">
<button className="woundedbutton">Go</button>
</a>
</div>
</div>
<Footer />
</>
);
};
export default VeteranPrograms;
<file_sep>/client/src/components/GamersProfile.jsx
import React, { useState, useContext, useEffect } from 'react';
import '../css/ProfilePage.css';
import NavBar from './NavBar';
import Footer from './Footer';
import axios from 'axios';
import swal from 'sweetalert';
import { Link } from 'react-router-dom';
import { AppContext } from '../context/AppContext';
import { MdComputer, MdDevicesOther } from 'react-icons/md';
import { FaXbox, FaPlaystation } from 'react-icons/fa';
import { SiNintendoswitch } from 'react-icons/si';
import wyncode from '../images/wyncode.png';
const GamersProfile = ({ match }) => {
const [loading, setLoading] = useState(true);
const { gamer, setGamer } = useContext(AppContext);
useEffect(() => {
console.log('PARAMS', match);
axios
.get(`/api/users/allusers/${match.params.id}`)
.then((response) => {
setGamer(response.data);
setLoading(false);
})
.catch((error) => {
swal(`Oops!`, 'Something went wrong.');
setLoading(false);
});
}, [setGamer, match]);
if (loading) return <h1>Loading...</h1>;
return (
<>
<NavBar />
<div key={gamer?._id}>
<div className="pic">
<img
className="proPic"
src={gamer?.avatar ? gamer?.avatar : `${wyncode}`}
alt="profile"
/>
</div>
<div className="namedPlayer">
<div className="nameEdit">
<h2 className="usersName">
{gamer?.first_name} {gamer?.last_name}
</h2>
</div>
<h3 className="userName">{gamer?.user_name}</h3>
<h4 className="dutyStatus">{gamer?.service_branch}</h4>
<Link to="/chats" className="messageButton">
<span className="messageButton1">Message</span>
</Link>
</div>
<div className="favGames" style={{ marginBottom: 20 }}>
<p className="consoles">Find me on:</p>
<div className="mygameTags">
<div>
<FaXbox /> <strong>Xbox:</strong> {gamer?.xbox}
</div>
<div>
<FaPlaystation /> <strong>Playstation:</strong> {gamer?.psn}
</div>
<div>
<SiNintendoswitch /> <strong>Nintendo:</strong> {gamer?.nes}
</div>
<div>
<MdComputer /> <strong>PC:</strong> {gamer?.pc}
</div>
<div>
<MdDevicesOther /> <strong>Other:</strong> {gamer?.other}
</div>
</div>
</div>
</div>
<Footer />
</>
);
};
export default GamersProfile;
<file_sep>/client/src/components/Footer.jsx
import React from 'react';
import { Link } from 'react-router-dom';
import '../css/Footer.css';
const Footer = () => {
return (
<>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
></link>
<div className="footer">
<div className="nav">
<Link style={{ textDecoration: 'none', color: 'black' }} to="/about">
{' '}
About Us{' '}
</Link>
<Link
style={{ textDecoration: 'none', color: 'black' }}
to="/contactus"
>
{' '}
Contact Us{' '}
</Link>
<Link
style={{ textDecoration: 'none', color: 'black' }}
to="/veteranprograms"
>
{' '}
Veteran Programs{' '}
</Link>
<Link style={{ textDecoration: 'none', color: 'black' }} to="/policy">
{' '}
Policy & Guidelines{' '}
</Link>
</div>
<div className="icon-bar">
<div>
<p className="follow">Follow Us</p>
</div>
<div className="social">
<a href="https://www.facebook.com/wyncode/" className="facebook">
<i className="fa fa-facebook"></i>
</a>
<a href="https://twitter.com/wyncode?lang=en" className="twitter">
<i className="fa fa-twitter"></i>
</a>
<a
href="https://www.instagram.com/wyncode/?hl=en"
className="instagram"
>
<i className="fa fa-instagram"></i>
</a>
</div>
</div>
</div>
</>
);
};
export default Footer;
<file_sep>/client/src/components/PasswordReset.jsx
import React, { useState } from 'react';
import axios from 'axios';
import swal from 'sweetalert';
import '../css/PasswordReset.css';
import NavBar from './NavBar';
import Footer from './Footer';
const ResetPassword = () => {
const [email, setEmail] = useState('');
const handleSubmit = async (event) => {
event.preventDefault();
const form = event.target;
try {
const response = await axios.get(`api/password?email=${email}`);
if (response) {
swal(
'Email sent',
'Check your email for a link to reset your password.'
);
}
form.reset();
} catch (error) {
swal('Error', 'Oops, something went wrong.');
}
};
return (
<div>
<NavBar />
<h1 className="resetPass">Reset Password</h1>
<form className="PassResetForm" onSubmit={handleSubmit}>
<label>Email address:</label>
<input
className="passemailReset"
type="email"
name="email"
placeholder="Enter email"
onChange={(event) => setEmail(event.target.value)}
autoComplete="off"
required
></input>
<button className="resetPassButton" type="submit">
Reset Password
</button>
</form>
<Footer />
</div>
);
};
export default ResetPassword;
<file_sep>/client/src/components/GamerSearch.jsx
import React, { useContext } from 'react';
import { AppContext } from '../context/AppContext';
import '../css/GamerStyles.css';
const GamerSearch = () => {
const { setSearch } = useContext(AppContext);
const handleSearch = (event) => {
setSearch(event.target.value);
};
return (
<div className="searchgamer">
<input
className="gamersearch"
onChange={handleSearch}
type="text"
placeholder="Search for a Gamer..."
/>
</div>
);
};
export default GamerSearch;
<file_sep>/client/src/components/Chatroom.jsx
import React from 'react';
import Chat from './Chats';
import NavBar from './NavBar';
import Footer from './Footer';
const Chatroom = () => {
return (
<>
<NavBar />
<div>
<Chat />
</div>
<Footer />
</>
);
};
export default Chatroom;
<file_sep>/client/src/App.jsx
import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import { AppContextProvider } from './context/AppContext';
import SecureRoute from './components/SecureRoute';
import HomePage from './components/HomePage';
import SignUpPage from './components/SignUpPage';
import LoginPage from './components/LoginPage';
import PasswordReset from './components/PasswordReset';
import PasswordUpdate from './components/PasswordUpdate';
import Menu from './components/MenuPage';
import AboutPage from './components/AboutPage';
import PolicyGuide from './components/PolicyGuide';
import VeteranPrograms from './components/VeteranPrograms';
import ContactUs from './components/ContactUsPage';
import Events from './components/Events';
import Gamers from './components/Gamers';
import Chatroom from './components/Chatroom';
import ProfilePage from './components/ProfilePage';
import ProfileEdit from './components/ProfileEdit';
import GamersList from './components/GamersList';
import GamersProfile from './components/GamersProfile';
function App() {
return (
<AppContextProvider>
<BrowserRouter>
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/signup" component={SignUpPage} />
<Route exact path="/login" component={LoginPage} />
<Route exact path="/passwordreset" component={PasswordReset} />
<Route exact path="/passwordupdate" component={PasswordUpdate} />
<Route exact path="/menu" component={Menu} />
<Route exact path="/about" component={AboutPage} />
<Route exact path="/policy" component={PolicyGuide} />
<Route exact path="/veteranprograms" component={VeteranPrograms} />
<Route exact path="/contactus" component={ContactUs} />
<Route exact path="/event" component={Events} />
<Route exact path="/search" component={Gamers} />
<Route exact path="/gamers" component={GamersList} />
<Route exact path="/gamersprofile/:id" component={GamersProfile} />
<SecureRoute exact path="/chats" component={Chatroom} />
<SecureRoute exact path="/profile" component={ProfilePage} />
<SecureRoute exact path="/profileedit" component={ProfileEdit} />
</Switch>
</BrowserRouter>
</AppContextProvider>
);
}
export default App;
<file_sep>/client/src/components/Chats.jsx
import React, { useState, useEffect, useContext } from 'react';
import socketIo from '../utils/socket-io';
import { AppContext } from '../context/AppContext';
import '../css/Chat.css';
import { RiSendPlaneFill } from 'react-icons/ri';
import wyncode from '../images/wyncode.png';
const Chat = () => {
const [message, setMessage] = useState('');
const [chats, setChats] = useState([]);
const { currentUser } = useContext(AppContext);
useEffect(() => {
socketIo.on('receive message', (data) => {
console.log('receive message', data);
addMessage(data);
});
}, [chats]);
const addMessage = (msg) => {
setChats(
chats.concat({
avatar: msg.avatar,
author: msg.author,
message: msg.message
})
);
};
const sendMessage = (event) => {
event.preventDefault();
socketIo.emit('send message', {
avatar: `${currentUser?.avatar ? currentUser?.avatar : `${wyncode}`}`,
author: `${currentUser?.user_name}`,
message: message
});
setMessage('');
};
const handleKeyDown = (event) => {
if (event.key === 'Enter') {
sendMessage(event);
setMessage('');
}
};
return (
<div className="container">
<div className="messages">
<div className="theMess">
{chats.map((chat) => {
let isSentByCurrentUser = chat.author === currentUser.user_name;
return isSentByCurrentUser ? (
<div className="messageMine justifyEnd">
<img className="messagePic" src={chat.avatar} alt="user"></img>
<div className="messageText">
<strong>{chat.author}:</strong> {chat.message}
</div>
</div>
) : (
<div className="messageTheirs justifyStart">
<img className="messagePic" src={chat.avatar} alt="user"></img>
<div className="messageText">
<strong>{chat.author}:</strong> {chat.message}
</div>
</div>
);
})}
</div>
</div>
<div className="inputBox">
<input
className="form-control"
type="text"
name="messages"
placeholder="Message"
value={message}
onKeyDown={handleKeyDown}
onChange={(e) => setMessage(e.target.value)}
/>
<button className="sendButton" type="submit" onClick={sendMessage}>
<RiSendPlaneFill size={30} style={{ color: 'rgba(5, 95, 158, 1)' }} />
</button>
</div>
</div>
);
};
export default Chat;
<file_sep>/client/src/components/ProfilePage.jsx
import React, { useContext, useState } from 'react';
import axios from 'axios';
import swal from 'sweetalert';
import '../css/ProfilePage.css';
import NavBar from './NavBar';
import Footer from './Footer';
import { Link } from 'react-router-dom';
import { AiOutlineCloudUpload } from 'react-icons/ai';
import { FiSave } from 'react-icons/fi';
import { BsTrash } from 'react-icons/bs';
import { VscSignOut } from 'react-icons/vsc';
import { AppContext } from '../context/AppContext';
import { MdComputer, MdDevicesOther } from 'react-icons/md';
import { FaXbox, FaPlaystation } from 'react-icons/fa';
import { SiNintendoswitch } from 'react-icons/si';
const ProfilePage = ({ history: { push } }) => {
const { currentUser, setCurrentUser, setLoading } = useContext(AppContext);
const [image, setImage] = useState(null);
const [preview, setPreview] = useState(null);
const handleImageSelect = (event) => {
setPreview(URL.createObjectURL(event.target.files[0]));
setImage(event.target.files[0]);
};
const handleSubmit = async (event) => {
event.preventDefault();
const avatar = new FormData();
avatar.append('avatar', image, image.name);
try {
const updatedUser = await axios({
method: 'POST',
url: '/api/users/avatar',
data: avatar,
headers: {
'Content-Type': 'multipart/form-data'
}
});
setCurrentUser({ ...currentUser, avatar: updatedUser.data.secure_url });
swal('Your image has been updated!', 'success');
} catch (error) {
swal('Error', 'Oops, something went wrong.');
}
};
const handleDelete = async () => {
setLoading(true);
try {
const willDelete = await swal({
title: 'Are you sure?',
text: 'Once deleted, you will not be able to recover this account!',
icon: 'warning',
buttons: true,
dangerMode: true
});
if (willDelete) {
try {
await axios({
method: 'DELETE',
url: '/api/users',
withCredentials: true
});
swal('Your account has been deleted!', {
icon: 'success'
});
setLoading(false);
sessionStorage.removeItem('user');
setCurrentUser(null);
push('/login');
} catch (error) {
swal(`Oops!`, 'Something went wrong.');
}
} else {
swal('Your account is safe!');
}
} catch (error) {
swal(`Oops!`, 'Something went wrong.');
}
};
const handleLogout = async () => {
try {
await axios({
method: 'POST',
url: '/api/users/logout',
withCredentials: true
});
swal('You have been logged out!', {
icon: 'success'
});
setLoading(false);
sessionStorage.removeItem('user');
setCurrentUser(null);
push('/login');
} catch (error) {
swal(`Oops!`, 'Something went wrong.');
}
};
return (
<>
<NavBar />
<div className="pic">
<img
className="proPic"
src={
preview
? preview
: currentUser?.avatar
? currentUser?.avatar
: 'https://files.willkennedy.dev/wyncode/wyncode.png'
}
alt="profile"
/>
</div>
<form className="d-flex flex-column" onSubmit={handleSubmit}>
<div className="proForm">
<div className="fileInput">
<input
type="file"
className="file"
id="file"
accept="image/*"
onChange={handleImageSelect}
/>
<label htmlFor="file">
<AiOutlineCloudUpload
size={15}
style={{ color: 'rgba(5, 95, 158, 1)' }}
/>{' '}
Profile Photo{' '}
</label>
</div>
<button className="ProfileButtons" type="submit">
<FiSave size={15} style={{ color: 'rgba(5, 95, 158, 1)' }} /> Save
Image
</button>
</div>
</form>
<div className="namedPlayer">
<div className="nameEdit">
<h2 className="usersName">
{currentUser?.first_name} {currentUser?.last_name}
</h2>
<Link to="/profileedit" className="editLink">
<span className="editProfile">Edit Profile</span>
</Link>
</div>
<h3 className="userName">{currentUser?.user_name}</h3>
<h4 className="dutyStatus">{currentUser?.service_branch}</h4>
<Link to="/chats" className="messageButton">
<span className="messageButton1">Message</span>
</Link>
</div>
<div className="favGames">
<p className="consoles">Find me on:</p>
<div className="mygameTags">
<div>
<FaXbox /> <strong>Xbox:</strong> {currentUser?.xbox}
</div>
<div>
<FaPlaystation /> <strong>Playstation:</strong> {currentUser?.psn}
</div>
<div>
<SiNintendoswitch /> <strong>Nintendo:</strong> {currentUser?.nes}
</div>
<div>
<MdComputer /> <strong>PC:</strong> {currentUser?.pc}
</div>
<div>
<MdDevicesOther /> <strong>Other:</strong> {currentUser?.other}
</div>
</div>
</div>
<div className="trash">
<button className="ProfileButtons" onClick={handleDelete}>
<BsTrash size={15} style={{ color: 'rgba(5, 95, 158, 1)' }} /> Delete
Account
</button>
<button className="ProfileButtons" onClick={handleLogout}>
<VscSignOut size={15} style={{ color: 'rgba(5, 95, 158, 1)' }} />{' '}
Logout
</button>
</div>
<Footer />
</>
);
};
export default ProfilePage;
<file_sep>/client/src/components/AboutPage.jsx
import React from 'react';
import '../css/AboutPage.css';
import NavBar from './NavBar';
import Footer from './Footer';
const AboutPage = () => {
return (
<>
<NavBar />
<div className="title">
<h2>About Us</h2>
</div>
<div className="story">
<h2 className="ourstory">Our Story</h2>
<p className="ourstory1">
We are a team of veterans and students at Wyncode in Miami, FL.
</p>
<p className="ourstory1">
The purpose for <strong className="colorme">Outpost</strong> is to
address suicide among veterans which is currently at an average of{' '}
<strong className="colorme">22 veterans per day</strong>. With this
app, we can help provide a safe space outlet for veterans to come
together, schedule gaming days, attend online group chats and talk
about whatever is on their mind.
</p>
<p className="ourstory1">
Additionally, we want to provide resources to other military
communities and mental health support/therapy.
</p>
</div>
<div className="ourTeam">
<h1 className="ourTeam1">Our Team</h1>
<div className="webDev">
<div>
<div className="William"></div>
<h1><NAME></h1>
<h2>Web Developer</h2>
</div>
<div>
<div className="kaylee"></div>
<h1><NAME></h1>
<h2>Web Developer</h2>
</div>
</div>
<div className="uxui1">
<div>
<div className="Phil"></div>
<h1><NAME></h1>
<h2>Web Developer</h2>
</div>
<div>
<div className="Gyovany"></div>
<h1><NAME></h1>
<h2>UX UI Designer</h2>
</div>
</div>
<div className="uxui2">
<div>
<div className="Jorge"></div>
<h1><NAME></h1>
<h2>UX UI Designer</h2>
</div>
<div>
<div className="Maria"></div>
<h1><NAME></h1>
<h2>UX UI Designer</h2>
</div>
</div>
</div>
<Footer />
</>
);
};
export default AboutPage;
<file_sep>/client/src/components/MenuPage.jsx
import React, { useContext } from 'react';
import '../css/MenuPage.css';
import { RiArrowLeftSLine } from 'react-icons/ri';
import { AppContext } from '../context/AppContext';
import { Link } from 'react-router-dom';
const Menu = ({ history }) => {
const { currentUser } = useContext(AppContext);
return (
<>
<div className="menuHeader">
<h1 className="menuTitle">MENU</h1>
<button className="backButton" onClick={() => history.goBack()}>
{' '}
<RiArrowLeftSLine
size={35}
style={{ color: 'rgba(5, 95, 158, 1)' }}
/>
</button>
</div>
<div className="line1">
<Link className="searchMenu" to="/gamers">
SEARCH
</Link>
</div>
<div className="menuLinks">
<div className="line1">
{!currentUser ? (
<Link to="/login" className="menuProfile">
LOGIN
</Link>
) : (
<Link to="/profile" className="menuProfile">
PROFILE
</Link>
)}
<Link to="/about" className="menuAbout">
ABOUT
</Link>
</div>
<div className="line2">
{!currentUser ? (
<Link to="/login" className="menuChat">
Chat Now
</Link>
) : (
<Link to="/chats" className="menuChat">
Chat Now
</Link>
)}
<Link to="/event" className="menuEvent">
Events
</Link>
</div>
<div className="line3">
<Link to="/policy" className="MenuPolicy">
Community Guidelines
</Link>
<Link to="/veteranprograms" className="menuVa">
Veteran Programs
</Link>
</div>
</div>
</>
);
};
export default Menu;
<file_sep>/client/src/components/Gamers.jsx
import React, { useContext } from 'react';
import { AppContext } from '../context/AppContext';
import { Link } from 'react-router-dom';
import wyncode from '../images/wyncode.png';
import '../css/GamerStyles.css';
const Task = ({ users }) => {
const { search, currentUser } = useContext(AppContext);
const filteredGamers = users?.filter((users) => {
return users.user_name.toLowerCase().includes(search.toLowerCase());
});
return (
<>
{filteredGamers.map((users) => (
<div key={users?._id}>
{!currentUser ? (
<Link to={'/login'} className="gamerbutton">
<img
src={users?.avatar ? users?.avatar : `${wyncode}`}
alt="user"
className="gamerPic"
/>
<div>
{users?.user_name}
<div>
{users?.first_name} {users?.last_name}
</div>
</div>
</Link>
) : (
<Link to={`/gamersprofile/${users?._id}`} className="gamerbutton">
<img
src={users?.avatar ? users?.avatar : `${wyncode}`}
alt="user"
className="gamerPic"
/>
<div>
{users?.user_name}
<div>
{users?.first_name} {users?.last_name}
</div>
</div>
</Link>
)}
</div>
))}
</>
);
};
export default Task;
<file_sep>/client/src/components/ProfileEdit.jsx
import React, { useContext, useState } from 'react';
import { AppContext } from '../context/AppContext';
import { FiSave } from 'react-icons/fi';
import { Link } from 'react-router-dom';
import NavBar from './NavBar';
import Footer from './Footer';
import axios from 'axios';
import swal from 'sweetalert';
import '../css/ProfileEdit.css';
const EditUser = ({ history }) => {
const { currentUser, setCurrentUser } = useContext(AppContext);
const [formData, setFormData] = useState(null);
const handleChange = (event) => {
setFormData({ ...formData, [event.target.name]: event.target.value });
};
const handleUpDate = async (event) => {
event.preventDefault();
try {
const response = await axios.patch('/api/users/profile', formData);
sessionStorage.setItem('user', response.data);
setCurrentUser(response.data.user);
history.push('/profile');
} catch (error) {
swal('SignUp Error: ', error.toString());
}
};
return (
<div>
<NavBar />
<form className="editForm" onSubmit={handleUpDate}>
<label>User Name: {currentUser?.user_name}</label>
<input
className="editFormUn"
type="text"
name="user_name"
onChange={handleChange}
/>
<label>Email: {currentUser?.email}</label>
<input
className="editFormUn"
type="text"
name="email"
onChange={handleChange}
/>
<label>First Name: {currentUser?.first_name}</label>
<input
className="editFormUn"
type="text"
name="first_name"
onChange={handleChange}
/>
<label>Last Name: {currentUser?.last_name}</label>
<input
className="editFormUn"
type="text"
name="last_name"
onChange={handleChange}
/>
<label>Branch: {currentUser?.service_branch}</label>
<input
className="editFormUn"
type="text"
name="service_branch"
onChange={handleChange}
/>
<div className="editForm">
<h4>Gamer Tags:</h4>
<label>XBOX: </label>
<input
className="editFormUn"
type="text"
name="xbox"
onChange={handleChange}
/>
<label>PSN: </label>
<input
className="editFormUn"
type="text"
name="psn"
onChange={handleChange}
/>
<label>NES: </label>
<input
className="editFormUn"
type="text"
name="nes"
onChange={handleChange}
/>
<label>PC: </label>
<input
className="editFormUn"
type="text"
name="pc"
onChange={handleChange}
/>
<label>other: </label>
<input
className="editFormUn"
type="text"
name="other"
onChange={handleChange}
/>
</div>
<button className="editFormButton" type="submit">
<FiSave size={25} style={{ color: 'rgba(5, 95, 158, 1)' }} /> Save
Info
</button>
<Link to="/passwordupdate" className="editFormButton1">
Update Password
</Link>
</form>
<Footer />
</div>
);
};
export default EditUser;
<file_sep>/server/app.js
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
require('./db/config/index');
const express = require('express'),
path = require('path'),
openRoutes = require('./routes/open/users'),
passport = require('./middleware/authentication/index'),
cookieParser = require('cookie-parser'),
fileUpload = require('express-fileupload'),
userRouter = require('./routes/secure/users');
const app = express();
app.use(express.json());
app.use(cookieParser());
app.use('/api', openRoutes);
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../client/build')));
}
app.use(
fileUpload({
useTempFiles: true,
tempFileDir: '/tmp/images'
})
);
app.use('/api/*', passport.authenticate('jwt', { session: false }));
app.use('/api/users', userRouter);
if (process.env.NODE_ENV === 'production') {
app.get('*', (request, response) => {
response.sendFile(
path.join(__dirname, '..', 'client', 'build', 'index.html')
);
});
}
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
cors: {
origin: true,
methods: ['GET', 'POST']
}
});
io.on('connection', (socket) => {
socket.on('send message', function (msg) {
io.emit('receive message', msg);
});
socket.on('disconnect', () => {});
});
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (request, response) => {
response.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
module.exports = http;
<file_sep>/client/src/context/AppContext.jsx
import React, { createContext, useState, useEffect } from 'react';
import axios from 'axios';
import swal from 'sweetalert';
const AppContext = createContext();
const AppContextProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
const [loading, setLoading] = useState(false);
const [search, setSearch] = useState('');
const [gamer, setGamer] = useState([]);
const [gamers, setGamers] = useState([]);
const [filteredGamers, setFilteredGamers] = useState([]);
const user = sessionStorage.getItem('user');
useEffect(() => {
if (user && !currentUser) {
axios
.get(`/api/users/profile`, {
withCredentials: true
})
.then(({ data }) => {
setCurrentUser(data);
})
.catch((error) => {
swal(`Oops!`, error.toString());
});
}
}, [currentUser, user]);
return (
<AppContext.Provider
value={{
currentUser,
setCurrentUser,
loading,
setLoading,
search,
setSearch,
gamer,
setGamer,
gamers,
setGamers,
filteredGamers,
setFilteredGamers
}}
>
{children}
</AppContext.Provider>
);
};
export { AppContext, AppContextProvider };
| f75660a0aeb2d17f85f62dce3659163d8abaa0fd | [
"JavaScript",
"Markdown"
] | 20 | JavaScript | Kaylee2319/Outpost | f619c3d7453028e8de3e7bf7cf456cc6f6c9e233 | ad9347d507fa65180f3cb43900f7e46ceb2a0481 | |
refs/heads/master | <file_sep>import pandas as pd
import numpy as np
import scipy.io as sio
import pickle
import sklearn.svm as svm
from sklearn.externals import joblib
from sklearn.model_selection import train_test_split,cross_val_score,ShuffleSplit,StratifiedShuffleSplit
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import RandomizedSearchCV
import sys
import os
from sklearn.metrics import f1_score
from sklearn.linear_model import LinearRegression,Lasso,Ridge
from sklearn import metrics
label = pd.read_csv('../data_labels/CIS-PD_Training_Data_IDs_Labels.csv')
#trainY = np.array(label['dyskinesia'])
# 'on_off', 'dyskinesia', 'tremor'
if __name__ == '__main__':
i = 0
while i < len(sys.argv[1:]):
fn = sys.argv[i+1]
trainY = np.array(label[sys.argv[i+2]])
with open(fn, 'rb') as handle:
all_presentations = pickle.loads(handle.read())
filename,ext = os.path.splitext(fn)
not_nan = ~np.isnan(trainY)
X = all_presentations[1:][not_nan]
Y = trainY[not_nan]
D = X.shape[1]
#Test if concatenating mean value within each patient is helpful
#X = X[:,:(D//2)]
seed = np.random.randint(100)
trainX,testX,trainY,testY = train_test_split(X,Y,random_state = 20,test_size = 0.25)
#LinearSVC doesn't converge
# print("seed: ",seed)
# Lsvc = svm.LinearSVC(class_weight='balanced')
# Lsvc.fit(trainX,trainY)
# pred_trainY = Lsvc.predict(trainX)
# pred_testY = Lsvc.predict(testX)
# print("LSVC_train accuracy rate: {} F1-score: {}".format(Lsvc.score(trainX,trainY),f1_score(trainY,pred_trainY,average = 'weighted')))
# print("LSVC_test accuracy rate: {} F1-score: {}".format(Lsvc.score(testX,testY),f1_score(testY,pred_testY,average = 'weighted')))
# print(metrics.confusion_matrix(trainY, pred_trainY))
# print(metrics.classification_report(trainY,pred_trainY, digits=3))
# print(metrics.confusion_matrix(testY, pred_testY))
# print(metrics.classification_report(testY,pred_testY, digits=3))
#Final test its MSE
# Parameters change according to the labels
svc = svm.SVC(class_weight=None,kernel = 'linear',gamma=0.001,degree=3,C=1)
svc.fit(trainX,trainY)
pred_trainY = svc.predict(trainX)
pred_testY = svc.predict(testX)
print("SVC_train accuracy rate: {} F1-score: {}".format(svc.score(trainX,trainY),f1_score(trainY,pred_trainY,average = 'weighted')))
print("SVC_test accuracy rate: {} F1-score: {}".format(svc.score(testX,testY),f1_score(testY,pred_testY,average = 'weighted')))
print("MSE:{}".format(np.mean((pred_testY-testY)**2)))
joblib.dump(svc,filename+'_'+sys.argv[i+2]+'_svc.pkl')
print(metrics.confusion_matrix(trainY, pred_trainY))
print(metrics.classification_report(trainY,pred_trainY, digits=3))
print(metrics.confusion_matrix(testY, pred_testY))
print(metrics.classification_report(testY,pred_testY, digits=3))
#GridSearchCV
cv = StratifiedShuffleSplit(n_splits=5, test_size=0.25, random_state=0)
parameters = {'kernel':('linear', 'rbf','poly'),'degree':[3,5,7], 'C':[0.001, 0.01, 0.1, 1, 10],'gamma' : [0.001, 0.01, 0.1, 1],'class_weight':['balanced',None]}
clf = GridSearchCV(svm.SVC(max_iter = 5000), parameters,cv=cv)
clf.fit(X,Y)
cv = StratifiedShuffleSplit(n_splits=5, test_size=0.25, random_state=1)
scores_accuracy = cross_val_score(clf.best_estimator_, X, Y, cv=cv)
scores_f1 = cross_val_score(clf.best_estimator_,X,Y,cv=cv,scoring='f1_weighted')
print(sys.argv[i+2])
print(clf.best_estimator_)
print("cv mean:",scores_accuracy.mean())
print("cv std:",scores_accuracy.std())
i += 2
joblib.dump(clf,filename+'_clf.pkl')
#joblib.dump(svc, filename+'_svc0410.pkl')
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Feb 19 10:33:51 2020
@author: eva
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#0:fully on 4:fully 0ff
label = pd.read_csv('data_labels/CIS-PD_Training_Data_IDs_Labels.csv')
step = pd.DataFrame(np.arange(0,1200.1,0.1),columns = ['step'])
step['step'] = step['step'].map(lambda x:str(round(x,1)))
def data_array(subject_id):
measurement_id = label[label['subject_id'] == subject_id]['measurement_id'].values
group = []
for id in measurement_id:
m = pd.read_csv('training_data/'+id+'.csv')
m['step'] = m['Timestamp'].map(lambda x:str(round(x,1)))
m= pd.concat([m,step],sort=False)
m_red = m.groupby('step').mean()
group.append(m_red[["X","Y","Z"]].values)
return group
l = label[label['subject_id'] == 1004]['on_off'].values
per1004 = data_array(1004)
per = np.array(per1004)
measurement_id = label[label['subject_id'] == 1004]['measurement_id'].values
l = label[label['subject_id'] == 1004].loc[0][2]
m = pd.read_csv('training_data/'+measurement_id[0]+'.csv')
m.iloc[:10]
m.iloc[-10:]
m.Y.sum()
m.plot('Timestamp','X')
m.plot('Timestamp','Y')
m.plot('Timestamp','Z')
m['seconds'] = m['Timestamp'].map(lambda x:int(x*10)/10)
m.iloc[:10].groupby('seconds').mean()
xx= pd.concat([m,b],sort=False)
np.arange(0,1200,0.01)
xx_red = xx.groupby('seconds').mean()
m_red = m.groupby('seconds').mean()
def plot(df):
fig,ax = plt.subplots()
ax.plot(df['Timestamp'],df.X,df['Timestamp'],df.Y,df['Timestamp'],df.Z)
plt.legend(('X','Y','Z'))
plt.show()
plot(m_red)
def plot_multi(s=0,n=0):
fig,axs = plt.subplots(n-s,1)
t = []
for i in range(n-s):
measurement_id = label[label['subject_id'] == 1004].loc[s+i][0]
m = pd.read_csv('training_data/'+measurement_id+'.csv')
l = label[label['subject_id'] == 1004].loc[i][2]
m['seconds'] = m['Timestamp'].map(int)+1
m = m.groupby('seconds').mean()
t.extend(m[["X","Y","Z"]].values)
axs[i].plot(m['Timestamp'],m.X,m['Timestamp'],m.Y,m['Timestamp'],m.Z)
axs[i].set_title("{}:{}".format('label',l))
#axs[i].legend(('X','Y','Z'))
fig.tight_layout()
#return t
t = plot_multi(4,7)
t = np.array(t)
plt.plot(range(3600),t[:,0],range(3600),t[:,1],range(3600),t[:,2])
threedee = plt.figure().gca(projection='3d')
threedee.plot(m.Timestamp,m.X,m.Y)
threedee.set_xlabel('X')
threedee.set_ylabel('Y')
threedee.set_zlabel('Z')
plt.show()<file_sep>import pandas as pd
import numpy as np
import scipy.io as sio
import pickle
import sys
label_Train = pd.read_csv('../data_labels/CIS-PD_Training_Data_IDs_Labels.csv')
label_Test = pd.read_csv('../data_labels/CIS-PD_Testing_Data_IDs_Labels.csv')
id_list = label_Train['subject_id'].unique()
c_Train = list(label_Train.groupby('subject_id')['measurement_id'].count())
c_Test = list(label_Test.groupby('subject_id')['measurement_id'].count())
def count(subject_id,data):
l = []
if data == 'Train':
measurement_id = label_Train[label_Train['subject_id'] == subject_id]['measurement_id'].values
for id in measurement_id:
m = pd.read_csv('../training_data/'+id+'.csv')
m['step'] = m['Timestamp'].map(lambda x:int(x*5)/10)
m = m.groupby('step').mean()
l.append(len(m))
else:
measurement_id = label_Test[label_Test['subject_id'] == subject_id]['measurement_id'].values
for id in measurement_id:
m = pd.read_csv('../testing_data/'+id+'.csv')
m['step'] = m['Timestamp'].map(lambda x:int(x*5)/10)
m = m.groupby('step').mean()
l.append(len(m))
return l
def create_tran(n):
counter = 0
#all_tran = {}
for i,id in enumerate(id_list):
cur = 0
for data in ["Train","Test"][:n]:
l = count(id,data)
for j in l:
seq = mat["Psi"][0]["stateSeq"][-1]["z"][0][i][0][cur:cur+j]
cur += j
cur += 1
tran = np.zeros((c_state,c_state))
for ts in range(j-1):
tran[seq[ts]-1][seq[ts+1]-1] += 1
tran = np.where(tran==0,0.1,tran)
tran = tran/tran.sum(axis = 1)
all_tran[counter] = tran
counter += 1
print(id,"done")
def create_HMM(N,D):
for i in range(N):
tran = all_tran[i]
d,v = np.linalg.eig(tran.T)
pos_zero = np.argmin(abs(d-1))
if np.round(d[pos_zero],6) != 1:
print('{} has no eigenvalue equal to 1'.format(i))
p = v[pos_zero]
p /= sum(p)
all_HMM[i,:D] = p
if __name__ == '__main__':
i = 0
while i < len(sys.argv[1:]):
route = sys.argv[1:][i]
mat = sio.loadmat('../result/'+str(route)+'/SamplerOutput.mat')
c_state = (mat["Psi"][0]["F"][-1]).shape[1]
all_tran = {}
if sys.argv[1:][i+1] == 'Test':
create_tran(2)
else:
create_tran(1)
c_Test = [0 for i in c_Test]
N = len(all_tran)
D = all_tran[0].shape[1]
all_HMM = np.zeros((N,2*D))
create_HMM(N,D)
print('Total data seq:{}'.format(N))
print('Length of vectors:{}'.format(2*D))
test_HMM = np.zeros((1,2*D))
train_HMM = np.zeros((1,2*D))
cur = 0
for l in range(len(c_Train)):
all_HMM[cur:c_Train[l]+c_Test[l]+cur,D:] = np.tile(all_HMM[cur:c_Train[l]+c_Test[l]+cur,:D].mean(axis = 0),(c_Train[l]+c_Test[l],1))
train_HMM = np.concatenate((train_HMM,all_HMM[cur:cur+c_Train[l]]))
cur += c_Train[l]
test_HMM = np.concatenate((test_HMM,all_HMM[cur:cur+c_Test[l]]))
cur += c_Test[l]
with open(str(route).replace('/','_')+'_seq_train_HMM.txt', 'wb') as handle:
pickle.dump(train_HMM, handle)
with open(str(route).replace('/','_')+'_seq_test_HMM.txt', 'wb') as handle:
pickle.dump(test_HMM, handle)
i += 2
'''
for i in range(len(all_tran)):
if i % 50 == 0:
print(i,all_tran[i])
'''
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon May 4 22:25:12 2020
@author: eva
"""
import pandas as pd
import numpy as np
import scipy.io as sio
import pickle
import sys
from sklearn.externals import joblib
import os
label_Train = pd.read_csv('data_labels/CIS-PD_Training_Data_IDs_Labels.csv')
label_Test = pd.read_csv('data_labels/CIS-PD_Testing_Data_IDs_Labels.csv')
id_list = label_Train['subject_id'].unique()
c_Train = list(label_Train.groupby('subject_id')['measurement_id'].count())
c_Test = list(label_Test.groupby('subject_id')['measurement_id'].count())
if __name__ == '__main__':
fn = sys.argv[1]
filename,ext = os.path.splitext(fn)
with open(fn, 'rb') as handle:
testing_data = pickle.loads(handle.read())
model = joblib.load(sys.argv[2])
a = model.predict(testing_data)
with open("dyskinesia.txt",'wb') as fn:
pickle.dump(a,fn)
<file_sep># INF552_project
## Introduction
Wearable devices enable us to track human behaviors continuously. Recognizing the connection between continuous sensor data and human actions may help the physicians better understand the conditions of patients. In this report, the Hidden Markov Model is utilized to extract the patterns of continuous accelerometer sequences and the extracted features are proved to be helpful in predicting Parkinson’s Disease patients’ medical states. I directly use the raw data provided and the accuracy rates are around 60% for predicting medication states and classifying severity of tremor and dyskinesia. Additional analysis and data preprocessing on the human sensory data may further recognize the human behavior patterns and increase the classification accuracy. Therefore, it may become feasible for doctors to use sensor data recorded by the portable devices as a support to prescribe the medicine.
## Model
As we were provided with the continuous collection of sensor data from wearable devices, there are more than hundred thousand timestamps in each individual file. Instead of training machine/deep learning on the dataset directly, it may be more practical and efficient to analyze data after extracting some patterns of data.
I utilized the Hidden Markov Model (HMM) to help discover the potential patterns of human behaviors. Then, embedded the HMM before running classification and regression model on the data.
<file_sep>import pandas as pd
import numpy as np
from sklearn.preprocessing import scale
import scipy.io as sio
label_Train = pd.read_csv('data_labels/CIS-PD_Training_Data_IDs_Labels.csv')
label_Test = pd.read_csv('data_labels/CIS-PD_Testing_Data_IDs_Labels.csv')
#Return a single wo minutes data
def id_single_data(subject_id,i):
measurement_id = label_Train[label_Train['subject_id'] == subject_id]['measurement_id'].values
id = measurement_id[i]
m = pd.read_csv('training_data/'+id+'.csv')
m['step'] = m['Timestamp'].map(lambda x:int(x*5)/10)
m = m.groupby('step').mean()
return m[["X","Y","Z"]].values
#Return an array of each subject_id with or without scaling within each data points
#seperate data by [0,0,0]
def concatData(subject_id,z = False):
measurement_id = label_Train[label_Train['subject_id'] == subject_id]['measurement_id'].values
group = []
for id in measurement_id:
m = pd.read_csv('training_data/'+id+'.csv')
m['step'] = m['Timestamp'].map(lambda x:int(x*5)/10)
m = m.groupby('step').mean()
if not z:
group.extend(m[["X","Y","Z"]].values)
else:
group.extend(scale(m[["X","Y","Z"]].values,axis = 0))
group.append([0,0,0])
measurement_id = label_Test[label_Test['subject_id'] == subject_id]['measurement_id'].values
for id in measurement_id:
m = pd.read_csv('testing_data/'+id+'.csv')
m['step'] = m['Timestamp'].map(lambda x:int(x*5)/10)
m = m.groupby('step').mean()
if not z:
group.extend(m[["X","Y","Z"]].values)
else:
group.extend(scale(m[["X","Y","Z"]].values,axis = 0))
group.append([0,0,0])
return np.array(group)
#Return an array of each subject with scaling within each person
#First scaling, then add [0,0,0] to split the data
def zscoreAmongperson(subject_id):
measurement_id = label_Train[label_Train['subject_id'] == subject_id]['measurement_id'].values
l = []
group = []
for id in measurement_id:
m = pd.read_csv('training_data/'+id+'.csv')
m['step'] = m['Timestamp'].map(lambda x:int(x*5)/10)
m = m.groupby('step').mean()
l.append(len(m))
group.extend(m[["X","Y","Z"]].values)
#group.append([0,0,0])
measurement_id = label_Test[label_Test['subject_id'] == subject_id]['measurement_id'].values
for id in measurement_id:
m = pd.read_csv('testing_data/'+id+'.csv')
m['step'] = m['Timestamp'].map(lambda x:int(x*5)/10)
m = m.groupby('step').mean()
l.append(len(m))
group.extend(m[["X","Y","Z"]].values)
#group.append([0,0,0])
group = scale(np.array(group),axis = 0)
cur = 0
for i in l:
cur += i
group = np.insert(group,cur,np.array([[0,0,0]]),axis = 0)
cur += 1
return np.array(group)
def createArray(l):
noScale = []
Scaledatapoints = []
Scaleperson = []
for i,id in enumerate(l):
noScale.append(concatData(id,False))
np.savetxt('outputA_Total/'+str(id_list[i])+'.csv',noScale[-1])
#sio.savemat('outputA_Total/'+str(id_list[i])+'.mat',{'data':noScale[-1]})
Scaledatapoints.append(concatData(id,True))
#sio.savemat('outputB_Total/'+str(id_list[i])+'.mat',{'data':Scaledatapoints[-1]})
np.savetxt('outputB_Total/'+str(id_list[i])+'.csv',Scaledatapoints[-1])
Scaleperson.append(zscoreAmongperson(id))
#sio.savemat('outputC_Total/'+str(id_list[i])+'.mat',{'data':Scaleperson[-1]})
np.savetxt('outputC_Total/'+str(id_list[i])+'.csv',Scaleperson[-1])
print(id," done!")
return np.array(noScale),np.array(Scaledatapoints),np.array(Scaleperson)
id_list = label_Train['subject_id'].unique()
A,B,C = createArray(id_list)
#np.savetxt(str(id_list[0])+'.csv',A[0])
#np.savetxt(str(id_list[0])+'_B.csv',B[0])
#np.savetxt(str(id_list[0])+'_C.csv',C[0])
#
#
#sio.savemat(str(id_list[0])+'_B.mat', {'mydata': A[0]})
#
#A[0][:10]
#B[0][:10]
#C[0].sum(axis = 0)
<file_sep>import pandas as pd
import numpy as np
import scipy.io as sio
import pickle
import sklearn.svm as svm
from sklearn.externals import joblib
from sklearn.model_selection import GridSearchCV,RandomizedSearchCV,train_test_split,cross_val_score,ShuffleSplit,StratifiedShuffleSplit
import sys
import os
from sklearn.metrics import f1_score
from sklearn.linear_model import LinearRegression,Lasso,Ridge
from sklearn import metrics
label = pd.read_csv('../data_labels/CIS-PD_Training_Data_IDs_Labels.csv')
#trainY = np.array(label['dyskinesia'])
# 'on_off', 'dyskinesia', 'tremor'
if __name__ == '__main__':
i = 0
while i < len(sys.argv[1:]):
fn = sys.argv[i+1]
trainY = np.array(label[sys.argv[i+2]])
with open(fn, 'rb') as handle:
all_presentations = pickle.loads(handle.read())
filename,ext = os.path.splitext(fn)
not_nan = ~np.isnan(trainY)
X = all_presentations[1:][not_nan]
Y = trainY[not_nan]
D = X.shape[1]
#Test if concatenating mean value within each patient is helpful
#X = X[:,:(D//2)]
#Final test its MSE
seed = np.random.randint(100)
trainX,testX,trainY,testY = train_test_split(X,Y,random_state = 20,test_size = 0.25)
print("seed: ",seed)
# Parameters change according to the labels
lasso = Lasso(alpha=0.005,max_iter=5000)
lasso.fit(trainX,trainY)
print("lasso_mse:",np.mean((lasso.predict(testX)-testY)**2))
#GridSearchCV
parameters = {'alpha':[0.005, 0.01, 0.1, 1, 10]}
lr = LinearRegression()
cv = StratifiedShuffleSplit(n_splits=5, test_size=0.25, random_state=0)
clf_lasso=GridSearchCV(Lasso(max_iter=5000),parameters,cv=cv)
clf_ridge=GridSearchCV(Ridge(max_iter=5000),parameters,cv=cv)
clf_lasso.fit(X,Y)
clf_ridge.fit(X,Y)
print(sys.argv[i+2])
cv = StratifiedShuffleSplit(n_splits=5, test_size=0.25, random_state=1)
scores_accuracy = cross_val_score(clf_lasso.best_estimator_, X, Y, cv=cv,scoring='neg_mean_squared_error')
print("lasso")
print(clf_lasso.best_estimator_)
print(scores_accuracy.mean())
print(scores_accuracy.std())
scores_accuracy = cross_val_score(clf_ridge.best_estimator_, X, Y, cv=cv,scoring='neg_mean_squared_error')
print("ridge")
print(clf_ridge.best_estimator_)
print(scores_accuracy.mean())
print(scores_accuracy.std())
i += 2
| 409f59fd27bac40dbff55c4da801d7c4934cd8cf | [
"Markdown",
"Python"
] | 7 | Python | Evakung-github/INF552_project | efeccce1d6917fe2d82a59c37c7a561fbaa035af | bc32e8a9497fa4d1026288f7074c4a3f8ce25519 | |
refs/heads/master | <file_sep>(function ($) {
var Brightcove = {
init: function () {
$('.brightcove_widget_refresh').on("click", function(e){
var that = this;
$(that).find('.fa').addClass('fa-spin');
$('.brightcove_widget select').load($(this).attr('href'), function () {
$(that).find('.fa').removeClass('fa-spin');
});
e.preventDefault();
});
}
};
$(function () {
Brightcove.init();
});
})(window.jQuery || django.jQuery);
<file_sep>from django.db import models
from django.utils.translation import ugettext_lazy as _
from .models import BrightcoveItems
from .widgets import BrightcoveIntegerField
class BrightcoveField(models.ForeignKey):
"""
Custom manager that inherits form the ForeignKey default django field, used to easily set a field up in order to
relate a Model the the BrightCoveItems model and widget.
i.e.::
class MyModel(Model):
my_field = BrightcoveField()
"""
def __init__(self, null=True, blank=True, **kwargs):
"""Overwites default settings to setup the relationship with the BrightcoveItems model"""
kwargs['verbose_name'] = kwargs.get('verbose_name', _("Brightcove"))
kwargs['null'] = null
kwargs['blank'] = blank
# If null is set to True we can't use SET_NULL as default
if null:
default_on_delete = models.PROTECT
else:
default_on_delete = models.SET_NULL
kwargs['on_delete'] = kwargs.get('on_delete', default_on_delete)
to_field = kwargs.pop('to_field', 'brightcove_id')
rel_class = models.ManyToOneRel
db_constraint = True
to = kwargs.pop('to', BrightcoveItems)
super(BrightcoveField, self).__init__(to, to_field, rel_class, db_constraint, **kwargs)
def save_form_data(self, instance, data):
#when data is u'' and form allow te be null, we need to make sure
#it will not blow up the page
if data:
video = BrightcoveItems.objects.get(pk=data)
else:
video = None
super(BrightcoveField, self).save_form_data(instance, video)
def formfield(self, **kwargs):
"""Overwites default formfield to trigger the custom Brightcove choicefield widget"""
defaults = {
'form_class': BrightcoveIntegerField,
}
defaults.update(kwargs)
return super(models.ForeignKey, self).formfield(**defaults)
def south_field_triple(self):
"""Provide a suitable description of this field for South."""
from south.modelsinspector import introspector
args, kwargs = introspector(self)
return 'django.db.models.fields.related.ForeignKey', args, kwargs
<file_sep># -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'BrightcoveItems'
db.create_table(u'django_brightcove_brightcoveitems', (
('brightcove_id', self.gf('django.db.models.fields.BigIntegerField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
('video_still_URL', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
('thumbnail_URL', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
('short_description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('long_description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('length', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)),
('link_URL', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
('plays_total', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
('creation_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('published_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
))
db.send_create_signal(u'django_brightcove', ['BrightcoveItems'])
def backwards(self, orm):
# Deleting model 'BrightcoveItems'
db.delete_table(u'django_brightcove_brightcoveitems')
models = {
u'django_brightcove.brightcoveitems': {
'Meta': {'object_name': 'BrightcoveItems'},
'brightcove_id': ('django.db.models.fields.BigIntegerField', [], {'primary_key': 'True'}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'length': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'link_URL': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'long_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'plays_total': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'published_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'thumbnail_URL': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'video_still_URL': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['django_brightcove']<file_sep>from django.conf import settings
from brightcove.api import Brightcove
from .models import BrightcoveItems
class BrightcoveApi():
"""Class managing communication with the Brightcove API though the brightcove app."""
token = ''
connector = None
def __init__(self, token=''):
if token:
self.token = token
if not self.token:
self.token = getattr(settings, 'BRIGHTCOVE_TOKEN', None)
self.connector = Brightcove(self.token)
def get_by_id(self, brightcove_id):
video = self.connector.find_video_by_id(brightcove_id)
if video:
return self._save_item(video)
return None
def _get_list(self):
return self.connector.find_all_videos()
def synchronize_list(self):
"""Synchronizes the list of videos form a brightcove account with the BrightcoveItem model."""
items = self._get_list()
existing_ids = []
for item in items.items:
self._save_item(item)
existing_ids.append(item.id)
BrightcoveItems.objects.exclude(brightcove_id__in=existing_ids).delete()
def _save_item(self, item):
brightcove_item, created = BrightcoveItems.objects.get_or_create(brightcove_id=item.id)
brightcove_item.name = item.name
brightcove_item.video_still_URL = item.videoStillURL
brightcove_item.thumbnail_URL = item.thumbnailURL
brightcove_item.short_description = item.shortDescription
brightcove_item.long_description = item.longDescription
brightcove_item.length = item.length
brightcove_item.link_URL = item.linkURL
brightcove_item.plays_total = item.playsTotal
brightcove_item.creation_date = item.creationDate
brightcove_item.published_date = item.publishedDate
brightcove_item.save()
return brightcove_item
<file_sep># -*- coding: utf-8 -*-
"""
This package is for Django migrations. South migrations can be found in the `south_migrations`
package.
"""
from __future__ import unicode_literals
SOUTH_ERROR_MESSAGE = """\n
To enable South migrations for this app customize the `SOUTH_MIGRATION_MODULES` setting in your
settings file such as the following:
SOUTH_MIGRATION_MODULES = {
'django_brightcove': 'django_brightcove.south_migrations',
}
"""
try:
from django.db import models, migrations
except ImportError:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured(SOUTH_ERROR_MESSAGE)
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='BrightcoveItems',
fields=[
('brightcove_id', models.BigIntegerField(serialize=False, verbose_name='Brightcove id', primary_key=True)),
('name', models.CharField(max_length=255, null=True, verbose_name='Name', blank=True)),
('video_still_URL', models.CharField(max_length=255, null=True, verbose_name='Video still url', blank=True)),
('thumbnail_URL', models.CharField(max_length=255, null=True, verbose_name='Thumbnail url', blank=True)),
('short_description', models.TextField(null=True, verbose_name='Short description', blank=True)),
('long_description', models.TextField(null=True, verbose_name='Short description', blank=True)),
('length', models.IntegerField(null=True, verbose_name='Length', blank=True)),
('link_URL', models.CharField(max_length=255, null=True, verbose_name='Link url', blank=True)),
('plays_total', models.PositiveIntegerField(null=True, verbose_name='Number of plays', blank=True)),
('creation_date', models.DateTimeField(null=True, verbose_name='Creation date', blank=True)),
('published_date', models.DateTimeField(null=True, verbose_name='Published date', blank=True)),
],
options={
},
bases=(models.Model,),
),
]
<file_sep>import datetime
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class BrightcoveItems(models.Model):
"""
This class is storing the brightcove fields and managing the generic relationship
"""
brightcove_id = models.BigIntegerField(verbose_name=_('Brightcove id'), primary_key=True)
name = models.CharField(verbose_name=_('Name'), max_length=255, null=True, blank=True)
video_still_URL = models.CharField(verbose_name=_('Video still url'), max_length=255, null=True, blank=True)
thumbnail_URL = models.CharField(verbose_name=_('Thumbnail url'), max_length=255, null=True, blank=True)
short_description = models.TextField(verbose_name=_('Short description'), null=True, blank=True)
long_description = models.TextField(verbose_name=_('Short description'), null=True, blank=True)
length = models.IntegerField(verbose_name=_('Length'), null=True, blank=True)
link_URL = models.CharField(verbose_name=_('Link url'), max_length=255, null=True, blank=True)
plays_total = models.PositiveIntegerField(verbose_name=_('Number of plays'), null=True, blank=True)
creation_date = models.DateTimeField(verbose_name=_('Creation date'), null=True, blank=True)
published_date = models.DateTimeField(verbose_name=_('Published date'), null=True, blank=True)
def __str__(self):
if self.name:
return self.name
return self.brightcove_id
@property
def length_seconds(self):
length = datetime.timedelta(milliseconds=self.length)
return ':'.join(str(length).split('.')[0:1])
<file_sep>from django.core import exceptions
from django.forms import IntegerField, NumberInput
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from .models import BrightcoveItems
from .utils import BrightcoveApi
class BrightcoveNumberInput(NumberInput):
"""
Overwrites the default Select widget to add the brightcove specific magic.
"""
choices = []
def render(self, name, value, attrs=None):
item = None
if value:
try:
item = BrightcoveItems.objects.get(pk=value)
except BrightcoveItems.DoesNotExist:
pass
context = {'select': self.render_input(name, value, attrs), 'pk': value, 'item': item}
return render_to_string('select_widget.html', context)
class Media:
css = {
'all': ('brightcove/css/brightcove.css',
'//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css',)
}
js = ('//admin.brightcove.com/js/APIModules_all.js', 'brightcove/js/brightcove.js',
'//admin.brightcove.com/js/BrightcoveExperiences.js',)
def render_input(self, name, value, attrs=None):
return super(BrightcoveNumberInput, self).render(name, value, attrs)
class BrightcoveIntegerField(IntegerField):
"""
Overwrites the default IntegerField widget to force the custom widget to be displayed.
"""
widget = BrightcoveNumberInput
def __init__(self, max_value=None, min_value=None, *args, **kwargs):
kwargs.pop('limit_choices_to', None)
super(BrightcoveIntegerField, self).__init__(max_value, min_value,
*args, **kwargs)
def clean(self, value):
value = super(BrightcoveIntegerField, self).clean(value)
if not self._has_changed(self.initial, value):
return value
api = BrightcoveApi()
try:
api.get_by_id(value)
except:
raise exceptions.ValidationError(_("The id you have passed doesn't seem to exist in the Brightcove \
database."))
return value
<file_sep>from django.conf.urls import patterns, url
from .views import refresh_item_list
urlpatterns = patterns(
'',
url(r'^brightcove-refresh-item-list/(?P<pk>[\w-]+)/$', refresh_item_list, name='brightcove-refresh-item-list'),
)
<file_sep>#################
Django Brightcove
#################
Manages the integration of brightcove videos in a django project. It extends the the Brightcove library developed by <NAME>: https://pypi.python.org/pypi/brightcove/0.2
It basically add a form field to easily integrate brightcove account video in the django admin or any form. And adds a template tag to fast integrate a brightcove video in a template.
*******
Install
*******
It is strongly recommanded to install this theme from GIT with PIP onto you project virtualenv.
From PyPi
.. code-block:: shell-session
pip install django-brightcove
From Github
.. code-block:: shell-session
https://github.com/RevSquare/django-brightcove#egg=django-brightcove
*****
Setup
*****
Before starting, you will need a Brightcove API token in order to connect to brightcove: http://docs.brightcove.com/en/video-cloud/media/guides/managing-media-api-tokens.html
The first step is to add the app in your installed apps list in settings.py
.. code-block:: python
INSTALLED_APPS = (
...
'django_brightcove'
...
)
The you will need to declare the loaders you want to add in your settings.py file
.. code-block:: python
BRIGHTCOVE_TOKEN = 'YOUR_TOKEN..'
Finally you will need to add the django-brightcove urls to your Root URLCONF
.. code-block:: python
urlpatterns = patterns('',
...
(r'^django_brightcove', include('django_brightcove.urls')),
...
)
*********************************
Add a Brightcove video to a model
*********************************
Simply add the Brightcove field manager to it.
.. code-block:: python
from django.db import models
from django_brightcove.fields import BrightcoveField
class MyModel(models.Model):
brightcove = BrightcoveField()
*************
Template tags
*************
You can easily insert a video with a built in template tag.
The first step is to list your brightcove player id and key in your settings file.
.. code-block:: python
BRIGHTCOVE_PLAYER = {
'default': {
'PLAYERID': 'a_default_player_id',
'PLAYERKEY': 'a_default_player_key',
},
'single': {
'PLAYERID': 'another_player_id',
'PLAYERKEY': 'another_player_key',
},
}
Then within your template, simply call for the player tag and pass your video id and eventualy a specific brightcove player type. By default the tag with the key set as 'default' in settings.BRIGHTCOVE_PLAYER dictionary.
.. code-block:: html
{% load brightcove %}
<div class="player">{% brightcove_player object.brightcove_id player='single' %}</div>
You can also pass height and width to the template tag, ie:
.. code-block:: html
{% load brightcove %}
<div class="player">{% brightcove_player object.brightcove_id width=480 height=270 %}</div>
You will also need to add the Brightcove javascript library
.. code-block:: html
<script type="text/javascript" src="http://admin.brightcove.com/js/BrightcoveExperiences.js"></script>
************
Contribution
************
Please feel free to contribute. Any help and advices are much appreciated.
*****
LINKS
*****
Development:
https://github.com/RevSquare/django-brightcove
Package:
https://pypi.python.org/pypi/django-brightcove
<file_sep>from django.http import HttpResponse, Http404
def refresh_item_list(request, pk):
"""Updates the select of brightcove items in a form"""
if not request.is_ajax():
raise Http404
return HttpResponse(pk)
<file_sep>from django import template
from django.conf import settings
register = template.Library()
@register.inclusion_tag('tags/brightcove_player.html',
takes_context=True)
def brightcove_player(context, player_id, *args, **kwargs):
"""
This tags generate the brightcove object code. It required the
BRIGHTCOVE_PLAYER constant to be properly setup in
the django settings.
"""
if not settings.BRIGHTCOVE_PLAYER:
raise Exception('BRIGHTCOVE_PLAYER constant is missing from your settings.')
player = kwargs.get('player', 'default')
try:
player = settings.BRIGHTCOVE_PLAYER[player]
except:
raise KeyError('%s player type is missing from the BRIGHTCOVE_PLAYER constant' % player)
try:
context['playerID'] = player['PLAYERID']
context['playerKey'] = player['PLAYERKEY']
except:
raise KeyError('%s player type from the BRIGHTCOVE_PLAYER constant is not properly configured' % player)
context['width'] = kwargs.get('width', 480)
context['height'] = kwargs.get('height', 270)
context['bgcolor'] = kwargs.get('bgcolor', '#FFFFFF')
context['isVid'] = kwargs.get('isVid', True)
context['isUI'] = kwargs.get('isUI', True)
context['dynamicStreaming'] = kwargs.get('dynamicStreaming', True)
context['player_id'] = player_id
return context
| c0861830b98026c49cb597772cf344c7c9d1e19e | [
"JavaScript",
"Python",
"reStructuredText"
] | 11 | JavaScript | ixc/django-brightcove | d70b2ce2d19c53161f390c6ea2be258b692b7536 | cb087bab6ca957a67a76af0d0aa23dd919b6c1a9 | |
refs/heads/main | <repo_name>lyqaiym/assemblydemo<file_sep>/app/src/main/cpp/native-lib.cpp
#include <jni.h>
#include <string>
extern "C" {
extern int arm_add(int a, int b);
extern int arm_sub(int a, int b);
extern void strcopy(char *d, const char *s);
}
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_assemblydemo_MainActivity_addTest(
JNIEnv *env,
jobject /* this */, jint a, jint b) {
int i1 = arm_add(a, b);
char *dest = (char *) malloc(11);
sprintf(dest, "add=%d", i1);
return env->NewStringUTF(dest);
}
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_assemblydemo_MainActivity_subTest(JNIEnv *env, jobject thiz, jint a, jint b) {
int i1 = arm_sub(a, b);
char *dest = (char *) malloc(11);
sprintf(dest, "sub=%d", i1);
return env->NewStringUTF(dest);
}
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_assemblydemo_MainActivity_strTest(JNIEnv *env, jobject thiz) {
char *dest = (char *) malloc(200);
const char *srcstr = "First string - source";
char dstchar[] = "Second string - destination";
strcopy(dstchar, srcstr);
sprintf(dest, "str=%s", dstchar);
return env->NewStringUTF(dest);
} | 74b1557c10ff80998707f1688a660d5a4a0f499e | [
"C++"
] | 1 | C++ | lyqaiym/assemblydemo | 921774212fe1c35f954ab2a9c516d705ca9e1499 | b7f8f0202c256b14fd2c67d022c8a1f18887d921 | |
refs/heads/main | <repo_name>gcostaa/devapiss<file_sep>/api/get.php
<?php
require_once("app/controller/get/request.php");
#validates if the get parameter is set
if(empty($_GET["id"])){
$msg = "Enter the credential id. Example: get.php?id=";
echo "<script type='text/javascript'>alert('$msg');</script>";
}else{
#executes the get method of the request.php class
$id = $_GET["id"];
get($id);
}
?>
<file_sep>/api/README.txt
Author: <NAME>
Date: 2021/04/10
Description: Integration with the senhasegura API for credentials password
query (version 1.0)
How to use:
- File config.json
In the file you must insert your access keys generated through the tool.
The keys are: Consumer Key and oAUTH Token
- Request
After configuring the config.json file, just call the URL
https://IP_OR_DNS/api/get.php?id=credential_id
or
curl -X "GET" https://server/api/get.php?id=2<file_sep>/api/app/controller/get/request.php
<?php
#get local directory
if(empty($_SERVER["PWD"])){
require_once $_SERVER["DOCUMENT_ROOT"].'/api/app/model/keys/accessKeys.php';
require_once $_SERVER["DOCUMENT_ROOT"].'/api/app/view/view.php';
}else{
require_once $_SERVER["PWD"].'/app/model/keys/accessKeys.php';
require_once $_SERVER["PWD"].'/app/view/view.php';
}
function get(string $credentialId){
try{
/*
The AcessKeys class will obtain the access keys defined
in config.json and deliver the values for the URL request
*/
$keys = new AccessKeys();
$url = "https://".$keys->getValtIp()."/iso/coe/senha/".$credentialId."?oauth_consumer_key=".$keys->getOauthConsumerKey().
"&oauth_token=".$keys->getOauthToken()."&oauth_signature=-";
#initialize the method curl
$request = curl_init();
#config URL
curl_setopt($request, CURLOPT_URL, $url);
#get response
curl_setopt($request,CURLOPT_RETURNTRANSFER,1);
#skip certificate
curl_setopt($request, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE);
#send request
$response = curl_exec($request);
/*
The View class will return the password values, device in the
form of text on the screen
*/
$view = new View($response);
#close connection
curl_close($request);
} catch(Exception $e){
echo("Erro ".$e->getMessage()."\n");
}
}
<file_sep>/api/app/model/keys/accessKeys.php
<?php
class AccessKeys{
private $oauth_consumer_key = "";
private $oauth_signature = "";
private $oauth_token = "";
private $vaultIP = "";
function __construct()
{
#get values from the configuration file
$json = file_get_contents($_SERVER['DOCUMENT_ROOT']."/api/config.json");
$data = json_decode($json,true);
$this->oauth_consumer_key = $data["keys"]["oauth_consumer_key"];
$this->oauth_signature = $data["keys"]["oauth_signature"];
$this->oauth_token = $data["keys"]["oauth_token"];
$this->vaultIP = $data["keys"]["vault"];
}
public function getOauthConsumerKey(){
$key = $this->oauth_consumer_key;
if (empty($key)){
echo("Consumer key is not configured");
}else{
return $key;
}
}
public function getOauthToken(){
$key = $this->oauth_token;
if (empty($key)){
echo("Token key is not configured");
}else{
return $key;
}
}
public function getOauthSignature(){
$key = $this->oauth_signature;
if (empty($key)){
echo("Signature key is not configured");
}else{
return $key;
}
}
public function getValtIp(){
$key = $this->vaultIP;
if (empty($key)){
echo("Vault IP is not configured");
}else{
return $key;
}
}
}
?><file_sep>/api/app/view/view.php
<?php
class View{
private $response = [];
private $status;
function __construct($responseRequest)
{
#get response from senhasegura API request and convert to array
$this->response = json_decode($responseRequest,true);
#get status code
$this->status = $this->getHttpCode($this->response);
#displays the values on the screen
$this->display($this->response,$this->status);
}
public function display(Array $response,$statusCode){
if($statusCode == 200){
echo (PHP_EOL."KEY VALUES"."<br><br>".PHP_EOL);
echo("Device.... ".$response["senha"]["hostname"]
."-".$response["senha"]["ip"]."<br>".PHP_EOL);
echo("Credential.... ".$response["senha"]["username"]."<br>".PHP_EOL);
echo("Password.... ".$response["senha"]["senha"]."".PHP_EOL);
}else{
echo ($response["response"]["mensagem"]);
}
}
private function getHttpCode(Array $response){
$code = $response["response"]["status"];
return $code;
}
}
?> | dc5040b25ffb1166e4dbf484e870e255a737fe6f | [
"Text",
"PHP"
] | 5 | PHP | gcostaa/devapiss | d31e1a96702d96e93188713280255260935ba152 | 6bad8b8363d2856798b69560933bf54258e31352 | |
refs/heads/master | <repo_name>menstartup/manhjj<file_sep>/src/app/manh1/manh1.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-manh1',
templateUrl: './manh1.component.html',
styleUrls: ['./manh1.component.css']
})
export class Manh1Component implements OnInit {
constructor() { }
ngOnInit() {
}
}
<file_sep>/src/app/book/book.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
data = [
{
id: 1,
img: 'https://images.pexels.com/photos/2246822/pexels-photo-2246822.jpeg?auto=compress&cs=tinysrgb&h=650&w=940',
title: 'item 1'
},
{
id: 2,
img: 'https://images.pexels.com/photos/2223082/pexels-photo-2223082.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260',
title: 'item 2'
},
{
id: 3,
img: 'https://images.pexels.com/photos/2246822/pexels-photo-2246822.jpeg?auto=compress&cs=tinysrgb&h=650&w=940',
title: 'item 3'
},
{
id: 4,
img: 'https://images.pexels.com/photos/2246822/pexels-photo-2246822.jpeg?auto=compress&cs=tinysrgb&h=650&w=940',
title: 'item 4'
},
]
updateData = [
{
id: 1,
img: 'https://images.pexels.com/photos/2246822/pexels-photo-2246822.jpeg?auto=compress&cs=tinysrgb&h=650&w=940',
title: 'item 1'
},
{
id: 2,
img: 'https://images.pexels.com/photos/2223082/pexels-photo-2223082.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260',
title: 'item2'
},
{
id: 3,
img: 'https://images.pexels.com/photos/2246822/pexels-photo-2246822.jpeg?auto=compress&cs=tinysrgb&h=650&w=940',
title: 'item 3'
},
{
id: 4,
img: 'https://images.pexels.com/photos/2246822/pexels-photo-2246822.jpeg?auto=compress&cs=tinysrgb&h=650&w=940',
title: 'item 4'
},
{
id: 5,
img: 'https://images.pexels.com/photos/2246822/pexels-photo-2246822.jpeg?auto=compress&cs=tinysrgb&h=650&w=940',
title: 'item 5'
},
{
id: 6,
img: 'https://images.pexels.com/photos/2246822/pexels-photo-2246822.jpeg?auto=compress&cs=tinysrgb&h=650&w=940',
title: 'item 6'
},
{
id: 7,
img: 'https://images.pexels.com/photos/2246822/pexels-photo-2246822.jpeg?auto=compress&cs=tinysrgb&h=650&w=940',
title: 'item 7'
},
{
id: 8,
img: 'https://images.pexels.com/photos/2246822/pexels-photo-2246822.jpeg?auto=compress&cs=tinysrgb&h=650&w=940',
title: 'item 8'
},
]
constructor() { }
ngOnInit() {
}
}
| 9e117678dc28cbf43aea3ac18439697313e53e74 | [
"TypeScript"
] | 2 | TypeScript | menstartup/manhjj | c8c1965c7449e25d29481babc38e5703d271aa95 | 2cd232cd768f7836597d85a3ad03577476d242bb | |
refs/heads/master | <file_sep>Esta aplicación, desarrollada en [JavaFX ](https://es.wikipedia.org/wiki/JavaFX) para la asignatura de [Interfaces Persona Computador](http://www.upv.es/pls/oalu/sic_asi.Busca_Asi?p_codi=11556&p_caca=act&P_IDIOMA=c&p_vista=), permite hacer un seguimiento de la actividad deportiva a partir de ficheros [GPX](https://es.wikipedia.org/wiki/GPX).
<file_sep>/*
* 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 models.charts;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import jgpx.model.analysis.TrackData;
/**
*
* @author Rafa
*/
public class LineChartTask extends ChartTask {
public LineChartTask(TrackData td, Abscissa abscissa) {
super(td, abscissa);
}
@Override
XYChart<Number, Number> chartInstance() {
NumberAxis x = new NumberAxis();
NumberAxis y = new NumberAxis();
LineChart chart = new LineChart(x, y);
chart.setCreateSymbols(false);
return chart;
}
}
<file_sep>/*
* 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 models.charts.sources;
import jgpx.model.analysis.Chunk;
import models.charts.ChartSource;
/**
*
* @author Rafa
*/
public class SpeedChartSource extends ChartSource {
public SpeedChartSource() {
super("Velocidad (km/h)");
}
@Override
public double getAbscissaValue(Chunk chunk) {
return chunk.getSpeed();
}
}
<file_sep>/*
* 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 models.charts;
import java.util.Iterator;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.chart.PieChart;
import jgpx.model.analysis.Chunk;
import jgpx.model.analysis.TrackData;
/**
*
* @author Rafa
*/
public class HeartRateZonesChartManager {
private PieChart chart;
private ObservableList<PieChart.Data> heartRateZonesData;
private TrackData trackData;
private int maxHeartRate;
public HeartRateZonesChartManager(PieChart chart) {
this.chart = chart;
heartRateZonesData = FXCollections.observableArrayList();
chart.setData(heartRateZonesData);
maxHeartRate = 0;
}
public void update(TrackData trackData) {
this.trackData = trackData;
if (maxHeartRate <= 0) return;
long[] timeCounter = {
0L, 0L, 0L, 0L, 0L
};
double[] limits = {
0.6d, 0.7d, 0.8d, 0.9d, 1.d
};
String[] limitsNames = {
"Z1 Recuperación", "Z2 Fondo", "Z3 Tempo",
"Z4 Umbral", "Z5 Anaeróbico"
};
for (Iterator<Chunk> it = trackData.getChunks().iterator(); it.hasNext();) {
Chunk c = it.next();
for (int i = 0; i < limits.length; i++) {
if (c.getAvgHeartRate() < limits[i] * maxHeartRate) {
timeCounter[i] += c.getDuration().getSeconds();
}
}
}
heartRateZonesData.clear();
for (int i = 0; i < timeCounter.length; i++) {
heartRateZonesData.add(new PieChart.Data(limitsNames[i], timeCounter[i]));
}
}
public void setMaxHeartRate(int maxHeartRate) {
this.maxHeartRate = maxHeartRate;
update(trackData);
}
}
<file_sep>/*
* 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 controllers;
import java.net.URL;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import models.Workout;
/**
* FXML Controller class
*
* @author Rafa
*/
public class SummaryController implements Initializable, ChangeListener<LocalDate> {
List<Workout> workouts;
@FXML
private DatePicker initialDate;
@FXML
private DatePicker finalDate;
@FXML
private Label distance;
@FXML
private Label duration;
@FXML
private Label averageSpeed;
@FXML
private BarChart<?, ?> summaryChart;
@FXML
private ComboBox<String> groupBy;
@FXML
private Label workoutsAmount;
enum GroupingCriteria {
DAY, MONTH, YEAR
};
@Override
public void initialize(URL url, ResourceBundle rb) {
initialDate.getEditor().setDisable(true);
initialDate.getEditor().setStyle("-fx-opacity: 1.0;");
finalDate.getEditor().setDisable(true);
finalDate.getEditor().setStyle("-fx-opacity: 1.0;");
groupBy.getItems().add("días");
groupBy.getItems().add("meses");
groupBy.getItems().add("años");
groupBy.getSelectionModel().select(0);
}
public void init(List<Workout> workouts) {
this.workouts = workouts;
setupUI();
initialDate.valueProperty().addListener(this);
finalDate.valueProperty().addListener(this);
}
void setupUI() {
setupLabels();
setupChart();
}
public void setupLabels() {
if (initialDate.getValue() == null || finalDate.getValue() == null) {
initialDate.setValue(getFirstWorkout().getTrackData().getStartTime().toLocalDate());
finalDate.setValue(getLastWorkout().getTrackData().getStartTime().toLocalDate());
}
double totalDistance = 0.d;
double totalAverageSpeed = 0.d;
Duration totalDuration = Duration.ZERO;
int workoutsAmountCounter = 0;
for (Workout w : filterWorkouts()) {
if (initialDate.getValue().compareTo(w.getTrackData().getStartTime().toLocalDate()) <= 0
&& finalDate.getValue().compareTo(w.getTrackData().getEndTime().toLocalDate()) >= 0) {
workoutsAmountCounter++;
totalAverageSpeed += w.getTrackData().getAverageSpeed();
totalDistance += w.getTrackData().getTotalDistance();
totalDuration = totalDuration.plus(w.getTrackData().getTotalDuration());
}
}
long secs = totalDuration.getSeconds();
duration.setText(String.format("%d:%02d:%02d", secs / 3600, (secs % 3600) / 60, (secs % 60)));
distance.setText(WorkoutController.round2(totalDistance / 1000.d) + " km");
averageSpeed.setText(WorkoutController.round2(totalAverageSpeed / workoutsAmountCounter) + " km/h");
workoutsAmount.setText("" + workoutsAmountCounter);
}
void setupChart() {
summaryChart.setAnimated(false);
summaryChart.getData().clear();
summaryChart.setAnimated(true);
XYChart.Series distanceSeries = new XYChart.Series();
distanceSeries.setName("Distancia (km)");
XYChart.Series timeSeries = new XYChart.Series();
timeSeries.setName("Tiempo (min)");
List<Group> groups = createGroups();
for (Group g : groups) {
List<Workout> groupWorkouts = g.getWorkouts();
double distance = 0.d;
long minutes = 0L;
for (Workout w : groupWorkouts) {
distance += w.getTrackData().getTotalDistance();
minutes += w.getTrackData().getTotalDuration().toMinutes();
}
distanceSeries.getData().add(new XYChart.Data<>(g.toString(getGroupingCriteria()), distance / 1000.d));
timeSeries.getData().add(new XYChart.Data<>(g.toString(getGroupingCriteria()), minutes));
}
summaryChart.getData().add(distanceSeries);
summaryChart.getData().add(timeSeries);
}
List<Group> createGroups() {
List<Group> groups = new ArrayList<>();
for (Workout w : filterWorkouts()) {
boolean added = false;
//¿El entrenamiento pertenece ya a un grupo existente?
for (Group g : groups) {
if (g.belongs(w, getGroupingCriteria())) {
//Sí: se añade.
g.add(w);
added = true;
break;
}
}
//No, se crea y se añade.
if (!added) {
Group newGroup = new Group(w.getTrackData().getStartTime());
newGroup.add(w);
insertOrdered(groups, newGroup);
}
}
return groups;
}
public static <E extends Comparable<E>> void insertOrdered(List<E> list, E item) {
boolean added = false;
for (int i = 0; i < list.size() && !added; i++) {
if (item.compareTo(list.get(i)) < 0) {
list.add(i, item);
added = true;
}
}
if (!added) {
list.add(item);
}
}
/**
*
* @return Devuelve los workouts dentro del periodo especificado por el
* usuario.
*/
public List<Workout> filterWorkouts() {
List<Workout> filteredWorkouts = new ArrayList<>();
for (Workout w : workouts) {
if (initialDate.getValue().compareTo(w.getTrackData().getStartTime().toLocalDate()) <= 0
&& finalDate.getValue().compareTo(w.getTrackData().getEndTime().toLocalDate()) >= 0) {
filteredWorkouts.add(w);
}
}
return filteredWorkouts;
}
public Workout getFirstWorkout() {
Workout first = null;
for (Workout w : workouts) {
if (first == null || w.getTrackData().getStartTime().compareTo(first.getTrackData().getStartTime()) < 0) {
first = w;
}
}
return first;
}
public Workout getLastWorkout() {
Workout last = null;
for (Workout w : workouts) {
if (last == null || w.getTrackData().getStartTime().compareTo(last.getTrackData().getStartTime()) > 0) {
last = w;
}
}
return last;
}
@Override
public void changed(ObservableValue<? extends LocalDate> observable, LocalDate oldValue, LocalDate newValue) {
if (initialDate.getValue().compareTo(finalDate.getValue()) > 0) {
initialDate.setValue(finalDate.getValue());
}
setupUI();
}
@FXML
private void groupByAction(ActionEvent event) {
setupChart();
}
private GroupingCriteria getGroupingCriteria() {
if (groupBy.getSelectionModel().isSelected(0)) {
return GroupingCriteria.DAY;
}
if (groupBy.getSelectionModel().isSelected(1)) {
return GroupingCriteria.MONTH;
}
if (groupBy.getSelectionModel().isSelected(2)) {
return GroupingCriteria.YEAR;
}
return null;
}
}
class Group implements Comparable<Group> {
private LocalDateTime localTime;
private List<Workout> workouts;
public Group(LocalDateTime localTime) {
this.localTime = localTime;
workouts = new ArrayList<>();
}
public boolean belongs(Workout workout, SummaryController.GroupingCriteria criteria) {
if (criteria == SummaryController.GroupingCriteria.DAY) {
return localTime.getDayOfMonth() == workout.getTrackData().getStartTime().getDayOfMonth()
&& localTime.getMonth() == workout.getTrackData().getStartTime().getMonth()
&& localTime.getYear() == workout.getTrackData().getStartTime().getYear();
} else if (criteria == SummaryController.GroupingCriteria.MONTH) {
return localTime.getMonth() == workout.getTrackData().getStartTime().getMonth()
&& localTime.getYear() == workout.getTrackData().getStartTime().getYear();
} else if (criteria == SummaryController.GroupingCriteria.YEAR) {
return localTime.getYear() == workout.getTrackData().getStartTime().getYear();
}
return false;
}
public void add(Workout workout) {
workouts.add(workout);
}
public List<Workout> getWorkouts() {
return workouts;
}
public String toString(SummaryController.GroupingCriteria criteria) {
if (criteria == SummaryController.GroupingCriteria.DAY) {
return localTime.getDayOfMonth() + "/" + localTime.getMonthValue() + "/" + localTime.getYear();
} else if (criteria == SummaryController.GroupingCriteria.MONTH) {
return localTime.getMonthValue() + "/" + localTime.getYear();
} else if (criteria == SummaryController.GroupingCriteria.YEAR) {
return localTime.getYear() + "";
}
return "";
}
@Override
public int compareTo(Group other) {
return localTime.compareTo(other.localTime);
}
}
| b8247a6fec0c8e39ba01312e5af5941184bff079 | [
"Markdown",
"Java"
] | 5 | Markdown | cshuig/SportsTracker | 3cafb95ea43b1d2a70d264213de0eea6ee6bc358 | ff422d2c0cd99de95f74404e577ec815535100c3 | |
refs/heads/master | <file_sep>package org.maven.MavenProject;
import org.testng.Assert;
import org.testng.annotations.Test;
public class Day1 {
@Test()
public void test1() {
System.out.println("Test1");
}
@Test(retryAnalyzer=Day2.class)
public void test2() {
System.out.println("Test2");
//Assert.assertTrue(false);
}
}
| 8ec63944c8c11391a4797307b8a1cae5df6492f4 | [
"Java"
] | 1 | Java | Anand230796/GitPractice | 4aa9c338f093b10ce38c89169c6789b53acc1145 | 5a0cbddabb0114b0b458c6872073fa0f89695055 | |
refs/heads/master | <file_sep>package com.smallrain.wechat.models.user.mapper;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.smallrain.wechat.models.user.entity.SysUser;
/**
* <p>
* Mapper 接口
* </p>
*
* @author wangying
* @since 2019-10-30
*/
@Mapper
public interface SysUserMapper extends BaseMapper<SysUser> {
}
<file_sep>package com.smallrain.wechat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan
public class SmallrainWechatApplication {
public static void main(String[] args) {
SpringApplication.run(SmallrainWechatApplication.class, args);
}
}
<file_sep>package com.smallrain.wechat.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.smallrain.wechat.common.model.Response;
import com.smallrain.wechat.models.dto.DtoUtils;
import com.smallrain.wechat.models.user.entity.SysUser;
import com.smallrain.wechat.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;
/**
* 通用页面控制类
*/
@Slf4j
@ApiIgnore
@Controller
public class CommonController {
/**
* 登录成功后的跳转
*
* @return
*/
@GetMapping("/index")
public ModelAndView loginSuccess() {
SysUser currentUser = ShiroUtil.getCurrentUser();
if (null == currentUser) {
return new ModelAndView("redirect:/login");
}
log.info("当前登陆用户:{}", currentUser.getAccount());
// 后期加上根据用户角色跳转前台页面或者后台
// roleService.getListByUserId(userId);
ModelAndView mv = new ModelAndView("back/index");
mv.addObject("user", currentUser);
return mv;
}
/**
* 未授权提示页面
*
* @return
*/
@GetMapping("/unauthorized")
public ModelAndView unauthorized() {
ModelAndView mv = new ModelAndView("error/unauthorized");
return mv;
}
/**
* 获取实体信息
*
* @return
*/
@ResponseBody
@GetMapping("/model/info/{modelName}")
public Response getModelInfo(@PathVariable String modelName) {
JSONObject info = DtoUtils.getModelInfo(modelName);
if(null==info) {
return Response.fail(-1, "实体信息为空,请确认名称正确");
}
return Response.success(info);
}
}
<file_sep>package com.samllrain.wechat;
import com.smallrain.wechat.utils.BaseUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SmallrainWechatApplicationTests {
public static void main(String[] args) {
log.info(BaseUtils.humpToLine("hsdbchHsdhs_sdcsh"));
}
}
<file_sep>## smalrain wechat project back
<file_sep>var menuList = [
{
id: '1',
name: '菜单管理',
title: '菜单管理页面',
icon: 'el-icon-menu',
childList: [
{
id: '1-1',
name: '后台菜单管理',
title: '菜单管理-后台菜单管理',
icon: 'el-icon-s-tools',
url: 'back/menu',
}
]
},
{
id: '2',
name: '用户-角色管理',
title: '用户-角色管理页面',
icon: 'el-icon-s-custom',
childList: [
{
id: '2-1',
name: '用户列表',
title: '用户管理-用户列表',
icon: 'el-icon-user-solid',
url: 'back/user',
}
]
}
]<file_sep>package com.smallrain.wechat.models.role.entity;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author wangying
* @since 2019-10-30
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="SysRole对象", description="")
public class SysRole extends Model<SysRole> {
private static final long serialVersionUID = 1L;
private String id;
@ApiModelProperty(value = "角色名称")
private String name;
@ApiModelProperty(value = "角色描述")
private String description;
private Integer deleteFlag;
@Override
protected Serializable pkVal() {
return this.id;
}
}
<file_sep>package com.smallrain.wechat.models.menu.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author wangying
* @since 2019-10-30
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="SysMenu对象", description="")
public class SysMenu extends Model<SysMenu> {
private static final long serialVersionUID = 1L;
private String id;
private String parentId;
private String name;
private String style;
private String href;
private String icon;
private String text;
private Integer type;
private String permission;
private Integer sort;
private Integer status;
@Override
protected Serializable pkVal() {
return this.id;
}
}
<file_sep>package com.smallrain.wechat.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.smallrain.wechat.models.user.entity.SysUser;
import com.smallrain.wechat.utils.ShiroUtil;
import springfox.documentation.annotations.ApiIgnore;
/**
* 管理后台相关控制类
*
*
*/
@ApiIgnore
@Controller
@RequestMapping("/back")
public class BackManagerController {
/**
* 后台管理 - 首页
*
* @return
*/
@GetMapping("/main")
public ModelAndView backMain() {
SysUser currentUser = ShiroUtil.getCurrentUser();
ModelAndView mv = new ModelAndView("back/main");
mv.addObject("user", currentUser);
return mv;
}
/**
* 后台管理 - 菜单管理
*
* @return
*/
//@RequiresPermissions(value = "admin:menu")
@GetMapping("/menu")
public ModelAndView backMenu() {
ModelAndView mv = new ModelAndView("back/menu");
return mv;
}
/**
* 后台管理 - 菜单管理
*
* @return
*/
//@RequiresPermissions(value = "admin:menu")
@GetMapping("/user")
public ModelAndView backUser() {
ModelAndView mv = new ModelAndView("back/user");
return mv;
}
}
<file_sep>package com.smallrain.wechat.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.yaml.snakeyaml.Yaml;
import com.alibaba.fastjson.JSONObject;
import com.smallrain.wechat.common.exception.SmallrainException;
import com.smallrain.wechat.models.menu.entity.SysMenu;
import com.smallrain.wechat.models.role.entity.SysRole;
import com.smallrain.wechat.models.user.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
/**
* 实体类检查工具类
* @author wangying.dz3
*
*/
@Slf4j
public class EntityCheckUtil {
// 初始化实体类检查配置内存
private static JSONObject checkConfig = new JSONObject();
//静态代码块,启动时加载本地配置文件
static {
// 获取配置文件输入流
ClassPathResource resource = new ClassPathResource("check/beans-field-check.yml");
try (InputStream inputStream = resource.getInputStream()){
Yaml yaml = new Yaml();
Object ticketsCheckConfig = yaml.load(inputStream);
checkConfig = JSONObject.parseObject(JSONObject.toJSONString(ticketsCheckConfig));
if (null != inputStream)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 检测用户对象某些必须属性
* @param user
* @return
* @throws SmallrainException
*/
public static void userFieldCheck(SysUser user) throws SmallrainException {
if(null == user) {
throw new SmallrainException(601,"用户信息为空");
}
String check = BaseUtils.checkBeanNeededField(user, checkConfig.getJSONObject("USER"));
if(StringUtils.isNotBlank(check)) {
log.info("user check error:{}",check);
throw new SmallrainException(600,check);
}
// if(StringUtils.isBlank(user.getAccount())) {
// throw new SmallrainException(600,"用户信息缺少账号");
// }
// if(StringUtils.isBlank(user.getPassword())) {
// throw new SmallrainException(600,"用户信息缺少密码");
// }
// return ;
}
/**
* 检测角色对象某些必须属性
* @param user
* @return
* @throws SmallrainException
*/
public static void roleFieldCheck(SysRole role) throws SmallrainException {
if(null == role) {
throw new SmallrainException(601,"角色信息为空");
}
String check = BaseUtils.checkBeanNeededField(role, checkConfig.getJSONObject("USER"));
if(StringUtils.isNotBlank(check)) {
throw new SmallrainException(600,check);
}
// if(StringUtils.isBlank(role.getName())) {
// throw new SmallrainException(600,"角色信息名称");
// }
return ;
}
/**
* 检测角色对象某些必须属性
* @param user
* @return
* @throws SmallrainException
*/
public static void menuFieldCheck(SysMenu menu) throws SmallrainException {
if(null == menu) {
throw new SmallrainException(601,"角色信息为空");
}
String check = BaseUtils.checkBeanNeededField(menu, checkConfig.getJSONObject("USER"));
if(StringUtils.isNotBlank(check)) {
throw new SmallrainException(600,check);
}
return ;
}
}
<file_sep>package com.smallrain.wechat.common;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import lombok.Data;
@Data
@SpringBootConfiguration
@PropertySource(value = {"classpath:auth/base-config.properties"})
@ConfigurationProperties(prefix = "base.config")
public class BaseProperties {
private int tokenExpire;
}
<file_sep>package com.smallrain.wechat.common.shiro;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Base64Utils;
import com.smallrain.wechat.common.filter.LogoutFilter;
import com.smallrain.wechat.common.filter.RestfulFilter;
import com.smallrain.wechat.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Configuration
public class ShiroConfig {
@Resource
private ShiroProperties shiroProperties;
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager); // 设置 securityManager
shiroFilterFactoryBean.setLoginUrl(shiroProperties.getLoginUrl()); // 登录的 url
//shiroFilterFactoryBean.setSuccessUrl(shiroProperties.getSuccessUrl()); // 登录成功后跳转的 url
shiroFilterFactoryBean.setUnauthorizedUrl(shiroProperties.getUnauthorizedUrl()); // 未授权 url
LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
// 设置免认证 url
String[] anonUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(shiroProperties.getAnonUrl(), ",");
for (String url : anonUrls) {
filterChainDefinitionMap.put(url, "anon");
}
// 配置退出过滤器,其中具体的退出代码 Shiro已经替我们实现了
filterChainDefinitionMap.put(shiroProperties.getLogoutUrl(), "logout");
// 除上以外所有 url都必须认证通过才可以访问,未通过认证自动访问 LoginUrl
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
//配置自定义退出过滤器
LogoutFilter logoutFilter = new LogoutFilter();
logoutFilter.setRedirectUrl("/login");
shiroFilterFactoryBean.getFilters().put("logout", logoutFilter);
//配置restFul 接口过滤器
RestfulFilter restfulFilter = new RestfulFilter();
shiroFilterFactoryBean.getFilters().put("authc", restfulFilter);
log.info("Shiro拦截器工厂类注入成功");
return shiroFilterFactoryBean;
}
@Bean
@Autowired
public SecurityManager securityManager(SmallrainRealm smallrainRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 配置 SecurityManager,并注入 shiroRealm
smallrainRealm.setCredentialsMatcher(hashedCredentialsMatcher()); // 原来在这里
securityManager.setRealm(smallrainRealm);
// 配置 shiro session管理器
securityManager.setSessionManager(sessionManager());
// 配置 rememberMeCookie
securityManager.setRememberMeManager(rememberMeManager());
return securityManager;
}
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName(AuthUtil.ALGORITHM_NAME); // 散列算法
hashedCredentialsMatcher.setHashIterations(AuthUtil.HASH_ITERATIONS); // 散列次数
return hashedCredentialsMatcher;
}
/**
* rememberMe cookie 效果是重开浏览器后无需重新登录
*
* @return SimpleCookie
*/
private SimpleCookie rememberMeCookie() {
// 设置 cookie 名称,对应 login.html 页面的 <input type="checkbox" name="rememberMe"/>
SimpleCookie cookie = new SimpleCookie("rememberMe");
// 设置 cookie 的过期时间,单位为秒,这里为一天
cookie.setMaxAge(shiroProperties.getCookieTimeout());
return cookie;
}
/**
* cookie管理对象
*
* @return CookieRememberMeManager
*/
private CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
// rememberMe cookie 加密的密钥
String encryptKey = "febs_shiro_key";
byte[] encryptKeyBytes = encryptKey.getBytes(StandardCharsets.UTF_8);
String rememberKey = Base64Utils.encodeToString(Arrays.copyOf(encryptKeyBytes, 16));
cookieRememberMeManager.setCipherKey(Base64.decode(rememberKey));
return cookieRememberMeManager;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
/**
* session 管理对象
*
* @return DefaultWebSessionManager
*/
@Bean
public DefaultWebSessionManager sessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
Collection<SessionListener> listeners = new ArrayList<>();
listeners.add(new ShiroSessionListener());
// 设置 session超时时间
sessionManager.setGlobalSessionTimeout(shiroProperties.getSessionTimeout() * 1000L);
sessionManager.setSessionListeners(listeners);
// sessionManager.setSessionDAO(redisSessionDAO());
sessionManager.setSessionIdUrlRewritingEnabled(false);
return sessionManager;
}
}
<file_sep>package com.smallrain.wechat.generator;
import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
/**
* mybatis 代码生成器
*
* @author wangying.dz3
*
*/
public class MybatisCodeGenerator {
private static final String MODEL_NAME = "";
private static final String TABLES_NAME = ""; // ,分割
public static void main(String[] args) {
// 代码生成器
AutoGenerator autoGenerator = new AutoGenerator();
// set freemarker engine
autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
String projectPath = System.getProperty("user.dir");
// 全局配置
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(projectPath + "/src/main/java"); //代码生成目录
globalConfig.setAuthor("wangying");
globalConfig.setOpen(false);
globalConfig.setSwagger2(true); // 实体属性 Swagger2 注解
globalConfig.setFileOverride(true);
globalConfig.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
globalConfig.setEnableCache(false);// XML 二级缓存
globalConfig.setBaseResultMap(true);// XML ResultMap
globalConfig.setBaseColumnList(true);// XML columList
globalConfig.setServiceName("%sService");
// .setKotlin(true) 是否生成 kotlin 代码
autoGenerator.setGlobalConfig(globalConfig);
// 数据库配置
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL);
dataSourceConfig.setUrl("jdbc:mysql://172.16.17.32:3306/template?useUnicode=true&useSSL=false&characterEncoding=utf8");
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
dataSourceConfig.setUsername("template");
dataSourceConfig.setPassword("<PASSWORD>");
autoGenerator.setDataSource(dataSourceConfig);
// 包配置
PackageConfig packageConfig = new PackageConfig();
packageConfig.setModuleName(MODEL_NAME.toLowerCase());
packageConfig.setParent("com.smallrain.wechat.models");
autoGenerator.setPackageInfo(packageConfig);
// 自定义配置
InjectionConfig injectionConfig = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + packageConfig.getModuleName() + "/" + tableInfo.getEntityName()
+ "Mapper" + StringPool.DOT_XML;
}
});
injectionConfig.setFileOutConfigList(focList);
autoGenerator.setCfg(injectionConfig);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
templateConfig.setService("/source/service.java");
// /templates/source/controller.java.ftl
templateConfig.setController("/source/controller.java");
templateConfig.setXml(null);
autoGenerator.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
//strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
// 公共父类
//strategy.setSuperControllerClass("com.smallrain.wechat.common.base.BaseController.java");
//strategy.setSuperServiceClass("com.smallrain.wechat.common.base.BaseService.java");
// 写于父类中的公共字段
//strategy.setSuperEntityColumns("id");
strategy.setInclude(TABLES_NAME.split(","));
strategy.setTablePrefix(packageConfig.getModuleName() + "_");
autoGenerator.setStrategy(strategy);
autoGenerator.execute();
}
}
<file_sep>package com.smallrain.wechat.models.user.entity;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author wangying
* @since 2019-10-30
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="SysUser对象", description="")
public class SysUser extends Model<SysUser> {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "用户 id")
private String id;
@ApiModelProperty(value = "用户名")
private String name;
@ApiModelProperty(value = "用户账号")
private String account;
@ApiModelProperty(value = "用户密码")
private String password;
private String salt;
@ApiModelProperty(value = "用户性别: 0- 男,1- 女")
private Integer sex;
@ApiModelProperty(value = "用户手机号")
private String phone;
@ApiModelProperty(value = "用户邮箱 ")
private String email;
@ApiModelProperty(value = "用户身份证号")
private String identity;
@ApiModelProperty(value = "头像")
private String headImage = "";
@ApiModelProperty(value = "用户角色ID")
private String role;
@ApiModelProperty(value = "注册时间")
private Date registerTime;
@ApiModelProperty(value = "绑定 ip ")
private String bandIp;
@ApiModelProperty(value = "用户真实姓名")
private String realName;
@ApiModelProperty(value = "签名")
private String signature;
@ApiModelProperty(value = "删除标记")
private Integer status;
public String getCredentialsSalt() {
// TODO Auto-generated method stub
return "user-credentials-salt-"+salt;
}
@Override
protected Serializable pkVal() {
return this.id;
}
}
<file_sep>package com.smallrain.wechat.models.user.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smallrain.wechat.common.exception.SmallrainException;
import com.smallrain.wechat.common.model.QueryParam;
import com.smallrain.wechat.models.user.entity.SysUser;
/**
*
* @author wangying
* @since 2019-10-30
*/
public interface SysUserService {
public IPage<SysUser> getList(QueryParam<SysUser> param) throws SmallrainException;
public SysUser getOne(String id) throws SmallrainException;
public SysUser add(SysUser entity) throws SmallrainException;
public SysUser update(SysUser entity) throws SmallrainException;
public boolean delete(String... ids) throws SmallrainException;
public SysUser getUserByUserName(String useName) throws SmallrainException;
}
<file_sep>package com.smallrain.wechat.common.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.smallrain.wechat.common.manager.datasource.SelectDataType;
/**
* 用于标记需要编辑的实体属性
* @author wangying.dz3
*
*/
//ElementType.FIELD:注解放在属性上
@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)// 注解在运行时有效
public @interface ModelEditField {
/**
* 属性名称
* @return
*/
String name() default "实体属性";
/**
* 是否在添加时需要
* @return
*/
boolean add() default true;
/**
* 是否在修改时需要
* @return
*/
boolean edit() default true;
/**
* 是否在列表显示
* @return
*/
boolean show() default false;
/**
* 列表显示时的宽度
* @return
*/
int width() default 100;
/**
* 输入格式
* @return
*/
InputType type() default InputType.TEXT;
/**
* 校验规则 ,形如:type:string;message:必须为字符串,tigger:blur 参考:async-validator
* @return
*/
String [] validators() default {};
/**
* 选择框所需的选择项来源
* @return
*/
SelectDataType source() default SelectDataType.DEFAULT;
}
<file_sep>package com.smallrain.wechat.models.miniapp.config;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
/**
* 微信小程序先相关配置
*
* @author wangying.dz3
*
*/
@Data
@ConfigurationProperties(prefix = "wx.miniapp")
public class WechatMiniAppProperties {
private List<Config> configs;
@Data
public static class Config {
/**
* 设置微信小程序的appid
*/
private String appid;
/**
* 设置微信小程序的Secret
*/
private String secret;
/**
* 设置微信小程序消息服务器配置的token
*/
private String token;
/**
* 设置微信小程序消息服务器配置的EncodingAESKey
*/
private String aesKey;
/**
* 消息格式,XML或者JSON
*/
private String msgDataFormat;
}
}
<file_sep>package com.smallrain.wechat.models.user.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smallrain.wechat.common.exception.SmallrainException;
import com.smallrain.wechat.common.model.QueryParam;
import com.smallrain.wechat.models.user.entity.SysUser;
import com.smallrain.wechat.models.user.mapper.SysUserMapper;
import com.smallrain.wechat.models.user.service.SysUserService;
import com.smallrain.wechat.utils.AuthUtil;
import com.smallrain.wechat.utils.BaseUtils;
import com.smallrain.wechat.utils.EntityCheckUtil;
import lombok.extern.slf4j.Slf4j;
/**
* <p>
* 服务实现类
* </p>
*
* @author wangying
* @since 2019-10-30
*/
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
@Override
public IPage<SysUser> getList(QueryParam<SysUser> param) throws SmallrainException {
// TODO Auto-generated method stub
return this.page(param.getPage(), param.getQueryWrapper());
}
@Override
public SysUser getOne(String id) throws SmallrainException {
// TODO Auto-generated method stub
return this.getById(id);
}
@Override
public SysUser add(SysUser entity) throws SmallrainException {
// TODO Auto-generated method stub
log.info("添加用户:{}", entity);
if (StringUtils.isNotBlank(entity.getId())) {
update(entity);
}
entity.setId(BaseUtils.createUuid("user"));
entity.setRegisterTime(new Date());
entity.setStatus(0);
EntityCheckUtil.userFieldCheck(entity);
// 密码加密
AuthUtil.encryptPassword(entity, true);
this.save(entity);
return entity;
}
@Override
public SysUser update(SysUser entity) throws SmallrainException {
// TODO Auto-generated method stub
log.info("更新用户:{}", entity);
if (StringUtils.isBlank(entity.getId()) || !entity.getId().startsWith("user")) {
entity.setId(null);
add(entity);
}
SysUser oldUser = getOne(entity.getId());
if (null == oldUser) {
log.info("不存在 id 为:{} 的用户", entity.getId());
add(entity);
}
BaseUtils.copyNotNullProperties(entity, oldUser, "id", "registerTime", "bandIp");
EntityCheckUtil.userFieldCheck(entity);
log.info("更新用户。。");
this.updateById(entity);
return entity;
}
@Override
public boolean delete(String... ids) throws SmallrainException {
// TODO Auto-generated method stub
log.info("根据Id:{} 删除用户。", String.join(",", ids));
if (null == ids || ids.length == 0) {
throw new SmallrainException(601, "删除用户失败,传入的用户id 为空!");
}
boolean result = true;
if (ids.length == 1) {
result = this.removeById(ids[0]);
} else {
List<String> idsList = new ArrayList<String>();
for (String id : ids) {
idsList.add(id);
}
result = this.removeByIds(idsList);
}
return result;
}
@Override
public SysUser getUserByUserName(String useName) throws SmallrainException {
// TODO Auto-generated method stub
log.info("根据用户名:{} 获取用户信息", useName);
if (StringUtils.isBlank(useName)) {
throw new SmallrainException(601, "获取用户失败,用户名为空");
}
QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("account", useName);
return this.getOne(queryWrapper);
}
}
<file_sep>package com.smallrain.wechat.models.dto;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smallrain.wechat.common.annotations.ModelEditField;
import com.smallrain.wechat.common.manager.datasource.SelectDataSourceManager;
import com.smallrain.wechat.common.manager.datasource.SelectDataType;
import com.smallrain.wechat.utils.BaseUtils;
import com.smallrain.wechat.utils.SpringUtil;
/**
* 数据转对象工具类,用于生成实体类信息
* @author wangying.dz3
*
*/
public class DtoUtils {
private static Map<Class<?>,String> INIT_MODELS = new HashMap<>();
private static JSONObject MODELS = new JSONObject();
static {
INIT_MODELS.put(UserDto.class, "用户");
INIT_MODELS.put(MenuDto.class, "菜单");
//遍历处理
Set<Class<?>> keys = INIT_MODELS.keySet();
for(Class<?> key:keys) {
if(null==key) continue;
JSONObject obj = new JSONObject();
String modelName = INIT_MODELS.get(key);
obj.put("modelName", modelName);
obj.put("beanInfo", resolveEntity(key));
MODELS.put(key.getSimpleName().toUpperCase(), obj);
}
}
public static JSONObject getModelInfo(String modelName) {
if(StringUtils.isBlank(modelName)) return null;
return MODELS.getJSONObject((modelName+"DTO").toUpperCase());
}
private static JSONObject resolveEntity(Class<?> clazz) {
JSONObject result = new JSONObject();
if (null == clazz)
return result;
List<Field> fieldsList = new ArrayList<>();
Field[] fields = clazz.getDeclaredFields();
fieldsList.addAll(Arrays.asList(fields));
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null) {
Field[] superFields = superClazz.getDeclaredFields();
fieldsList.addAll(Arrays.asList(superFields));
}
List<String> names = new ArrayList<>();
for (Field field : fieldsList) {
// 设置访问对象权限,保证对私有属性的访问
field.setAccessible(true);
ModelEditField mef = field.getAnnotation(ModelEditField.class);
if (null == mef)
continue; // 没有该注解,跳过
String name = field.getName();
names.add(field.getName());
JSONObject mefJson = JSONObject.parseObject(JSON.toJSONString(mef));
//处理校验规则
if(StringUtils.isNoneBlank(mef.validators())) {
JSONArray validatorsJson = new JSONArray();
String [] validators = mef.validators();
for(String validator:validators) {
JSONObject json = new JSONObject();
if(StringUtils.isBlank(validator)) continue;
String [] validatorItems = validator.split(",");
if(null!=validatorItems) {
for(String validatorItem:validatorItems) {
if(!validatorItem.contains(":")) continue;
String [] items = validatorItem.split(":");
if(null==items || items.length == 0) continue;
if(items.length == 1) {
json.put(validatorItem.split(":")[0], "");
}else {
json.put(validatorItem.split(":")[0], BaseUtils.transBoolean(validatorItem.split(":")[1])?true:validatorItem.split(":")[1]);
}
}
}
validatorsJson.add(json);
}
mefJson.put("validators", validatorsJson);
}
//处理选择数据
if(SelectDataType.DEFAULT != mef.source()) {
SelectDataSourceManager selectDataSourceManager = SpringUtil.getBean(SelectDataSourceManager.class);
mefJson.put("dataList", selectDataSourceManager.getData(mef.source()));
}
result.put(name, mefJson);
}
result.put("FIELD_ITEM_LIST", names);
return result;
}
}
<file_sep>package com.smallrain.wechat.common.manager.datasource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
/**
* 表单选择项数据源管理
* @author wangying.dz3
*
*/
@Service
public class SelectDataSourceManager {
public List<Map<String,String>> getData(SelectDataType dataType){
if(null == dataType) {
return new ArrayList<>();
}
switch(dataType) {
case SEX: //性别
return getSexDataSource();
case DEFAULT:
return new ArrayList<>();
default:
return new ArrayList<>();
}
}
@SuppressWarnings("serial")
private List<Map<String,String>> getSexDataSource() {
List<Map<String,String>> result = new ArrayList<>();
result.add(new HashMap<String,String>() {{
put("key","0");
put("value","男");
}});
result.add(new HashMap<String,String>() {{
put("key","1");
put("value","女");
}});
return result;
}
}
<file_sep>package com.smallrain.wechat.common.model;
import lombok.Data;
@Data
public class LoginData {
private String account;
private String password;
private boolean rememberMe;
}
| 4602031e345416e5be3410ddaffac06dd9d841da | [
"Markdown",
"Java",
"JavaScript"
] | 21 | Java | Playtigertomorrownight/wechatMiniApp | ece668fe9c3f31cea09f43cdd8cf0ee0e018351b | 5158ce518654b489521f68bf78f3c2aa252e6523 | |
refs/heads/main | <file_sep>import classes from "./Footer.module.css";
import Map from "./Map/Map"
import Contacts from "./Contacts/Contacts"
const Footer = () => {
return ( <div className={classes.Footer}>
<Contacts/>
<Map/>
</div> );
}
export default Footer;<file_sep>import { Route } from "react-router-dom";
import classes from "./Vacancies.module.css";
import VacanciesList from "./VacanciesList/VacanciesList";
import Vacancy from "./Vacancy/Vacancy";
const Vacancies = ({match}) => {
return ( <div className={classes.Vacancies}>
<h1>Вакансии</h1>
{match.isExact ? <VacanciesList/> : <Route path='/vacancies/:id' component={Vacancy}/>}
</div> );
}
export default Vacancies;<file_sep>import classes from "./Languages.module.css";
const Languages = () => {
return ( <div className={classes.Languages}>
</div> );
}
export default Languages;<file_sep>import classes from "./Best.module.css";
const Best = () => {
return ( <div className={classes.Best}>
</div> );
}
export default Best;<file_sep>import classes from "./Menu.module.css";
const Menu = () => {
return ( <div className={classes.Menu}>
</div> );
}
export default Menu;<file_sep>import classes from "./Logo.module.css";
import logo from "../../../images/kumara.png"
const Logo = () => {
return ( <div className={classes.Logo}>
<img alt="logo" src={logo} className={classes.logo}/>
<h1 className={classes.title}><NAME></h1>
</div> );
}
export default Logo;<file_sep>import classes from "./Contacts.module.css";
import insta from "../../../images/contacts-images/insta.svg"
import fb from "../../../images/contacts-images/facebook.svg"
import tripadvisor from "../../../images/contacts-images/trip-adv.svg"
import wsp from "../../../images/contacts-images/whatsapp.svg"
import tg from "../../../images/contacts-images/tg.svg"
const Contacts = () => {
return ( <div className={classes.Contacts}>
<h3>Свяжитесь с нами</h3>
<ul>
<li>Адресс:г.Каракол ул.Пржевальского 105а</li>
<li>Телефон: +996 556-255-258</li>
<li>Телефон: +996 706-255-258</li>
<li>Email: <EMAIL></li>
</ul>
<div className={classes.links}>
<a rel="noreferrer" href='https://www.instagram.com/altyn_kumara/' target='_blank'><img alt='instagram' src={insta}/></a>
<a rel="noreferrer" href='https://www.facebook.com/AltynKumara' target='_blank'><img alt='facebook' src={fb}/></a>
<a rel="noreferrer" href='https://www.tripadvisor.ru/Restaurant_Review-g815340-d13313936-Reviews-Altyn_Kumara-Karakol_Issyk_Kul_Province.html' target='_blank'><img alt='tripadvisor' src={tripadvisor}/></a>
<a rel="noreferrer" href='https://api.whatsapp.com/send?phone=996556521111' target='_blank'><img alt='whatsapp' src={wsp}/></a>
<a rel="noreferrer" href='https://google.com' target='_blank'><img alt='telegram' src={tg}/></a>
</div>
</div> );
}
export default Contacts;<file_sep>const Logout = () => {
return null;
}
export default Logout;<file_sep>import classes from "./Map.module.css";
const Map = () => {
return ( <div className={classes.Map}>
<iframe title='map' src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d183.85646859515637!2d78.38430175567255!3d42.49785579934702!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0xe5e3d768d570e350!2z0JDQu9GC0YvQvSDQmtGD0LzQsNGA0LA!5e0!3m2!1sru!2skg!4v1622704059122!5m2!1sru!2skg" width="500" height="300" style={{border:0}} allowFullScreen="" loading="lazy"></iframe>
</div> );
}
export default Map;<file_sep>import classes from "./Nav.module.css";
import NavItem from "./NavItem/NavItem";
const Nav = ({click}) => {
return ( <div className={classes.Nav}>
<NavItem click={click} url="/" exact>Главная</NavItem>
<NavItem click={click} url="/menu">Меню</NavItem>
<NavItem click={click} url="/vacancies">Вакансии</NavItem>
<NavItem click={click} url="/about">О нас</NavItem>
</div> );
}
export default Nav;
<file_sep>import classes from "./Bravo.module.css";
import bravo from "../../images/bravo-logo.png"
const Bravo = () => {
return ( <div className={classes.Bravo}>
<img alt='bravo-logo' src={bravo}/>
<h1><NAME></h1>
</div> );
}
export default Bravo;<file_sep>import Toolbar from "./Toolbar/Toolbar"
import Drawer from "./Drawer/Drawer"
import Footer from "../Footer/Footer"
import { useState } from "react";
const Layout = ({children}) => {
const [drawerOpen, setDrawerOpen] = useState(false);
return ( <div>
<Toolbar openDrawer={() => setDrawerOpen(true)} />
<Drawer open={drawerOpen} closeDrawer={()=>setDrawerOpen(false)}/>
<main>
{children}
</main>
<Footer/>
</div> );
}
export default Layout;<file_sep>import { NavLink } from "react-router-dom";
import classes from "./NavItem.module.css";
const NavItem = ({ url, children, exact, click }) => {
return (<div onClick={click} className={classes.NavItem}>
<NavLink to={url} activeStyle={{color: "#ffdc23"}} exact={exact}>{children}</NavLink>
</div>);
}
export default NavItem;<file_sep>import { Route, Switch } from "react-router";
import About from "./About/About";
import classes from "./AltynKumara.module.css";
import Home from "./Home/Home";
import Menu from "./Menu/Menu";
import Vacancies from "./Vacancies/Vacancies";
import NotFound from "../UI/NotFound/NotFound"
import Bravo from "../Bravo/Bravo"
const AltynKumara = () => {
return ( <div className={classes.AltynKumara}>
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/menu' component={Menu}/>
<Route path='/vacancies' component={Vacancies}/>
<Route path='/about' component={About}/>
<Route path='/bravo-pizza' component={Bravo}/>
<Route path='/' component={NotFound}/>
</Switch>
</div> );
}
export default AltynKumara;<file_sep>import { useState } from "react";
import classes from "./Slider.module.css";
import image1 from "../../../../images/slider-images/ittashkent.jpg";
import image2 from "../../../../images/slider-images/itcompany.jpg";
import image3 from "../../../../images/slider-images/bulut.jpg";
const Slider = () => {
const [currentSlide, setCurrentSlide] = useState(1);
let move = '0px'
switch (currentSlide) {
case 1:
move = '0px'
break;
case 2:
move = '-100%'
break;
case 3:
move = '-200%'
break;
default:
move = '0px'
break;
}
if(currentSlide === 4){
setCurrentSlide(1)
}
if(currentSlide < 1){
setCurrentSlide(3)
}
return ( <div className={classes.Slider}>
<div style={{transform: `translateX(${move})`}} className={classes.slides}>
<div style={{backgroundImage: `url(${image1})`}}></div>
<div style={{backgroundImage: `url(${image2})`}}></div>
<div style={{backgroundImage: `url(${image3})`}}></div>
</div>
<div className={classes.sliderBtns}>
<button onClick={()=> setCurrentSlide(currentSlide - 1)} className={classes.sliderBtn}>{'<'}</button>
<button onClick={()=> setCurrentSlide(currentSlide + 1)} className={classes.sliderBtn}>{'>'}</button>
</div>
</div> );
}
export default Slider; | c38f48d96f8df82676e058a94d08503d36e23139 | [
"JavaScript"
] | 15 | JavaScript | soltonbekov-aiymkyz/authentification | d5cc8d9e90bfc50bb29aa328e4ee0240cadd5d94 | 90cef154db2ebfcb13c021d53da425633621a173 | |
refs/heads/master | <file_sep>#include <stdio.h>
#include <math.h>
void input(int *num);
void reverse_num(int num,char *reverse[],char *actual[]);
void compare_strings(char *a[],char *b[],int *equal);
void check_palindrome(char *reverse[],char *actual[]);
void main(){
int num;
char *actual[100];
char *reverse[100];
input(&num);
printf("%d",num);
reverse_num(num,reverse,actual);
check_palindrome(reverse,actual);
}
void input(int *num){
printf("Enter the number");
int n;
scanf("%d",&n);
*num = n;
}
void reverse_num(int num,char *reverse[],char *actual[]){
int num_of_digits,i;
num_of_digits = log10(num)+1;
char act[100];
char rev[100];
for(i=0;i<num_of_digits;i++){
act[i] =num%10;
rev[(num_of_digits-1)-i] =num%10;
num /= 10;
}
printf("%s",act);
*actual = act;
*reverse = rev;
}
void compare_strings(char *a[],char *b[],int *equal){
int i=0;
while(*a[i]==*b[i]){
if(*a[i]=='\0'||*b[i]=='\0'){
break;
}
i++;
}
if(*a[i]=='\0'&&*b[i]=='\0'){
*equal=0;
}else{
*equal=-1;
}
}
void check_palindrome(char *reverse[],char *actual[]){
int equal;
compare_strings(reverse,actual,&equal);
if(equal==0){
printf("Yes,The number is a palindrome. %s",*actual);
}else{
printf("No,The number is not a palindrome. %s",*reverse);
}
}<file_sep>#include <stdio.h>
#include <stdlib.h>
void input_dim(int *m,int *n){
printf("Enter the dimensions of matrix");
scanf("%d %d",m,n);
if(*m!=*n){
printf("Required a square matrix");
exit(0);
}
}
void input_matrix(int m,int n,float matrix[m][n]){
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
printf("Enter the element matrix[%d][%d]",i,j);
scanf("%f",&matrix[i][j]);
}
}
}
void print_diagonal(int m,int n,float matrix[m][n]){
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==j){
printf("%f ",matrix[i][j]);
}
}
}
}
void main(){
int m,n;
input_dim(&m,&n);
float matrix[m][n];
input_matrix(m,n,matrix);
print_diagonal(m,n,matrix);
}
<file_sep>#include <stdio.h>
void input(char *vehicle,int *time){
printf("Enter the first character of vehicle type and parking time");
scanf("%c %d",vehicle,time);
}
void fares(char vehicle,int time,int *fare){
int i=0;
if(vehicle=='c'){
if(time>2){
*fare=(20*2)+(30*(time-2));
}
else if(time==2){
*fare=(20*2);
}
else{
*fare=(20);
}
}
else if(vehicle=='b'){
if(time>4){
*fare=(40*4)+(50*(time-4));
}
else if(time==4){
*fare=(40*4);
}
else{
*fare=(40)*(time);
}
}
else{
if(time>3){
*fare=(30*3)+(40*(time-3));
}
else if(time==3){
*fare=(30*3);
}
else{
*fare=(30)*(time);
}
}
}
void main(){
int time,fare;
char vehicle;
input(&vehicle,&time);
fares(vehicle,time,&fare);
printf("The total fare for %c vehicle parked for %d hours is %d",vehicle,time,fare);
}
<file_sep>#include <stdio.h>
#include <math.h>
struct root{
float real;
float imaginary;
};
struct qequation{
float a;
float b;
float c;
};
void input(struct qequation *e);
void find_roots(struct root *r1,struct root *r2,struct qequation e,float *d);
void output(struct root r1,struct root r2,float d);
void main(){
struct qequation e;
struct root r1;
struct root r2;
float d;
input(&e);
find_roots(&r1,&r2,e,&d);
output(r1,r2,d);
}
void input(struct qequation *e){
printf("Type the values of a,b,c of quadratic equation.");
scanf("%f %f %f",&e->a,&e->b,&e->c);
}
/*
* compute function recieves three parameters:
* input parameters i : coefficients a,b,c
* Outut parameters r1,c2 : roots of the quadratic equation if the root
* Return Parameter : Value of Discrminant
* Note: ( return value >= 0) If roots are not complex imaginary part of c is zero
*/
void find_roots(struct root *r1,struct root *r2,struct qequation e,float *d){
*d=(e.b*e.b) -(4*e.a*e.c);
if (*d<0){
r1->real = -e.b/(2*e.a);
r1->imaginary = sqrt(-*d)/(2*e.a);
}
else if (*d==0){
r2->real = -e.b/(2*e.a);
r2->imaginary = 0;
}
else{
r2->real = -e.b/(2*e.a);
r2->imaginary = sqrt(*d)/(2*e.a);
}
}
void output(struct root r1,struct root r2,float d){
if (d<0){
printf("The roots are imaginary. %f + %fi and %f + %fi",r1.real,r1.imaginary,r1.real,r1.imaginary);
}
else if(d==0){
printf("The roots are equal. %f and %f",r2.real,r2.real);
}else{
printf("The roots are distinct. %f and %f", r2.real+r2.imaginary,r2.real-r2.imaginary);
}
}
<file_sep>#include <stdio.h>
#include <math.h>
void input(int *n){
printf("Enter the positive integer.");
scanf("%d",n);
}
void is_armstrong(int n){
int n_sub = n;
int num_digits=log10(n)+1;
int digits[num_digits];
for(int i=0;i<num_digits;i++){
digits[i]=(n%10)*(n%10)*(n%10);
n/=10;
}
int arm_digit = 0;
for(int i=0;i<num_digits;i++){
arm_digit = arm_digit+digits[i];
}
if(arm_digit==n_sub){
printf("Yes, it is a arstrong number. %d %d",n_sub,arm_digit);
}else{
printf("NO, it is not a armstrong number. %d %d",n_sub,arm_digit);
}
}
void main(){
int n;
input(&n);
is_armstrong(n);
}
<file_sep>#include <stdio.h>
void input(float a[]){
printf("Enter three numbers.");
scanf("%f %f %f",&a[0],&a[1],&a[2]);
}
/*
greatest_integer receives 2 parameter:
INPUT PARAMETERS a[]: array which contains input.
OUTPUT PARAMETERS great: greatest number
RETURN PARAMETERS : doesn't return anything.
*/
void greatest_integer(float *great,float a[]){
if(a[0]>a[1]&&a[1]>a[2]){
*great= a[0];
}
else if (a[1]>a[0]&&a[0]>a[2]){
*great = a[1];
}
else{
*great = a[2];
}
}
void output(float great){
printf("The greatest integer is = %f",great);
}
void main(){
float a[3],great;
input(a);
greatest_integer(&great,a);
output(great);
}<file_sep>#include <stdio.h>
#include <string.h>
void input(int *num){
int n;
printf("Enter the number");
scanf("%d",&n);
*num=n;
}
void check_palindrome(int num,int rev){
if (num==rev)
printf("Yes, The number is a palindrome. %d\n",rev);
else
printf("No, The number is not a palindrome. %d\n",rev);
}
void reverse(int num,int *rev){
int r=0;
while(num!=0){
r = r*10+num%10;
num/=10;
}
*rev=r;
}
void main(){
int num,rev;
input(&num);
reverse(num,&rev);
check_palindrome(num,rev);
}
<file_sep>#include <stdio.h>
void input(float *marks);
void grades(float marks,char *grade[]);
void output(char *grade[]);
void main(){
float marks;
char *grade[3];
input(&marks);
grades(marks,grade);
output(grade);
}
void input(float *marks){
printf("Type the marks.");
float mar;
scanf("%f",&mar);
*marks = mar;
}
void grades(float marks,char *grade[]){
if (marks>95){
*grade = "A1\0";
}
else if(marks>85){
*grade = "A2\0";
}
else if(marks>75){
*grade = "B1\0";
}
else if (marks>60){
*grade = "B2\0";
}
else if(marks>45){
*grade = "C1\0";
}
else if(marks>40){
*grade = "C2\0";
}
else if(marks>35){
*grade = "D1\0";
}
else if(marks>30){
*grade = "D2\0";
}
else{
*grade = "E1\0";
}
}
void output(char *grade[]){
printf("Your grade is %s",*grade);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
void input(int *num){
printf("Enter a positive number N");
scanf("%d",num);
}
void print_primes(int num,int primes[],int *prime_count){
int count =0;
if(num<2){
printf("There are no prime numbers.");
exit(0);
}
primes[count] = 2;
count++;
int i,j,is_prime;
for(i=3;i<num;i+=2){
is_prime=1;
for(j=2;j<=(i/2);j++){
if((i%j)==0){
is_prime=0;
break;
}
}
if(is_prime==1){
primes[count] = i;
count++;
}
}
*prime_count = count;
}
void output(int primes[],int prime_count){
int i;
printf("[");
for(i=0;i<prime_count;i++){
printf("%d, ",primes[i]);
}
printf("]");
}
void main(){
int num;
input(&num);
int primes[num];
int prime_count;
print_primes(num,primes,&prime_count);
output(primes,prime_count);
}
<file_sep>#include <stdio.h>
void input(char str[]){
printf("Enter the string");
scanf("%s",str);
}
void copy_str(char str[],char new_str[]){
for(int i=0;i<100;i++){
if(str[i]!='\0'){
new_str[i] = str[i];
}
else{
break;
}
}
printf("Copied the string int a new string array.");
}
void main(){
char str[100];
input(str);
char new_str[100];
copy_str(str,new_str);
}
<file_sep>#include <stdio.h>
void input_dims(int *m,int *n){
printf("Enter the dimensions of matrix");
scanf("%d %d",m,n);
}
void input(int m,int n,float matrix[m][n]){
printf("Enter the values of the matrix");
int i,j;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("Enter the values of matrix[%d][%d]",i,j);
scanf("%f",&matrix[i][j]);
}
}
}
void is_symmetric(int m,int n,float matrix[m][n],float mat_trans[m][n],int *result){
int i,j,k,l;
float tmp[m],tmp1[m];
for(i=0;i<m;i++){
for(j=0;j<n;j++){
for(k=0;k<n;k++){
mat_trans[k][i]=matrix[i][k];
}
}
}
for(i=0;i<m;i++){
for(j=0;j<n;j++){
if(mat_trans[i][j]==matrix[i][j]){
*result = 0;
}
else{
*result = -1;
break;
}
if(result==-1){
break;
}
}
}
}
void main(){
int m,n;
input_dims(&m,&n);
float matrix[m][n],mat_trans[m][n];
input(m,n,matrix);
int i,j;
printf("Real matrix\n");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%f ",matrix[i][j]);
}
printf("\n");
}
int result;
is_symmetric(m,n,matrix,mat_trans,&result);
printf("Transpose matrix\n");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%f ",mat_trans[i][j]);
}
printf("\n");
}
if(result==0){
printf("THe matrix is a symmetric matrix");
}
else{
printf("The matrix is not a symmetric matrix");
}
}
<file_sep>#include <stdio.h>
void input_param(int *l,float *search){
printf("Enter the length of array and the element to be searched");
scanf("%d %f",l,search);
}
void input(int l,float array[l]){
int i;
printf("Enter the array elements");
for(i=0;i<l;i++){
printf("Enter the array[%d] element",i);
scanf("%f",&array[i]);
}
}
void linear_search(int l,float array[l],float search){
int i;
for(i=0;i<l;i++){
if(array[i]==search){
printf("The element to be searched is the %dth element in the array",i+1);
break;
}
if(i==l){
printf("The element was not found in the array");
}
}
}
void main(){
int l;
float search;
input_param(&l,&search);
float array[l];
input(l,array);
linear_search(l,array,search);
}
<file_sep>#include <stdio.h>
#include <math.h>
#include <complex.h>
struct roots{
float real1;
float real2;
float complex imaginary1;
float complex imaginary2;
};
struct quadratic{
float a;
float b;
float c;
};
void input(struct quadratic *q);
void compute(struct roots *r,struct quadratic q,float *d);
void output(struct roots r,float d);
void main(){
struct roots r;
struct quadratic q;
float d;
input(&q);
compute(&r,q,&d);
output(r,d);
}
void input(struct quadratic *q){
printf("Type the three coefficients of quadratic equation.");
scanf("%f %f %f",&q->a,&q->b,&q->c);
}
/*
* compute function recieves three parameters:
* input parameters q : coefficients a,b,c
* Outut parameters r,d : roots of the quadratic equation and value of d
* Return Parameter : Value of Discrminant
* Note: ( return value >= 0) If roots are not complex imaginary parts of r is zero
*/
void compute(struct roots *r,struct quadratic q,float *d){
*d=(q.b*q.b)-(4*q.a*q.c);
if (*d<0){
r->real1=(-q.b)/(2*q.a);
r->real2=r->real1;
float complex c = ((*d)/(4*q.a*q.a));
r->imaginary1=csqrt(c);
r->imaginary2=r->imaginary1;
}
else if (*d==0){
r->real1=(-q.b)/(2*q.a);
r->real2=r->real1;
r->imaginary1=0*I;
r->imaginary2=r->imaginary1;
}
else{
r->real1=(-q.b+sqrtf(*d))/(2*q.a);
r->real2=(-q.b-sqrtf(*d))/(2*q.a);
r->imaginary1=0*I;
r->imaginary2=r->imaginary1;
}
}
void output(struct roots r,float d){
if (d<0){
printf("The roots are complex %f + %fi and %f - %fi",r.real1,cimag(r.imaginary1),r.real2,cimag(r.imaginary2));
}
else if (d==0){
printf("The roots are real and equal %f and %f",r.real1,r.real2);
}
else{
printf("The roots are real and distinct %f and %f",r.real1,r.real2);
}
}
<file_sep>#include <stdio.h>
void swap(int *a,int *b){
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void main(){
int a=10,b=20;
swap(&a,&b);
printf("%d %d",a,b);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
struct matrix_dim{
int rows;
int col;
};
void input_dim(struct matrix_dim *mat1,struct matrix_dim *mat2){
printf("Enter the values of matrix 1 rows,cols");
scanf("%d %d",&mat1->rows,&mat1->col);
printf("Enter the values of matrix 2 rows,cols");
scanf("%d %d",&mat2->rows,&mat2->col);
if(mat1->col!=mat2->rows){
printf("Invalid matrix dimensions.");
exit(0);
}
}
void input(struct matrix_dim mat1,struct matrix_dim mat2,float matrix1[mat1.rows][mat1.col],float matrix2[mat2.rows][mat2.col]){
int i,j;
for(i=0;i<mat1.rows;i++){
for(j=0;j<mat1.col;j++){
printf("Enter the value of matrix1[%d][%d]",i,j);
scanf("%f",&matrix1[i][j]);
}
}
for(i=0;i<mat2.rows;i++){
for(j=0;j<mat2.col;j++){
printf("Enter the value of matrix2[%d][%d]",i,j);
scanf("%f",&matrix2[i][j]);
}
}
}
void multiply(struct matrix_dim mat1,struct matrix_dim mat2,float matrix_final[mat1.rows][mat2.col],float matrix1[mat1.rows][mat1.col],float matrix2[mat2.rows][mat2.col]){
int i,j,k;
float sum=0;
for(i=0;i<mat1.rows;i++){
for(j=0;j<mat2.col;j++){
for(k=0;k<mat1.col;k++){
sum = sum+matrix1[i][k]*matrix2[k][j];
}
matrix_final[i][j]=sum;
sum=0;
}
}
}
void print_matrix(struct matrix_dim mat1,struct matrix_dim mat2,float matrix_final[mat1.rows][mat2.col]){
int i,j;
printf("Matrix final is :\n");
for(i=0;i<mat1.rows;i++){
for(j=0;j<mat2.col;j++){
printf(" %f ",matrix_final[i][j]);
}
printf("\n");
}
}
void main(){
struct matrix_dim mat1;
struct matrix_dim mat2;
input_dim(&mat1,&mat2);
float matrix1[mat1.rows][mat1.col],matrix2[mat2.rows][mat2.col],matrix_final[mat1.rows][mat2.col];
input(mat1,mat2,matrix1,matrix2);
multiply(mat1,mat2,matrix_final,matrix1,matrix2);
int i,j;
printf("Matrix 1 is :\n");
for(i=0;i<mat1.rows;i++){
for(j=0;j<mat1.col;j++){
printf(" %f ",matrix1[i][j]);
}
printf("\n");
}
printf("Matrix 2 is :\n");
for(i=0;i<mat2.rows;i++){
for(j=0;j<mat2.col;j++){
printf(" %f ",matrix2[i][j]);
}
printf("\n");
}
print_matrix(mat1,mat2,matrix_final);
}
<file_sep>#include <stdio.h>
void input(int *m,int *n){
printf("Enter two numbers");
scanf("%d %d",m,n);
}
void swap(int *m,int *n){
int tmp;
tmp = *m;
*m = *n;
*n = tmp;
}
void main(){
int m,n;
input(&m,&n);
swap(&m,&n);
printf("The swapped numbers m = %d and n = %d",m,n);
}
<file_sep>#include <stdio.h>
void bubble_sort(float a[],float length);
void input_length(int *length);
void input_array(float a[],float length);
void output(float a[],float length);
void main(){
int length;
input_length(&length);
float a[length];
input_array(a,length);
bubble_sort(a,length);
output(a,length);
}
void input_length(int *length){
printf("Enter length of array");
int len;
scanf("%d",&len);
*length = len;
}
void input_array(float a[],float length){
printf("Enter the elements");
int i;
for(i=0;i<length;i++){
printf("Enter the value for a[%d]",i);
scanf("%f",&a[i]);
}
}
/*
bubble_sort receives 2 parameter:
INPUT PARAMETERS a[],length: array and length of array.
OUTPUT PARAMETERS sorted array a[]: sorted array
RETURN PARAMETERS : doesn't return anything.
*/
void bubble_sort(float a[],float length){
int i,j,swap_count;
float tmp;
for(i=0;i<length-1;i++){
swap_count=0;
for(j=0;j<length-i-1;j++){
if (a[j]>a[j+1]){
tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
swap_count++;
}
}
if(swap_count==0){
break;
}
}
}
void output(float a[],float length){
int i;
for(i=0;i<length;i++){
printf("%f \n",a[i]);
}
}<file_sep>#include <stdio.h>
void input(int *n){
printf("ENter the total number of fibonacci numbers.");
scanf("%d",n);
}
void fib(int n){
int count =0;
int i,fib;
int f1 =0;
int f2 = 1;
printf("%d ",f1);
printf("%d ",f2);
while(count<(n-2)){
fib = f1+f2;
f1 = f2;
f2 = fib;
printf("%d ",fib);
count++;
}
}
void main(){
int n;
input(&n);
fib(n);
}
<file_sep>#include <stdio.h>
#include <math.h>
struct complex{
float real;
float imaginary;
};
struct inputs{
float a;
float b;
float c;
};
struct real{
float root1;
float root2;
};
void input(struct inputs *i);
float compute(struct complex *c,struct real *r,struct inputs i);
void output(struct complex c,struct real r,float d);
void main(){
struct inputs i;
struct complex c;
struct real r;
float d;
input(&i);
d = compute(&c,&r,i);
output(c,r,d);
}
void input(struct inputs *i){
printf("Type the values of a,b,c");
scanf("%f %f %f",&i->a,&i->b,&i->c);
}
float compute(struct complex *c,struct real *r,struct inputs i){
float d;
d = (i.b*i.b) -(4*i.a*i.c);
if (d<0){
c->real = -i.b/(2*i.a);
c->imaginary = sqrt(-d)/(2*i.a);
}
else if (d==0){
r->root1 = -i.b/(2*i.a);
r->root2 = -i.b/(2*i.a);
}
else{
r->root1 = -i.b+sqrt(d);
r->root2 = -i.b-sqrt(d);
}
return d;
}
void output(struct complex c,struct real r,float d){
if (d<0){
printf("The roots are imaginary. %f + %fi and %f + %fi",c.real,c.imaginary,c.real,c.imaginary);
}
else if(d==0){
printf("The roots are equal. %f and %f",r.root1,r.root2);
}else{
printf("The roots are distinct. %f and %f",r.root1,r.root2);
}
}
<file_sep>#include <stdio.h>
void input(int *n,int *r){
printf("Enter the values of n and r");
scanf("%d %d",n,r);
}
void factorial(int num,int *fact){
int i;
*fact = 1;
for(i=1;i<=num;i++){
*fact = *fact*i;
}
}
void npr(int n,int r){
int n_fact;
factorial(n,&n_fact);
int n_r_fact;
factorial((n-r),&n_r_fact);
printf("npr value for n = %d and r = %d is = %d",n,r,(n_fact/n_r_fact));
}
void ncr(int n,int r){
int n_fact;
factorial(n,&n_fact);
int r_fact;
factorial(r,&r_fact);
int n_r_fact;
factorial((n-r),&n_r_fact);
printf("\nncr value for n = %d and r = %d is = %d ",n,r,(n_fact/(n_r_fact*r_fact)));
}
void main(){
int n,r;
input(&n,&r);
npr(n,r);
ncr(n,r);
}
<file_sep>#include <stdio.h>
void main(){
printf("Commiting C program on github.");
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float * input();
float * compute();
void output();
void main(){
float *p;
p = input();
/*int loop;
for(loop=0;loop<3;loop++)
printf("%f ",p[loop]);*/
float *c;
c = compute(p);
free(p);
/*if (c==NULL){
printf("The function doesn't have root.");
}else{
int loop1;
for(loop1=0;loop1<2;loop1++)
printf("%f ",c[loop1]);
}*/
output(c);
free(c);
}
/*1)To return a array we use asterisk
2)Since it is not possible to return local address because once
we come out of the function the local address is not used anymore
therefore it is important to import stdlib and call malloc to create space
so that , that particular memory address is returned.
*/
float * input(){
float *nums = malloc(sizeof(float)*3);
printf("Type the values for a,b,c and press enter after each number.");
scanf("%f %f %f",&nums[0],&nums[1],&nums[2]);
return nums;
}
/*1)To return an array we use asterisk
2)Since it is not possible to return local address because once
we come out of the function the local address is not used anymore
therefore it is important to import stdlib and call malloc to create space
so that , that particular memory address is returned.
3)I will first check if the function has roots and then return root if it has or else return NULL
4)For square root (sqrt) function I have used math.h header file.
*/
float * compute(float *arr){
float a,b,c;
a=arr[0];
b = arr[1];
c = arr[2];
float x_plus;
float x_minus;
float *results = malloc(sizeof(float)*3);
float d = (b*b)-4*a*c;
if (d<0){
float real,imaginary;
real = (-b)/(2*a);
imaginary = (sqrtf(-d))/(2*a);
results[0]=real;
results[1]=imaginary;
results[2]=d;
return results;
}
else{
x_plus = (-b + sqrtf(d))/(2*a);
x_minus = (-b - sqrtf(d))/(2*a);
results[0]=x_plus;
results[1]=x_minus;
results[2]=d;
}
return results;
}
/*1)To return a array we use asterisk
2)Printf is used fromm stdio.h header file to print on the terminal.
*/
void output(float *a){
if (a[2]<0){
printf("The given quadratic equation has imaginary roots. %f+i(%f) and %f-i(%f)",a[0],a[1],a[0],a[1]);
}
else{
printf("The two roots are %f %f",a[0],a[1]);
}
}<file_sep>#include <stdio.h>
void input_dim(int *l){
printf("Enter the length of the array");
scanf("%d",l);
}
void input(int l,float array[l]){
for(int i=0;i<l;i++){
printf("Enter the element array[%d]",i);
scanf("%f",&array[i]);
}
}
void selection_sort(int l,float array[l]){
int pos,tmp,pos_ele;
for(int i=0;i<(l-1);i++){
pos = i;
pos_ele = array[i];
for(int j=i+1;j<(l);j++){
if(pos_ele>array[j]){
pos = j;
}
}
if(pos!=i){
tmp = array[i];
array[i] = array[pos];
array[pos]=tmp;
}
}
}
void main(){
int l;
input_dim(&l);
float array[l];
input(l,array);
selection_sort(l,array);
printf("The sorted array is [");
for(int i=0;i<l;i++){
printf("%f, ",array[i]);
}
printf("]");
printf("The maximum element is %f and minimum element is %f",array[l-1],array[0]);
}
<file_sep>#include <stdio.h>
void input(int *rows){
printf("enter number of rows.");
scanf("%d",rows);
}
/*
print_triangle receives 1 parameter:
INPUT PARAMETERS rows: no. of rows of triangle
OUTPUT PARAMETERS printf: prints the triangle
RETURN PARAMETERS : doesn't return anything.
Note: It will print a triangle with equal sides of n number of rows.
*/
void print_triangle(int rows){
int i,white_space,j;
for(i=0;i<rows;i++){
white_space=(rows)-(i+1);
printf("%*s",white_space,"");
for(j=0;j<(2*(i+1)-1);j++){
printf("*");
}
printf("\n");
}
}
void main(){
int rows;
input(&rows);
print_triangle(rows);
}
<file_sep>#include <stdio.h>
struct student{
int roll;
char name[100];
char dept[100];
int marks;
char grade[10];
};
void input_data(int index,struct student *studs){
printf("Enter the student roll.");
scanf("%d",&studs->roll);
printf("Enter the student name.");
scanf("%s",studs->name);
printf("Enter the student dept.");
scanf("%s",studs->dept);
printf("Enter the student marks.");
scanf("%d",&studs->marks);
printf("Enter the student grade.");
scanf("%s",studs->grade);
}
void print_data(int length,struct student studs[],int roll){
int done = 0;
for(int i=0;i<length;i++){
if(studs[i].roll==roll){
printf("The student data is : %d %s %s %d %s",studs[i].roll,studs[i].name,studs[i].dept,studs[i].marks,studs[i].grade);
done = 1;
break;
}
}
if(done==0){
printf("THere is no such student.");
}
}
void get_roll(int *roll){
printf("Enter the roll number");
scanf("%d",roll);
}
void main(){
int roll,index=0;
struct student studs[100];
input_data(index,&studs[index]);
index++;
get_roll(&roll);
print_data(index,studs,roll);
}
<file_sep>#include <stdio.h>
void input_length(int *length);
void input_array(float a[],int length);
void input_search_ele(float *search);
void binary_search(float a[],float length,int *index,float search);
void output(int index);
void main(){
int length,index;
input_length(&length);
float a[length],search;
input_array(a,length);
input_search_ele(&search);
binary_search(a,length,&index,search);
output(index);
}
void input_length(int *length){
int len;
printf("Enter the length of array");
scanf("%d",&len);
*length = len;
}
void input_array(float a[],int length){
int i;
for(i=0;i<length;i++){
printf("Enter the value of a[%d]",i);
scanf("%f",&a[i]);
}
}
void input_search_ele(float *search){
float s;
printf("Enter the value to search");
scanf("%f",&s);
*search = s;
}
/*
binary_search receives 4 parameter:
INPUT PARAMETERS a[],length,search: array,it's length and element to be searched respc.
OUTPUT PARAMETERS index: Index of the element.
RETURN PARAMETERS : doesn't return anything.
*/
void binary_search(float a[],float length,int *index,float search){
int first_index,last_index,mid_index;
first_index=0;
last_index=length-1;
mid_index = (first_index+last_index)/2;
while(first_index<=last_index){
if(a[mid_index]==search){
*index = mid_index+1;
break;
}
else if(a[mid_index]<search){
first_index = mid_index+1;
}
else{
last_index = mid_index-1;
}
mid_index = (first_index+last_index)/2;
}
if(first_index>last_index){
*index = -1;
}
}
void output(int index){
if(index==-1){
printf("Your key element was not found in the given array");
}
else{
printf("The given element is located at %dth position.",index);
}
} | c467ca332df8e2abeffe4382659e61511cd81e6e | [
"C"
] | 26 | C | sbh69840/cpps-fasttrack | 9780c1a3cf23298894f46a871be2ddc442ff0cc6 | 3e77c52f137185e79295f8a19035843364ff706a | |
refs/heads/master | <file_sep>## This set of functions takes in a matrix and creates the inverse of it. If that calculation has
## already been done before, it knows to get the answer from the cache instead of recalculating
# this function gets a matrix and returns the inverse of the matrix
makeCacheMatrix <- function(x = matrix()) {
# m stores the cached inverse matrix
m <- NULL
# sets the matrix
set <- function (y) {
x <<- y
m <<- NULL
}
# gets the matrix
get <- function() x
# sets the inverse
setinverse <- function(solve) m <<- solve
# gets the inverse
getinverse <- function() m
# returns the matrix
list(set = set, get = get, setinverse = setinverse, getinverse = getinverse)
}
# this function checks to see of the matrix is cached, before it (re)calculates
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m<-x$getinverse()
#if the inverse is calculated, return it
if(!is.null(m)){
message("getting chached data")
return(m)
}
# The inverse isn't calculated yet, so do the calculation
data<-x$get()
m<-solve(data)
# cache inverse
x$setinverse(m)
# return inverse
m
}
| d5307c14db89e3d9a85424460beb7bc470a014d2 | [
"R"
] | 1 | R | rdolen/ProgrammingAssignment2 | 055077e5a4400558083a7d62da7ed5417b3bd26c | 99fb8e3dccbf947f7877f0626f72b0e0ea117530 | |
refs/heads/master | <file_sep>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "PathOpsExtendedTest.h"
#include "SkPath.h"
#include "SkPathOps.h"
#include "SkPoint.h"
#include "Test.h"
static const SkPoint nonFinitePts[] = {
{ SK_ScalarInfinity, 0 },
{ 0, SK_ScalarInfinity },
{ SK_ScalarInfinity, SK_ScalarInfinity },
{ SK_ScalarNegativeInfinity, 0},
{ 0, SK_ScalarNegativeInfinity },
{ SK_ScalarNegativeInfinity, SK_ScalarNegativeInfinity },
{ SK_ScalarNegativeInfinity, SK_ScalarInfinity },
{ SK_ScalarInfinity, SK_ScalarNegativeInfinity },
{ SK_ScalarNaN, 0 },
{ 0, SK_ScalarNaN },
{ SK_ScalarNaN, SK_ScalarNaN },
};
const size_t nonFinitePtsCount = sizeof(nonFinitePts) / sizeof(nonFinitePts[0]);
static const SkPoint finitePts[] = {
{ 0, 0 },
{ SK_ScalarMax, 0 },
{ 0, SK_ScalarMax },
{ SK_ScalarMax, SK_ScalarMax },
{ SK_ScalarMin, 0 },
{ 0, SK_ScalarMin },
{ SK_ScalarMin, SK_ScalarMin },
};
const size_t finitePtsCount = sizeof(finitePts) / sizeof(finitePts[0]);
static void failOne(skiatest::Reporter* reporter, int index) {
SkPath path;
int i = (int) (index % nonFinitePtsCount);
int f = (int) (index % finitePtsCount);
int g = (int) ((f + 1) % finitePtsCount);
switch (index % 13) {
case 0: path.lineTo(nonFinitePts[i]); break;
case 1: path.quadTo(nonFinitePts[i], nonFinitePts[i]); break;
case 2: path.quadTo(nonFinitePts[i], finitePts[f]); break;
case 3: path.quadTo(finitePts[f], nonFinitePts[i]); break;
case 4: path.cubicTo(nonFinitePts[i], finitePts[f], finitePts[f]); break;
case 5: path.cubicTo(finitePts[f], nonFinitePts[i], finitePts[f]); break;
case 6: path.cubicTo(finitePts[f], finitePts[f], nonFinitePts[i]); break;
case 7: path.cubicTo(nonFinitePts[i], nonFinitePts[i], finitePts[f]); break;
case 8: path.cubicTo(nonFinitePts[i], finitePts[f], nonFinitePts[i]); break;
case 9: path.cubicTo(finitePts[f], nonFinitePts[i], nonFinitePts[i]); break;
case 10: path.cubicTo(nonFinitePts[i], nonFinitePts[i], nonFinitePts[i]); break;
case 11: path.cubicTo(nonFinitePts[i], finitePts[f], finitePts[g]); break;
case 12: path.moveTo(nonFinitePts[i]); break;
}
SkPath result;
result.setFillType(SkPath::kWinding_FillType);
bool success = Simplify(path, &result);
REPORTER_ASSERT(reporter, !success);
REPORTER_ASSERT(reporter, result.isEmpty());
REPORTER_ASSERT(reporter, result.getFillType() == SkPath::kWinding_FillType);
reporter->bumpTestCount();
}
static void dontFailOne(skiatest::Reporter* reporter, int index) {
SkPath path;
int f = (int) (index % finitePtsCount);
int g = (int) ((f + 1) % finitePtsCount);
switch (index % 11) {
case 0: path.lineTo(finitePts[f]); break;
case 1: path.quadTo(finitePts[f], finitePts[f]); break;
case 2: path.quadTo(finitePts[f], finitePts[g]); break;
case 3: path.quadTo(finitePts[g], finitePts[f]); break;
case 4: path.cubicTo(finitePts[f], finitePts[f], finitePts[f]); break;
case 5: path.cubicTo(finitePts[f], finitePts[f], finitePts[g]); break;
case 6: path.cubicTo(finitePts[f], finitePts[g], finitePts[f]); break;
case 7: path.cubicTo(finitePts[f], finitePts[g], finitePts[g]); break;
case 8: path.cubicTo(finitePts[g], finitePts[f], finitePts[f]); break;
case 9: path.cubicTo(finitePts[g], finitePts[f], finitePts[g]); break;
case 10: path.moveTo(finitePts[f]); break;
}
SkPath result;
result.setFillType(SkPath::kWinding_FillType);
bool success = Simplify(path, &result);
REPORTER_ASSERT(reporter, success);
REPORTER_ASSERT(reporter, result.getFillType() != SkPath::kWinding_FillType);
reporter->bumpTestCount();
}
static void fuzz_59(skiatest::Reporter* reporter, const char* filename) {
SkPath path;
path.moveTo(SkBits2Float(0x430c0000), SkBits2Float(0xce58f41c)); // 140, -9.09969e+08f
path.lineTo(SkBits2Float(0x43480000), SkBits2Float(0xce58f419)); // 200, -9.09969e+08f
path.lineTo(SkBits2Float(0x42200000), SkBits2Float(0xce58f41b)); // 40, -9.09969e+08f
path.lineTo(SkBits2Float(0x43700000), SkBits2Float(0xce58f41b)); // 240, -9.09969e+08f
path.lineTo(SkBits2Float(0x428c0000), SkBits2Float(0xce58f419)); // 70, -9.09969e+08f
path.lineTo(SkBits2Float(0x430c0000), SkBits2Float(0xce58f41c)); // 140, -9.09969e+08f
path.close();
testSimplifyFuzz(reporter, path, filename);
}
static void fuzz_x1(skiatest::Reporter* reporter, const char* filename) {
SkPath path;
path.moveTo(SkBits2Float(0x00000000), SkBits2Float(0x00000000)); // 0, 0
path.cubicTo(SkBits2Float(0x1931204a), SkBits2Float(0x2ba1a14a), SkBits2Float(0x4a4a08ff), SkBits2Float(0x4a4a08ff), SkBits2Float(0x4a4a4a34), SkBits2Float(0x4a4a4a4a)); // 9.15721e-24f, 1.14845e-12f, 3.31014e+06f, 3.31014e+06f, 3.31432e+06f, 3.31432e+06f
path.moveTo(SkBits2Float(0x000010a1), SkBits2Float(0x19312000)); // 5.96533e-42f, 9.15715e-24f
path.cubicTo(SkBits2Float(0x4a6a4a4a), SkBits2Float(0x4a4a4a4a), SkBits2Float(0xa14a4a4a), SkBits2Float(0x08ff2ba1), SkBits2Float(0x08ff4a4a), SkBits2Float(0x4a344a4a)); // 3.83861e+06f, 3.31432e+06f, -6.85386e-19f, 1.53575e-33f, 1.53647e-33f, 2.95387e+06f
path.cubicTo(SkBits2Float(0x4a4a4a4a), SkBits2Float(0x4a4a4a4a), SkBits2Float(0x2ba1a14a), SkBits2Float(0x4e4a08ff), SkBits2Float(0x4a4a4a4a), SkBits2Float(0xa1a181ff)); // 3.31432e+06f, 3.31432e+06f, 1.14845e-12f, 8.47397e+08f, 3.31432e+06f, -1.09442e-18f
testSimplify(reporter, path, filename);
}
static void fuzz_x2(skiatest::Reporter* reporter, const char* filename) {
SkPath path;
path.moveTo(SkBits2Float(0x00000000), SkBits2Float(0x00000000)); // 0, 0
path.cubicTo(SkBits2Float(0x1931204a), SkBits2Float(0x2ba1a14a), SkBits2Float(0x4a4a08ff), SkBits2Float(0x4a4a08ff), SkBits2Float(0x4a4a4a34), SkBits2Float(0x4a4a4a4a)); // 9.15721e-24f, 1.14845e-12f, 3.31014e+06f, 3.31014e+06f, 3.31432e+06f, 3.31432e+06f
path.moveTo(SkBits2Float(0x000010a1), SkBits2Float(0x19312000)); // 5.96533e-42f, 9.15715e-24f
path.cubicTo(SkBits2Float(0x4a6a4a4a), SkBits2Float(0x4a4a4a4a), SkBits2Float(0xa14a4a4a), SkBits2Float(0x08ff2ba1), SkBits2Float(0x08ff4a4a), SkBits2Float(0x4a344a4a)); // 3.83861e+06f, 3.31432e+06f, -6.85386e-19f, 1.53575e-33f, 1.53647e-33f, 2.95387e+06f
path.cubicTo(SkBits2Float(0x4a4a4a4a), SkBits2Float(0x4a4a4a4a), SkBits2Float(0x2ba1a14a), SkBits2Float(0x4e4a08ff), SkBits2Float(0x4a4a4a4a), SkBits2Float(0xa1a181ff)); // 3.31432e+06f, 3.31432e+06f, 1.14845e-12f, 8.47397e+08f, 3.31432e+06f, -1.09442e-18f
testSimplify(reporter, path, filename);
}
static void fuzz763_1(skiatest::Reporter* reporter, const char* filename) {
SkPath path;
path.setFillType((SkPath::FillType) 0);
path.moveTo(SkBits2Float(0x00000000), SkBits2Float(0x00000000)); // 0, 0
path.cubicTo(SkBits2Float(0xbcb63000), SkBits2Float(0xb6b6b6b7), SkBits2Float(0x38b6b6b6), SkBits2Float(0xafb63a5a), SkBits2Float(0xca000087), SkBits2Float(0xe93ae9e9)); // -0.0222397f, -5.44529e-06f, 8.71247e-05f, -3.31471e-10f, -2.09719e+06f, -1.41228e+25f
path.quadTo(SkBits2Float(0xb6007fb6), SkBits2Float(0xb69fb6b6), SkBits2Float(0xe9e964b6), SkBits2Float(0xe9e9e9e9)); // -1.91478e-06f, -4.75984e-06f, -3.52694e+25f, -3.5348e+25f
path.quadTo(SkBits2Float(0xb6b6b8b7), SkBits2Float(0xb60000b6), SkBits2Float(0xb6b6b6b6), SkBits2Float(0xe9e92064)); // -5.44553e-06f, -1.90739e-06f, -5.44529e-06f, -3.52291e+25f
path.quadTo(SkBits2Float(0x000200e9), SkBits2Float(0xe9e9d100), SkBits2Float(0xe93ae9e9), SkBits2Float(0xe964b6e9)); // 1.83997e-40f, -3.53333e+25f, -1.41228e+25f, -1.72812e+25f
path.quadTo(SkBits2Float(0x40b6e9e9), SkBits2Float(0xe9b60000), SkBits2Float(0x00b6b8e9), SkBits2Float(0xe9000001)); // 5.71605f, -2.75031e+25f, 1.67804e-38f, -9.67141e+24f
path.quadTo(SkBits2Float(0xe9d3b6b2), SkBits2Float(0x40404540), SkBits2Float(0x803d4043), SkBits2Float(0xe9e9e9ff)); // -3.19933e+25f, 3.00423f, -5.62502e-39f, -3.53481e+25f
path.cubicTo(SkBits2Float(0x00000000), SkBits2Float(0xe8b3b6b6), SkBits2Float(0xe90a0003), SkBits2Float(0x4040403c), SkBits2Float(0x803d4040), SkBits2Float(0xe9e80900)); // 0, -6.78939e+24f, -1.0427e+25f, 3.00392f, -5.62501e-39f, -3.50642e+25f
path.quadTo(SkBits2Float(0xe9e910e9), SkBits2Float(0xe9e93ae9), SkBits2Float(0x0000b6b6), SkBits2Float(0xb6b6aab6)); // -3.52199e+25f, -3.52447e+25f, 6.55443e-41f, -5.4439e-06f
path.moveTo(SkBits2Float(0xe9e92064), SkBits2Float(0xe9e9d106)); // -3.52291e+25f, -3.53334e+25f
path.quadTo(SkBits2Float(0xe9e93ae9), SkBits2Float(0x0000abb6), SkBits2Float(0xb6b6bdb6), SkBits2Float(0xe92064b6)); // -3.52447e+25f, 6.15983e-41f, -5.44611e-06f, -1.2119e+25f
path.quadTo(SkBits2Float(0x0000e9e9), SkBits2Float(0xb6b6b6e9), SkBits2Float(0x05ffff05), SkBits2Float(0xe9ea06e9)); // 8.39112e-41f, -5.44532e-06f, 2.40738e-35f, -3.53652e+25f
path.quadTo(SkBits2Float(0xe93ae9e9), SkBits2Float(0x02007fe9), SkBits2Float(0xb8b7b600), SkBits2Float(0xe9e9b6b6)); // -1.41228e+25f, 9.44066e-38f, -8.76002e-05f, -3.53178e+25f
path.quadTo(SkBits2Float(0xe9e9e9b6), SkBits2Float(0xedb6b6b6), SkBits2Float(0x5a38a1b6), SkBits2Float(0xe93ae9e9)); // -3.53479e+25f, -7.06839e+27f, 1.29923e+16f, -1.41228e+25f
path.quadTo(SkBits2Float(0x0000b6b6), SkBits2Float(0xb6b6b6b6), SkBits2Float(0xe9e9e9b6), SkBits2Float(0xe9e9e954)); // 6.55443e-41f, -5.44529e-06f, -3.53479e+25f, -3.53477e+25f
path.quadTo(SkBits2Float(0xb6e9e93a), SkBits2Float(0x375837ff), SkBits2Float(0xceb6b6b6), SkBits2Float(0x0039e94f)); // -6.97109e-06f, 1.28876e-05f, -1.53271e+09f, 5.31832e-39f
path.quadTo(SkBits2Float(0xe9e9e9e9), SkBits2Float(0xe9e6e9e9), SkBits2Float(0xb6b641b6), SkBits2Float(0xede9e9e9)); // -3.5348e+25f, -3.48947e+25f, -5.43167e-06f, -9.0491e+27f
path.moveTo(SkBits2Float(0xb6b6e9e9), SkBits2Float(0xb6b60000)); // -5.45125e-06f, -5.42402e-06f
path.moveTo(SkBits2Float(0xe9b6b6b6), SkBits2Float(0xe9b6b8e9)); // -2.76109e+25f, -2.76122e+25f
path.close();
path.moveTo(SkBits2Float(0xe9b6b6b6), SkBits2Float(0xe9b6b8e9)); // -2.76109e+25f, -2.76122e+25f
path.quadTo(SkBits2Float(0xe93ae9e9), SkBits2Float(0xe964b6e9), SkBits2Float(0x0000203a), SkBits2Float(0xb6000000)); // -1.41228e+25f, -1.72812e+25f, 1.15607e-41f, -1.90735e-06f
path.moveTo(SkBits2Float(0x64b6b6b6), SkBits2Float(0xe9e9e900)); // 2.69638e+22f, -3.53475e+25f
path.quadTo(SkBits2Float(0xb6b6b6e9), SkBits2Float(0xb6b6b6b6), SkBits2Float(0xe9e9b6ce), SkBits2Float(0xe9e93ae9)); // -5.44532e-06f, -5.44529e-06f, -3.53179e+25f, -3.52447e+25f
testSimplifyFuzz(reporter, path, filename);
}
static void fuzz763_2(skiatest::Reporter* reporter, const char* filename) {
SkPath path;
path.setFillType((SkPath::FillType) 0);
path.moveTo(SkBits2Float(0x00000000), SkBits2Float(0x00000000)); // 0, 0
path.cubicTo(SkBits2Float(0x76773011), SkBits2Float(0x5d66fe78), SkBits2Float(0xbbeeff66), SkBits2Float(0x637677a2), SkBits2Float(0x205266fe), SkBits2Float(0xec296fdf)); // 1.25339e+33f, 1.0403e+18f, -0.00729363f, 4.54652e+21f, 1.78218e-19f, -8.19347e+26f
path.lineTo(SkBits2Float(0x00000000), SkBits2Float(0x00000000)); // 0, 0
path.close();
path.moveTo(SkBits2Float(0x00000000), SkBits2Float(0x00000000)); // 0, 0
path.quadTo(SkBits2Float(0xec4eecec), SkBits2Float(0x6e6f10ec), SkBits2Float(0xb6b6ecf7), SkBits2Float(0xb6b6b6b6)); // -1.00063e+27f, 1.84968e+28f, -5.45161e-06f, -5.44529e-06f
path.moveTo(SkBits2Float(0x002032b8), SkBits2Float(0xecfeb6b6)); // 2.95693e-39f, -2.46344e+27f
path.moveTo(SkBits2Float(0x73737300), SkBits2Float(0x73735273)); // 1.9288e+31f, 1.9278e+31f
path.cubicTo(SkBits2Float(0x1616ece4), SkBits2Float(0xdf020018), SkBits2Float(0x77772965), SkBits2Float(0x1009db73), SkBits2Float(0x80ececec), SkBits2Float(0xf7ffffff)); // 1.21917e-25f, -9.36751e+18f, 5.01303e+33f, 2.71875e-29f, -2.17582e-38f, -1.03846e+34f
path.lineTo(SkBits2Float(0x73737300), SkBits2Float(0x73735273)); // 1.9288e+31f, 1.9278e+31f
path.close();
path.moveTo(SkBits2Float(0x73737300), SkBits2Float(0x73735273)); // 1.9288e+31f, 1.9278e+31f
path.conicTo(SkBits2Float(0xec0700ec), SkBits2Float(0xecececec), SkBits2Float(0xececccec), SkBits2Float(0x772965ec), SkBits2Float(0x77777377)); // -6.52837e+26f, -2.2914e+27f, -2.29019e+27f, 3.4358e+33f, 5.0189e+33f
path.moveTo(SkBits2Float(0xfe817477), SkBits2Float(0xdf665266)); // -8.60376e+37f, -1.65964e+19f
path.close();
path.moveTo(SkBits2Float(0xfe817477), SkBits2Float(0xdf665266)); // -8.60376e+37f, -1.65964e+19f
path.quadTo(SkBits2Float(0x29ec02ec), SkBits2Float(0x1009ecec), SkBits2Float(0x80ececec), SkBits2Float(0xf7ffffff)); // 1.0481e-13f, 2.7201e-29f, -2.17582e-38f, -1.03846e+34f
path.lineTo(SkBits2Float(0xfe817477), SkBits2Float(0xdf665266)); // -8.60376e+37f, -1.65964e+19f
path.close();
path.moveTo(SkBits2Float(0xfe817477), SkBits2Float(0xdf665266)); // -8.60376e+37f, -1.65964e+19f
path.conicTo(SkBits2Float(0xff003aff), SkBits2Float(0xdbec2300), SkBits2Float(0xecececec), SkBits2Float(0x6fdf6052), SkBits2Float(0x41ecec29)); // -1.70448e+38f, -1.32933e+17f, -2.2914e+27f, 1.38263e+29f, 29.6153f
path.lineTo(SkBits2Float(0xfe817477), SkBits2Float(0xdf665266)); // -8.60376e+37f, -1.65964e+19f
path.close();
path.moveTo(SkBits2Float(0xfe817477), SkBits2Float(0xdf665266)); // -8.60376e+37f, -1.65964e+19f
path.quadTo(SkBits2Float(0xecf76e6f), SkBits2Float(0xeccfddec), SkBits2Float(0xecececcc), SkBits2Float(0x66000066)); // -2.39301e+27f, -2.01037e+27f, -2.2914e+27f, 1.51118e+23f
path.lineTo(SkBits2Float(0xfe817477), SkBits2Float(0xdf665266)); // -8.60376e+37f, -1.65964e+19f
path.close();
path.moveTo(SkBits2Float(0xfe817477), SkBits2Float(0xdf665266)); // -8.60376e+37f, -1.65964e+19f
path.cubicTo(SkBits2Float(0x772965df), SkBits2Float(0x77777377), SkBits2Float(0x77777876), SkBits2Float(0x665266fe), SkBits2Float(0xecececdf), SkBits2Float(0x0285806e)); // 3.4358e+33f, 5.0189e+33f, 5.0193e+33f, 2.48399e+23f, -2.2914e+27f, 1.96163e-37f
path.lineTo(SkBits2Float(0xecececeb), SkBits2Float(0xecec0700)); // -2.2914e+27f, -2.28272e+27f
path.lineTo(SkBits2Float(0xfe817477), SkBits2Float(0xdf665266)); // -8.60376e+37f, -1.65964e+19f
path.close();
path.moveTo(SkBits2Float(0xfe817477), SkBits2Float(0xdf665266)); // -8.60376e+37f, -1.65964e+19f
path.lineTo(SkBits2Float(0x65ecfaec), SkBits2Float(0xde777729)); // 1.39888e+23f, -4.45794e+18f
path.conicTo(SkBits2Float(0x74777777), SkBits2Float(0x66fe7876), SkBits2Float(0xecdf6660), SkBits2Float(0x726eecec), SkBits2Float(0x29d610ec)); // 7.84253e+31f, 6.00852e+23f, -2.16059e+27f, 4.73241e+30f, 9.50644e-14f
path.lineTo(SkBits2Float(0xfe817477), SkBits2Float(0xdf665266)); // -8.60376e+37f, -1.65964e+19f
path.close();
path.moveTo(SkBits2Float(0xd0ecec10), SkBits2Float(0x6e6eecdb)); // -3.17991e+10f, 1.84859e+28f
path.quadTo(SkBits2Float(0x003affec), SkBits2Float(0xec2300ef), SkBits2Float(0xecececdb), SkBits2Float(0xcfececec)); // 5.41827e-39f, -7.88237e+26f, -2.2914e+27f, -7.9499e+09f
path.lineTo(SkBits2Float(0xd0ecec10), SkBits2Float(0x6e6eecdb)); // -3.17991e+10f, 1.84859e+28f
path.close();
path.moveTo(SkBits2Float(0xd0ecec10), SkBits2Float(0x6e6eecdb)); // -3.17991e+10f, 1.84859e+28f
path.quadTo(SkBits2Float(0xecccec80), SkBits2Float(0xfa66ecec), SkBits2Float(0x66fa0000), SkBits2Float(0x772965df)); // -1.9819e+27f, -2.99758e+35f, 5.90296e+23f, 3.4358e+33f
path.moveTo(SkBits2Float(0x77777790), SkBits2Float(0x00807677)); // 5.01923e+33f, 1.17974e-38f
path.close();
path.moveTo(SkBits2Float(0x77777790), SkBits2Float(0x00807677)); // 5.01923e+33f, 1.17974e-38f
path.cubicTo(SkBits2Float(0xecececec), SkBits2Float(0xfe66eaec), SkBits2Float(0xecdf1452), SkBits2Float(0x806eecec), SkBits2Float(0x10ececec), SkBits2Float(0xec000000)); // -2.2914e+27f, -7.67356e+37f, -2.15749e+27f, -1.01869e-38f, 9.34506e-29f, -6.1897e+26f
path.lineTo(SkBits2Float(0x77777790), SkBits2Float(0x00807677)); // 5.01923e+33f, 1.17974e-38f
path.close();
path.moveTo(SkBits2Float(0x77777790), SkBits2Float(0x00807677)); // 5.01923e+33f, 1.17974e-38f
path.cubicTo(SkBits2Float(0x52668062), SkBits2Float(0x2965df66), SkBits2Float(0x77777377), SkBits2Float(0x76777773), SkBits2Float(0x1697fe78), SkBits2Float(0xeebfff00)); // 2.47499e+11f, 5.1042e-14f, 5.0189e+33f, 1.2548e+33f, 2.4556e-25f, -2.971e+28f
path.lineTo(SkBits2Float(0x77777790), SkBits2Float(0x00807677)); // 5.01923e+33f, 1.17974e-38f
path.close();
testSimplifyFuzz(reporter, path, filename);
}
static void fuzz_twister(skiatest::Reporter* reporter, const char* filename) {
SkPath path;
path.setFillType((SkPath::FillType) 0);
path.moveTo(0, 600);
path.lineTo(3.35544e+07f, 600);
path.lineTo(3.35544e+07f, 0);
path.lineTo(0, 0);
path.lineTo(0, 600);
path.close();
path.moveTo(63, 600);
path.lineTo(3.35545e+07f, 600);
path.lineTo(3.35545e+07f, 0);
path.lineTo(63, 0);
path.lineTo(63, 600);
path.close();
path.moveTo(93, 600);
path.lineTo(3.35545e+07f, 600);
path.lineTo(3.35545e+07f, 0);
path.lineTo(93, 0);
path.lineTo(93, 600);
path.close();
path.moveTo(123, 600);
path.lineTo(3.35546e+07f, 600);
path.lineTo(3.35546e+07f, 0);
path.lineTo(123, 0);
path.lineTo(123, 600);
path.close();
testSimplifyFuzz(reporter, path, filename);
}
static void fuzz_twister2(skiatest::Reporter* reporter, const char* filename) {
SkPath path;
path.moveTo(SkBits2Float(0x00000000), SkBits2Float(0x44160000)); // 0, 600
path.lineTo(SkBits2Float(0x4bfffffe), SkBits2Float(0x44160000)); // 3.35544e+07f, 600
path.lineTo(SkBits2Float(0x4bfffffe), SkBits2Float(0x00000000)); // 3.35544e+07f, 0
path.lineTo(SkBits2Float(0x00000000), SkBits2Float(0x00000000)); // 0, 0
path.lineTo(SkBits2Float(0x00000000), SkBits2Float(0x44160000)); // 0, 600
path.close();
path.moveTo(SkBits2Float(0x427c0000), SkBits2Float(0x00000000)); // 63, 0
path.lineTo(SkBits2Float(0x4c00000f), SkBits2Float(0x00000000)); // 3.35545e+07f, 0
path.lineTo(SkBits2Float(0x4c00000f), SkBits2Float(0x00000000)); // 3.35545e+07f, 0
path.lineTo(SkBits2Float(0x427c0000), SkBits2Float(0x00000000)); // 63, 0
path.close();
path.moveTo(SkBits2Float(0x42ba0000), SkBits2Float(0x00000000)); // 93, 0
path.lineTo(SkBits2Float(0x4c000016), SkBits2Float(0x00000000)); // 3.35545e+07f, 0
path.lineTo(SkBits2Float(0x4c000016), SkBits2Float(0x00000000)); // 3.35545e+07f, 0
path.lineTo(SkBits2Float(0x42ba0000), SkBits2Float(0x00000000)); // 93, 0
path.close();
path.moveTo(SkBits2Float(0x42f60000), SkBits2Float(0x00000000)); // 123, 0
path.lineTo(SkBits2Float(0x4c00001e), SkBits2Float(0x00000000)); // 3.35546e+07f, 0
path.lineTo(SkBits2Float(0x4c00001e), SkBits2Float(0x00000000)); // 3.35546e+07f, 0
path.lineTo(SkBits2Float(0x42f60000), SkBits2Float(0x00000000)); // 123, 0
path.close();
testSimplifyFuzz(reporter, path, filename);
}
static void fuzz994s_11(skiatest::Reporter* reporter, const char* filename) {
SkPath path;
path.setFillType((SkPath::FillType) 0);
path.moveTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x41f00000)); // 10, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x41f00000)); // 10, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.close();
path.moveTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x41f00000)); // 10, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x41f00000)); // 10, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.close();
path.moveTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x42b40000)); // 110, 90
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x41f00000)); // 110, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x41f00000)); // 10, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.close();
path.moveTo(SkBits2Float(0x41200000), SkBits2Float(0x41f00000)); // 10, 30
path.lineTo(SkBits2Float(0x46ff4c00), SkBits2Float(0x41f00000)); // 32678, 30
path.lineTo(SkBits2Float(0x46ff4c00), SkBits2Float(0x41f00000)); // 32678, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x41f00000)); // 10, 30
path.close();
path.moveTo(SkBits2Float(0x41200000), SkBits2Float(0x4c000006)); // 10, 3.35545e+07f
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x4c000006)); // 110, 3.35545e+07f
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x41f00000)); // 110, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x41f00000)); // 10, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x4c000006)); // 10, 3.35545e+07f
path.close();
path.moveTo(SkBits2Float(0x41200000), SkBits2Float(0x439d8000)); // 10, 315
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x439d8000)); // 110, 315
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x437f0000)); // 110, 255
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x437f0000)); // 10, 255
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x439d8000)); // 10, 315
path.close();
path.moveTo(SkBits2Float(0x00000000), SkBits2Float(0x42700000)); // 0, 60
path.lineTo(SkBits2Float(0x42c80000), SkBits2Float(0x42700000)); // 100, 60
path.lineTo(SkBits2Float(0x42c80000), SkBits2Float(0x00000000)); // 100, 0
path.lineTo(SkBits2Float(0x00000000), SkBits2Float(0x00000000)); // 0, 0
path.lineTo(SkBits2Float(0x00000000), SkBits2Float(0x42700000)); // 0, 60
path.close();
path.moveTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x42b40000)); // 110, 90
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x41f00000)); // 110, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x41f00000)); // 10, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.close();
path.moveTo(SkBits2Float(0x41200000), SkBits2Float(0x4c000006)); // 10, 3.35545e+07f
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x4c000006)); // 110, 3.35545e+07f
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x41f00000)); // 110, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x41f00000)); // 10, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x4c000006)); // 10, 3.35545e+07f
path.close();
path.moveTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x42b40000)); // 110, 90
path.lineTo(SkBits2Float(0x42dc0000), SkBits2Float(0x41f00000)); // 110, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x41f00000)); // 10, 30
path.lineTo(SkBits2Float(0x41200000), SkBits2Float(0x42b40000)); // 10, 90
path.close();
testSimplifyFuzz(reporter, path, filename);
}
static void fuzz994s_3414(skiatest::Reporter* reporter, const char* filename) {
SkPath path;
path.setFillType((SkPath::FillType) 0);
path.moveTo(SkBits2Float(0x42c80000), SkBits2Float(0x42480000)); // 100, 50
path.conicTo(SkBits2Float(0x42c80000), SkBits2Float(0x00000000), SkBits2Float(0x42480000), SkBits2Float(0x00000000), SkBits2Float(0x3f3504f3)); // 100, 0, 50, 0, 0.707107f
path.conicTo(SkBits2Float(0x00000000), SkBits2Float(0x00000000), SkBits2Float(0x00000000), SkBits2Float(0x42480000), SkBits2Float(0x3f3504f3)); // 0, 0, 0, 50, 0.707107f
path.conicTo(SkBits2Float(0x00000000), SkBits2Float(0x42c80000), SkBits2Float(0x42480000), SkBits2Float(0x42c80000), SkBits2Float(0x3f3504f3)); // 0, 100, 50, 100, 0.707107f
path.conicTo(SkBits2Float(0x42c80000), SkBits2Float(0x42c80000), SkBits2Float(0x42c80000), SkBits2Float(0x42480000), SkBits2Float(0x3f3504f3)); // 100, 100, 100, 50, 0.707107f
path.close();
path.moveTo(SkBits2Float(0x42c84964), SkBits2Float(0x42480000)); // 100.143f, 50
path.conicTo(SkBits2Float(0x42c84964), SkBits2Float(0x00000000), SkBits2Float(0x424892c8), SkBits2Float(0x00000000), SkBits2Float(0x3f3504f3)); // 100.143f, 0, 50.1433f, 0, 0.707107f
path.conicTo(SkBits2Float(0x3e12c788), SkBits2Float(0x00000000), SkBits2Float(0x3e12c788), SkBits2Float(0x42480000), SkBits2Float(0x3f3504f3)); // 0.143339f, 0, 0.143339f, 50, 0.707107f
path.conicTo(SkBits2Float(0x3e12c788), SkBits2Float(0x42c80000), SkBits2Float(0x424892c8), SkBits2Float(0x42c80000), SkBits2Float(0x3f3504f3)); // 0.143339f, 100, 50.1433f, 100, 0.707107f
path.conicTo(SkBits2Float(0x42c84964), SkBits2Float(0x42c80000), SkBits2Float(0x42c84964), SkBits2Float(0x42480000), SkBits2Float(0x3f3504f3)); // 100.143f, 100, 100.143f, 50, 0.707107f
path.close();
path.moveTo(SkBits2Float(0x42c80000), SkBits2Float(0x42480000)); // 100, 50
path.conicTo(SkBits2Float(0x42c80000), SkBits2Float(0x00000000), SkBits2Float(0x42480000), SkBits2Float(0x00000000), SkBits2Float(0x3f3504f3)); // 100, 0, 50, 0, 0.707107f
path.conicTo(SkBits2Float(0x00000000), SkBits2Float(0x00000000), SkBits2Float(0x00000000), SkBits2Float(0x42480000), SkBits2Float(0x3f3504f3)); // 0, 0, 0, 50, 0.707107f
path.conicTo(SkBits2Float(0x00000000), SkBits2Float(0x42c80000), SkBits2Float(0x42480000), SkBits2Float(0x42c80000), SkBits2Float(0x3f3504f3)); // 0, 100, 50, 100, 0.707107f
path.conicTo(SkBits2Float(0x42c80000), SkBits2Float(0x42c80000), SkBits2Float(0x42c80000), SkBits2Float(0x42480000), SkBits2Float(0x3f3504f3)); // 100, 100, 100, 50, 0.707107f
path.close();
path.moveTo(SkBits2Float(0x4c00006b), SkBits2Float(0x424c0000)); // 3.35549e+07f, 51
path.conicTo(SkBits2Float(0x4c00006b), SkBits2Float(0xcbffffe5), SkBits2Float(0x43d6e720), SkBits2Float(0xcbffffe5), SkBits2Float(0x3f3504f3)); // 3.35549e+07f, -3.35544e+07f, 429.806f, -3.35544e+07f, 0.707107f
path.conicTo(SkBits2Float(0xcbffff28), SkBits2Float(0xcbffffe5), SkBits2Float(0xcbffff28), SkBits2Float(0x424c0000), SkBits2Float(0x3f3504f3)); // -3.3554e+07f, -3.35544e+07f, -3.3554e+07f, 51, 0.707107f
path.conicTo(SkBits2Float(0xcbffff28), SkBits2Float(0x4c00000c), SkBits2Float(0x43d6e720), SkBits2Float(0x4c00000c), SkBits2Float(0x3f3504f3)); // -3.3554e+07f, 3.35545e+07f, 429.806f, 3.35545e+07f, 0.707107f
path.conicTo(SkBits2Float(0x4c00006b), SkBits2Float(0x4c00000c), SkBits2Float(0x4c00006b), SkBits2Float(0x424c0000), SkBits2Float(0x3f3504f3)); // 3.35549e+07f, 3.35545e+07f, 3.35549e+07f, 51, 0.707107f
path.close();
path.moveTo(SkBits2Float(0x43ef6720), SkBits2Float(0x42480000)); // 478.806f, 50
path.conicTo(SkBits2Float(0x43ef6720), SkBits2Float(0x00000000), SkBits2Float(0x43d66720), SkBits2Float(0x00000000), SkBits2Float(0x3f3504f3)); // 478.806f, 0, 428.806f, 0, 0.707107f
path.conicTo(SkBits2Float(0x43bd6720), SkBits2Float(0x00000000), SkBits2Float(0x43bd6720), SkBits2Float(0x42480000), SkBits2Float(0x3f3504f3)); // 378.806f, 0, 378.806f, 50, 0.707107f
path.conicTo(SkBits2Float(0x43bd6720), SkBits2Float(0x42c80000), SkBits2Float(0x43d66720), SkBits2Float(0x42c80000), SkBits2Float(0x3f3504f3)); // 378.806f, 100, 428.806f, 100, 0.707107f
path.conicTo(SkBits2Float(0x43ef6720), SkBits2Float(0x42c80000), SkBits2Float(0x43ef6720), SkBits2Float(0x42480000), SkBits2Float(0x3f3504f3)); // 478.806f, 100, 478.806f, 50, 0.707107f
path.close();
testSimplify(reporter, path, filename);
}
static void fuzz763_4713_b(skiatest::Reporter* reporter, const char* filename) {
SkPath path;
path.setFillType((SkPath::FillType) 0);
path.moveTo(SkBits2Float(0x42240000), SkBits2Float(0x42040000));
path.quadTo(SkBits2Float(0x42240000), SkBits2Float(0x4211413d), SkBits2Float(0x421aa09e), SkBits2Float(0x421aa09e));
path.quadTo(SkBits2Float(0x4211413d), SkBits2Float(0x42240000), SkBits2Float(0x42040000), SkBits2Float(0x42240000));
path.quadTo(SkBits2Float(0x41ed7d86), SkBits2Float(0x42240000), SkBits2Float(0x41dabec3), SkBits2Float(0x421aa09e));
path.quadTo(SkBits2Float(0x41c80000), SkBits2Float(0x4211413d), SkBits2Float(0x41c80000), SkBits2Float(0x42040000));
path.quadTo(SkBits2Float(0x41c80000), SkBits2Float(0x41ed7d86), SkBits2Float(0x41dabec3), SkBits2Float(0x41dabec3));
path.quadTo(SkBits2Float(0x41ed7d86), SkBits2Float(0x41c80000), SkBits2Float(0x42040000), SkBits2Float(0x41c80000));
path.quadTo(SkBits2Float(0x4211413d), SkBits2Float(0x41c80000), SkBits2Float(0x421aa09e), SkBits2Float(0x41dabec3));
path.quadTo(SkBits2Float(0x42240000), SkBits2Float(0x41ed7d86), SkBits2Float(0x42240000), SkBits2Float(0x42040000));
path.close();
path.moveTo(SkBits2Float(0x4204f72e), SkBits2Float(0x41c56cd2));
path.quadTo(SkBits2Float(0x42123842), SkBits2Float(0x41c52adf), SkBits2Float(0x421baed7), SkBits2Float(0x41d7bac6));
path.quadTo(SkBits2Float(0x4225256d), SkBits2Float(0x41ea4aad), SkBits2Float(0x42254667), SkBits2Float(0x4202666b));
path.quadTo(SkBits2Float(0x42256760), SkBits2Float(0x420fa77f), SkBits2Float(0x421c1f6c), SkBits2Float(0x42191e14));
path.quadTo(SkBits2Float(0x421bff97), SkBits2Float(0x42193e89), SkBits2Float(0x421bdf6b), SkBits2Float(0x42195eb8));
path.quadTo(SkBits2Float(0x421bbff6), SkBits2Float(0x42197f32), SkBits2Float(0x421ba03b), SkBits2Float(0x42199f57));
path.quadTo(SkBits2Float(0x421b605e), SkBits2Float(0x4219e00a), SkBits2Float(0x421b1fa8), SkBits2Float(0x421a1f22));
path.quadTo(SkBits2Float(0x421ae0f1), SkBits2Float(0x421a604b), SkBits2Float(0x421aa09e), SkBits2Float(0x421aa09e));
path.quadTo(SkBits2Float(0x4211413d), SkBits2Float(0x42240000), SkBits2Float(0x42040000), SkBits2Float(0x42240000));
path.quadTo(SkBits2Float(0x41ed7d86), SkBits2Float(0x42240000), SkBits2Float(0x41dabec3), SkBits2Float(0x421aa09e));
path.quadTo(SkBits2Float(0x41c80000), SkBits2Float(0x4211413d), SkBits2Float(0x41c80000), SkBits2Float(0x42040000));
path.quadTo(SkBits2Float(0x41c80000), SkBits2Float(0x41ed7d86), SkBits2Float(0x41dabec3), SkBits2Float(0x41dabec3));
path.quadTo(SkBits2Float(0x41db19b1), SkBits2Float(0x41da63d5), SkBits2Float(0x41db755b), SkBits2Float(0x41da0a9b));
path.quadTo(SkBits2Float(0x41dbce01), SkBits2Float(0x41d9ae59), SkBits2Float(0x41dc285e), SkBits2Float(0x41d952ce));
path.quadTo(SkBits2Float(0x41dc55b6), SkBits2Float(0x41d924df), SkBits2Float(0x41dc82cd), SkBits2Float(0x41d8f7cd));
path.quadTo(SkBits2Float(0x41dcaf1e), SkBits2Float(0x41d8ca01), SkBits2Float(0x41dcdc4c), SkBits2Float(0x41d89bf0));
path.quadTo(SkBits2Float(0x41ef6c33), SkBits2Float(0x41c5aec5), SkBits2Float(0x4204f72e), SkBits2Float(0x41c56cd2));
path.close();
testSimplify(reporter, path, filename);
}
static void fuzz864a(skiatest::Reporter* reporter,const char* filename) {
SkPath path;
path.moveTo(10, 90);
path.lineTo(10, 90);
path.lineTo(10, 30);
path.lineTo(10, 30);
path.lineTo(10, 90);
path.close();
path.moveTo(10, 90);
path.lineTo(10, 90);
path.lineTo(10, 30);
path.lineTo(10, 30);
path.lineTo(10, 90);
path.close();
path.moveTo(10, 90);
path.lineTo(110, 90);
path.lineTo(110, 30);
path.lineTo(10, 30);
path.lineTo(10, 90);
path.close();
path.moveTo(10, 30);
path.lineTo(32678, 30);
path.lineTo(32678, 30);
path.lineTo(10, 30);
path.close();
path.moveTo(10, 3.35545e+07f);
path.lineTo(110, 3.35545e+07f);
path.lineTo(110, 30);
path.lineTo(10, 30);
path.lineTo(10, 3.35545e+07f);
path.close();
path.moveTo(10, 315);
path.lineTo(110, 315);
path.lineTo(110, 255);
path.lineTo(10, 255);
path.lineTo(10, 315);
path.close();
path.moveTo(0, 60);
path.lineTo(100, 60);
path.lineTo(100, 0);
path.lineTo(0, 0);
path.lineTo(0, 60);
path.close();
path.moveTo(10, 90);
path.lineTo(110, 90);
path.lineTo(110, 30);
path.lineTo(10, 30);
path.lineTo(10, 90);
path.close();
path.moveTo(10, 3.35545e+07f);
path.lineTo(110, 3.35545e+07f);
path.lineTo(110, 30);
path.lineTo(10, 30);
path.lineTo(10, 3.35545e+07f);
path.close();
path.moveTo(10, 90);
path.lineTo(110, 90);
path.lineTo(110, 30);
path.lineTo(10, 30);
path.lineTo(10, 90);
path.close();
testSimplifyFuzz(reporter, path, filename);
}
#define TEST(test) test(reporter, #test)
DEF_TEST(PathOpsSimplifyFail, reporter) {
TEST(fuzz864a);
TEST(fuzz763_4713_b);
TEST(fuzz994s_3414);
TEST(fuzz994s_11);
TEST(fuzz_twister2);
TEST(fuzz_twister);
TEST(fuzz763_2);
TEST(fuzz763_1);
TEST(fuzz_x2);
TEST(fuzz_x1);
TEST(fuzz_59);
for (int index = 0; index < (int) (13 * nonFinitePtsCount * finitePtsCount); ++index) {
failOne(reporter, index);
}
for (int index = 0; index < (int) (11 * finitePtsCount); ++index) {
dontFailOne(reporter, index);
}
}
#undef TEST
DEF_TEST(PathOpsSimplifyFailOne, reporter) {
int index = 0;
failOne(reporter, index);
}
DEF_TEST(PathOpsSimplifyDontFailOne, reporter) {
int index = 17;
dontFailOne(reporter, index);
}
| ececdaebdc53fc41405c3ed798d763c1bc482da8 | [
"C++"
] | 1 | C++ | tmyibos/skia | 8f297c9994f864b1347d69c9b2c8795c7e8359b0 | b5d049151d837b36a8cf3bcc3289dfb00399df01 | |
refs/heads/master | <repo_name>EleDiaz/qml-rust<file_sep>/examples/listmodel_macro.rs
#[macro_use]
extern crate qml;
use qml::*;
Q_LISTMODEL!{
pub QTestModel {
name: String,
number: i32,
}
}
fn main() {
let mut qqae = QmlEngine::new();
let mut qalm = QTestModel::new();
qalm.insert_row("John".into(), 42);
qalm.insert_row("Oak".into(), 505);
// `&QTestModel` implements `Into<QVariant>`
qqae.set_and_store_property("listModel", qalm.get_qvar());
qqae.load_file("examples/listmodel.qml");
qalm.set_data(vec![("OMG".into(), 13317), ("HACKED".into(), 228)]);
qqae.exec();
qqae.quit();
}
<file_sep>/build.rs
extern crate pkg_config;
use std::env;
use std::process::Command;
use std::path::*;
use pkg_config::*;
fn main() {
Command::new("sh")
.arg("build_lib.sh")
.output()
.unwrap_or_else(|e| panic!("failed to execute process: {}", e));
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let path = Path::new(&manifest_dir).join("DOtherSide").join("build").join("lib");
println!("cargo:rustc-link-search=native={}", path.display());
println!("cargo:rerun-if-changed={}", path.display());
println!("cargo:rustc-link-lib=static=DOtherSideStatic");
println!("cargo:rustc-link-lib=dylib=stdc++");
Config::new().probe("Qt5Core Qt5Gui Qt5Qml Qt5Quick Qt5Widgets").unwrap();
}
<file_sep>/src/lib.rs
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(unused_variables)]
extern crate libc;
#[macro_use]
extern crate lazy_static;
mod qmlengine;
mod qvariant;
mod qabstractlistmodel;
mod qinthasharray;
mod utils;
mod qmodelindex;
mod types;
mod qurl;
mod qobject;
mod qmeta;
mod qtypes;
#[macro_use]
mod macros;
mod qmlregister;
pub use qmlengine::QmlEngine;
pub use qvariant::QVariant;
pub use qabstractlistmodel::{QModel, QAbstractListModel, QListModel};
pub use qmodelindex::QModelIndex;
pub use qobject::QObject;
pub use qmeta::{QObjectMacro, emit_signal};
pub use qtypes::*;
pub use qmlregister::QMLRegisterable;
#[doc(hidden)]
pub use libc::c_void;
#[doc(hidden)]
pub use qmlregister::{register_qml_type, register_qml_singleton_type};
<file_sep>/build_lib.sh
git clone https://github.com/filcuc/DOtherSide.git --single-branch --depth 1
cd DOtherSide
rm -rf build
mkdir build
cd build
cmake ..
make DOtherSideStatic
<file_sep>/examples/qobjects.rs
#[macro_use]
extern crate qml;
use qml::*;
pub struct Test;
impl Test {
pub fn launchGoose(&self, i: i32, i2: String) -> Option<&QVariant> {
println!("GOOSE HI from {} and {}", i2, i);
None
}
}
Q_OBJECT!(
pub Test as QTest{
signals:
fn testname (a: i32, b: i32);
slots:
fn launchGoose(i: i32, launchText: String);
properties:
});
fn main() {
let mut qqae = QmlEngine::new();
let mut qtest = QTest::new(Test);
qtest.testname(54, 55);
qtest.qslot_call("launchGoose",
vec![42.into(), "QML Rust".to_string().into()]);
println!("{:?}", qtest.qmeta());
}
<file_sep>/examples/qabstractlistmodel.rs
#[macro_use] extern crate qml;
use qml::*;
pub struct SimpleList(Vec<i32>);
impl QModel for SimpleList {
fn row_count(&self) -> i32 {
self.0.len() as i32
}
fn data(&self, index: QModelIndex, role: i32) -> QVariant {
QVariant::from(self.0[index.row() as usize])
}
fn roles_names(&self) -> Vec<String> {
vec!["name".to_string(), "number".to_string()]
}
fn flags(&self, index: QModelIndex) -> i32 {
0
}
}
// ...
fn main() {
let mut qqae = QmlEngine::new();
let model = SimpleList(vec![1,74,7,8,75]);
let mut qalm = QAbstractListModel::new(&model);
qqae.set_property("listModel", &qalm.get_qvar());
qqae.load_file("examples/listmodel.qml");
qqae.exec();
qqae.quit();
}
<file_sep>/examples/listmodel.rs
#[macro_use]
extern crate qml;
use qml::*;
fn main() {
let qqae = QmlEngine::new();
let mut qalm = QListModel::new(&["name", "number"]);
qalm.insert_row(qvarlist!["John", 42].into_iter());
qalm.insert_row(qvarlist!["Oak", 505].into_iter());
qqae.set_property("listModel", &qalm.get_qvar());
qqae.load_file("examples/listmodel.qml");
qalm.set_data(vec![qvarlist!["OMG", 13317], qvarlist!["HACKED", 228]]);
qqae.exec();
qqae.quit();
}
| cc6a88a2e628fd8b77f737a29b403c0f8338e8d8 | [
"Rust",
"Shell"
] | 7 | Rust | EleDiaz/qml-rust | 74b07b4d7a88ed1971bae1bb3395237d4be83d2d | aea65e2278c61b10350649eec51fa3cd3ab03d3b |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.