branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>#!/usr/bin/env bash if [ -z "$AWS_ACCESS_KEY_ID" ]; then echo "AWS_ACCESS_KEY_ID must be set" HAS_ERRORS=true fi if [ -z "$AWS_SECRET_ACCESS_KEY" ]; then echo "AWS_SECRET_ACCESS_KEY must be set" HAS_ERRORS=true fi if [ -z "$S3BUCKET" ]; then echo "S3BUCKET must be set" HAS_ERRORS=true fi if [ $HAS_ERRORS ]; then echo "Exiting.... " exit 1 fi if [ -z "$MYSQL_USER" ]; then MYSQL_USER='root' fi if [ -z "$MYSQL_PASSWORD" ]; then MYSQL_PASSWORD='<PASSWORD>' fi if [ -z "$MYSQL_HOST" ]; then MYSQL_HOST='mysql' fi if [ -z "$FILEPREFIX" ]; then FILEPREFIX='backup' fi FILENAME=$FILEPREFIX.latest.sql.gz echo "Starting backup (v4) ... $(date)" mysqldump --protocol tcp -u $MYSQL_USER -h $MYSQL_HOST -p$MYSQL_PASSWORD --all-databases > latest.sql gzip latest.sql aws s3api put-object --bucket $S3BUCKET --key $FILENAME --body latest.sql.gz echo "Cleaning up..." rm latest.sql.gz exit 0<file_sep>#!/usr/bin/env bash LOGFIFO='/var/log/cron.fifo' if [[ ! -e "$LOGFIFO" ]]; then touch "$LOGFIFO" fi tail -f "$LOGFIFO"<file_sep>#!/usr/bin/env bash if [ -z "$AWS_ACCESS_KEY_ID" ]; then echo "AWS_ACCESS_KEY_ID must be set" HAS_ERRORS=true fi if [ -z "$AWS_SECRET_ACCESS_KEY" ]; then echo "AWS_SECRET_ACCESS_KEY must be set" HAS_ERRORS=true fi if [ -z "$S3BUCKET" ]; then echo "S3BUCKET must be set" HAS_ERRORS=true fi if [ $HAS_ERRORS ]; then echo "Exiting.... " exit 1 fi if [ -z "$MYSQL_USER" ]; then MYSQL_USER='root' fi if [ -z "$MYSQL_PASSWORD" ]; then MYSQL_PASSWORD='<PASSWORD>' fi if [ -z "$MYSQL_HOST" ]; then MYSQL_HOST='mysql' fi if [ -z "$FILEPREFIX" ]; then FILEPREFIX='backup' fi if [ -z "$DELAY" ]; then DELAY='30' fi FILENAME=$FILEPREFIX.latest.sql.gz CRON_SCHEDULE=${CRON_SCHEDULE:-3 3 * * *} LOGFIFO='/var/log/cron.fifo' if [[ ! -e "$LOGFIFO" ]]; then touch "$LOGFIFO" fi CRON_ENV="MYSQL_USER='$MYSQL_USER'" CRON_ENV="$CRON_ENV\nAWS_ACCESS_KEY_ID='$AWS_ACCESS_KEY_ID'" CRON_ENV="$CRON_ENV\nAWS_SECRET_ACCESS_KEY='$AWS_SECRET_ACCESS_KEY'" CRON_ENV="$CRON_ENV\nS3BUCKET='$S3BUCKET'" CRON_ENV="$CRON_ENV\nMYSQL_PASSWORD='$MYSQL_PASSWORD'" CRON_ENV="$CRON_ENV\nMYSQL_HOST='$MYSQL_HOST'" CRON_ENV="$CRON_ENV\nPATH=$PATH" CRON_ENV="$CRON_ENV\nFILEPREFIX=$FILEPREFIX" echo -e "$CRON_ENV\n$CRON_SCHEDULE /backup > $LOGFIFO 2>&1" | crontab - crontab -l cron tail -f "$LOGFIFO"<file_sep>[![Docker Build Status](https://img.shields.io/docker/build/jaaaco/mysql-s3-backup-restore.svg)](https://hub.docker.com/r/jaaaco/mysql-s3-backup-restore/) # MySql S3 backup (with cron) / restore container Container can work in cron-mode and wait-mode: # Cron mode Default mode, container will make backups according to CRON_SCHEDULE env variable. # Wait mode In this mode cron is disabled, you may make backups / restores with docker exec (see below). To enable wait mode add command: /wait to your composition. # Backup command Container is making archive **in the same S3 file every time**. If you want backup file retention enable Versioning on S3 bucket and create S3 Life Cycle Rules to permanently delete older version after certain number of days. To make backup when container is running in cron-mode or wait-mode: ``` docker exec -it <container-id> backup ``` # Restore command ``` docker exec -it <container-id> backup ``` ## Usage Example docker-compose.yml: ``` version: '3.3' services: app: image: wordpress environment: WORDPRESS_DB_HOST: mysql WORDPRESS_DB_PASSWORD: <PASSWORD> mysql: image: mysql:5.7 environment: MYSQL_ROOT_PASSWORD: <PASSWORD> mysql-backup: image: mysql-backup environment: FILEPREFIX: wordpress/default S3BUCKET: <your-bucket-name-here> AWS_ACCESS_KEY_ID: <your-key-id-here> AWS_SECRET_ACCESS_KEY: <your-aws-secret-key-here> depends_on: - mysql ``` ## Required and optional ENV variables * AWS_ACCESS_KEY_ID - key for aws user with s3 put-object and get-object permissions * AWS_SECRET_ACCESS_KEY * S3BUCKET - S3 bucket name * FILEPREFIX - (optional) file prefix, defaults to "backup" * CRON_SCHEDULE - (optional) cron schedule, defaults to 3 3 * * * (at 3:03 am, every day) * MYSQL_HOST - (optional) database host name, defaults to "mysql" * MYSQL_USER - (optional) database user, defaults to "root" * MYSQL_PASSWORD - (optional) password, defaults to "<PASSWORD>"
4f8bb1dd6ebcff7311164209b098254fc858814a
[ "Markdown", "Shell" ]
4
Shell
jaaaco/mysql-s3-backup-restore
6dd1f27dffc53d5b603673088c5435ec51fabbe4
950b33c33c8d2b62bad8095e1fde13ce608b0951
refs/heads/master
<file_sep><h1>Jeu du troll</h1> <h2>Projet de Théorie des Jeux</h2> <h3>B2RJ - <NAME></h3> <p>In this project we had to confront two Artificial Intelligence using a cautious strategy. We added a random strategy.</br> After the end of the project, the ability to confront AI was implemented. </p> <h2>Getting started</h2> <p>To launch the program since the root : </p> `java -jar out/artifacts/jeudutroll_jar/jeudutroll.jar` <p>Each confrontation will take place 10 times with 20 stones on a board of 7 squares.</p> <file_sep>import java.util.Scanner; /** * This class inherits from the Strategy class.<br> * This class is used to game with humans * @author B2RJ */ public class StrategyHuman extends Strategy{ /** * The constructor * @param p The board */ public StrategyHuman(Board p) { super(p); } /** * Allows you to know how many stones player 2 can throw. * @param pJ1 The number of stone of player 1. * @param pJ2 The number of stone of the player 2. * The position of the troll. * The number of stones to be thrown. */ @Override int play(double pJ1, double pJ2, double posT) { int stones = -1; while (stones < 0 || stones > pJ2) { System.out.println("You have " + pJ2 + " stones and the troll is in " + posT); System.out.println("How many stones do you play ?"); Scanner sc = new Scanner(System.in); stones = sc.nextInt(); } return stones; } }<file_sep>import it.ssc.pl.milp.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import java.util.logging.LogManager; import static it.ssc.pl.milp.LP.NaN; /** * This class inherits the Strategy class.<br> * This class was created as part of the university project. * This class is characterized by : * <ul> * <li>A constant when there are no results found.</li> * <li>A map of moves played.</li> * <li>A string representing the head.</li> * <li>The number of stones thrown by the player.</li> * </ul> * @author B2RJ et <NAME> */ public class StrategySafe2 extends Strategy { /** * The constant that determines when we haven't found a match. */ private final double NOT_FOUND = 404; /** * The shot history map. * It allows you to search only once per situation. */ private HashMap<String, Double> map = new HashMap<>(); /** * The character string that goes into map. */ private String head; /** * The number of stones thrown by the player. */ private int rocks; /** * The builder of the PrudentStrategy class. * The builder iniatilizes the number of stones played to 1. * @param p The board that contains the number of stones and squares. */ public StrategySafe2(Board p) { super(p); this.rocks = 1; } /** * Getter of the map. * @return The map. */ public HashMap<String, Double> getMap() { return this.map; } /** * Setter of the map. * @param m The new map. */ public void setMap(HashMap<String, Double> m) { this.map = m; } /** * The function that plays strategy. * @param pJ1 The number of stones of player 1. * @param pJ2 The number of stone of player 2. * @param posT The position of the Troll. * @return The number of stones. played. */ @Override public int play(double pJ1, double pJ2, double posT) { this.head = pJ1 + "-" + pJ2 + "-" + posT; evalGopt(pJ1, pJ2, posT); return this.rocks; } /** * The function that looks for simple cases in the table. * @param pJ1 The number of stones of player 1. * @param pJ2 The number of stone of player 2. * @param posT The position of the Troll * @return The result of the confrontation. * <ul> * <li> 1 if the player wins the battle </li> * <li>-1 if the player loses the battle </li> * <li> 0 if there's a tie</li> * <li>NOT_FOUND if the case is not trivial</li> * </ul> */ public double dico(double pJ1, double pJ2, double posT) { //If a player win int nbBoxes = super.getBoard().getBoxes(); if (posT == ((nbBoxes - 1)/2)) { return 1; } if (posT == -((nbBoxes - 1)/2)) { return -1; } //If Player 1 has no more stones if (pJ1 == 0) { if (posT - pJ2 > 0) { return 1; } else if (posT - pJ2 == 0) { return 0; } else { return -1; } } //If Player 2 has no more stones if (pJ2 == 0) { if (posT + pJ1 > 0) { return 1; } else if (posT + pJ1 == 0) { return 0; } else { return -1; } } //equality if (pJ1 == pJ2 && posT == 0) { return 0; } return NOT_FOUND; } /** * The function that generates the table according to the parameters. * @param pJ1 The number of stone of player 1. * @param pJ2 The number of stone of player 2. * @param posT The position of the troll. * @return A 3D table with the calculation of the winnings. */ public double[][][] genGopt(double pJ1, double pJ2, double posT) { double[][][] goptTable = new double[(int) pJ1][(int) pJ2][3]; for (int line = 1; line <= pJ1; line++) { for (int column = 1; column <= pJ2; column = column + 2) { double t = posT; if (column > line) { t = posT -1; } else if (column < line) { t = posT +1; } goptTable[line-1][column-1] = new double[] {pJ1 - line, pJ2 - column, t}; } } return goptTable; } /** * The function that looks at trivial cases and then solves non-trivial cases. * @param pJ1 The number of stone of player 1. * @param pJ2 The number of stone of the player 2. * @param posT The position of the troll * @return The value of the gain. */ public double evalGopt(double pJ1, double pJ2, double posT) { double[][][] goptTable = genGopt(pJ1, pJ2, posT); double[][] evalTable = new double[(int) pJ1][(int) pJ2]; for (int line = 0; line < goptTable.length; line++) { for (int column = 1; column < goptTable[line].length; column = column + 2) { double j1 = goptTable[line][column][0]; double j2 = goptTable[line][column][1]; double pos = goptTable[line][column][2]; double resDico = dico(j1, j2, pos); if (resDico != NOT_FOUND) { evalTable[line][column] = resDico; } else { if (this.map.containsKey(j1 +","+ j2+","+ pos)) { evalTable[line][column] = map.get(j1 +","+ j2+","+ pos); } else { evalTable[line][column] = evalGopt(j1, j2, pos); this.map.put(j1 +","+ j2+","+ pos, evalTable[line][column]); } } } } ArrayList<Integer> linesNumber = new ArrayList<>(); double[][] withoutDomine = dominate(evalTable, linesNumber); double[] listeProb = simplexResolver(withoutDomine); if (listeProb.length > 0) { double t = listeProb[0]; if (this.head.equals(pJ1 + "-" + pJ2 + "-" + posT)) { this.rocks = throwRocks(listeProb, linesNumber); } return t; } else { return -4; } } /** * The function that determines the number of gems to play based on a probability on the possible gems. * @param listProb The probability table * @param linesNumber The dominated lines * @return The number of stone to throw */ public int throwRocks(double[] listProb, ArrayList<Integer> linesNumber) { double[] weights = new double[listProb.length -1]; for(int i = 1; i < listProb.length ; i++) { weights[i-1] = Math.round(listProb[i] * 1000.0); } ArrayList<Integer> probaTable = new ArrayList<>(); for(int w = 0 ; w < weights.length ; w++) { for(int i = 0; i < weights[w]; i++) { probaTable.add((linesNumber.get(w) + 1)); } } Random random = new Random(); int rock = random.nextInt(probaTable.size() + 1) ; if(rock >= probaTable.size()) { rock = probaTable.size() - 1; } return probaTable.get(rock); } /** * The function that eliminates dominated rows and columns. * @param evalTable The array to filter. * @param linesNumber The list of deleted lines. * @return The table without the dominated rows and columns. */ public double[][] dominate(double[][] evalTable, ArrayList<Integer> linesNumber) { double[][] evalTableWithoutLines = deleteLine(evalTable,linesNumber); return deleteColumn(evalTableWithoutLines); } /** * Delete dominated lines. * @param evalTable The table to be filtered. * @param linesNumber The list of deleted lines. * @return The filtered table. */ public double[][] deleteLine(double[][]evalTable, ArrayList<Integer> linesNumber) { ArrayList<Integer> LinesToDelete = new ArrayList<>(); for (int line = 0; line < evalTable.length; line ++) { boolean deleteLine = false; boolean finished = false; int counter = 0; while (!finished && counter < evalTable.length) { if (counter != line && !LinesToDelete.contains(counter)) { boolean delete = true; for (int column = 0; column < evalTable[line].length; column ++) { double value = evalTable[line][column]; double valueBis = evalTable[counter][column]; if (value > valueBis) { delete = false; break; } } if (delete) { deleteLine = true; finished = true; } } counter ++; } if (deleteLine) { LinesToDelete.add(line); } else { linesNumber.add(line); } } //Construction du tableau que l'on retourne double[][] result; if (LinesToDelete.size() != 0) { result = new double[evalTable.length - LinesToDelete.size()][]; int countLine = 0; for(int line = 0; line < evalTable.length; line ++) { if (!LinesToDelete.contains(line)) { result[countLine] = evalTable[line]; countLine++; } } } else { result = evalTable; } return result; } /** * Deletes columns where Player 2 dominates. * @param evalTable The array to be filtered. * @return The filtered table. */ public double[][] deleteColumn(double[][]evalTable) { ArrayList<Integer> ColumnsToDelete = new ArrayList<>(); int nbColumns = 0; if (evalTable.length > 0) { nbColumns = evalTable[0].length; for (int column = 0; column < nbColumns; column ++) { boolean deleteColumn = false; boolean finished = false; int counter = 0; while (!finished && counter < nbColumns) { if (counter != column && !ColumnsToDelete.contains(counter)) { boolean delete = true; for (int line = 0; line < evalTable.length; line ++) { double value = evalTable[line][column]; double valueBis = evalTable[line][counter]; if ((value * -1) > (valueBis * -1)) { delete = false; break; } } if (delete) { deleteColumn = true; finished = true; } } counter ++; } if (deleteColumn) { ColumnsToDelete.add(column); } } } //Construction du tableau que l'on retourne double[][] result; if (ColumnsToDelete.size() != 0) { result = new double[evalTable.length][nbColumns - ColumnsToDelete.size()]; for(int line = 0; line < evalTable.length; line ++) { int countColumn = 0; for(int column = 0; column < evalTable[line].length; column++) { if (!ColumnsToDelete.contains(column)) { result[line][countColumn] = evalTable[line][column]; countColumn++; } } } } else { result = evalTable; } return result; } /** * The function that handles the simplex * @param evalTable The table to be analyzed using the simplex. * @return The coordinates of the square to be played. */ public double[] simplexResolver(double[][] evalTable) { int nbColumns = 0; if (evalTable.length > 0) { nbColumns = evalTable[0].length; double[][] TableA = new double[nbColumns + 3][evalTable.length]; //On ecrit les equations pour chaque colonnes for (int column = 0; column < nbColumns; column ++) { int counter = 0; while (counter < nbColumns) { double[] columnA = new double[evalTable.length + 1]; columnA[0] = -1; for (int line = 0; line < evalTable.length; line ++) { double value = evalTable[line][column]; columnA[line+1] = value; } counter ++; TableA[column] = columnA; } } // on ajoute la ligne x1 + x2 + ... + Xn = 1 double[] columnA = new double[evalTable.length + 1]; columnA[0] = 0; for (int line = 0; line < evalTable.length; line ++) { columnA[line+1] = 1; } TableA[nbColumns] = columnA; // on ajoute la ligne Upper double[] columnUpper = new double[evalTable.length + 1]; for (int line = 0; line < evalTable.length+1; line ++) { columnUpper[line] = NaN; } TableA[nbColumns+1] = columnUpper; // on ajoute la ligne Lower double[] columnLower = new double[evalTable.length + 1]; columnLower[0] = NaN; for (int line = 1; line < evalTable.length+1; line ++) { columnLower[line] = 0; } TableA[nbColumns+2] = columnLower; double[] TableB = new double[nbColumns + 3]; for (int line = 0; line < nbColumns; line ++) { TableB[line] = 0; } TableB[nbColumns] = 1; TableB[nbColumns+1] = NaN; TableB[nbColumns+2] = NaN; double[] TableC = new double[evalTable.length + 1]; TableC[0] = 1; for (int line = 1; line < evalTable.length + 1; line ++) { TableC[line] = 0; } ConsType[] TableConsType = new ConsType[nbColumns + 3]; for (int line = 0; line < nbColumns; line ++) { TableConsType[line] = ConsType.GE; } TableConsType[nbColumns] = ConsType.EQ; TableConsType[nbColumns+1] = ConsType.UPPER; TableConsType[nbColumns+2] = ConsType.LOWER; try { return simplex(TableA, TableB, TableC, TableConsType); } catch (Exception e) { e.printStackTrace(); } } return new double[] {-3.0}; } /** * Function that solves simplex. * @param A The array that contains coefficients of each xi. * @param b The table that contains t representing the maximum gain. * @param c The table that contains the gain of each possible throw. * @param rel The array of ConsType. * @return The resolved simplex. * @throws Exception */ public double[] simplex(double[][] A, double[] b, double[] c, ConsType[] rel) throws Exception{ double[] solutions; LinearObjectiveFunction f = new LinearObjectiveFunction(c, GoalType.MAX); ArrayList< Constraint > constraints = new ArrayList<>(); for(int i=0; i < A.length; i++) { constraints.add(new Constraint(A[i], rel[i], b[i])); } LogManager.getLogManager().reset(); LP lp = new LP(f,constraints); SolutionType solution_type=lp.resolve(); if(solution_type==SolutionType.OPTIMUM) { Solution solution=lp.getSolution(); solutions = new double[solution.getVariables().length]; int counter = 0; for(Variable var : solution.getVariables()) { solutions[counter] = var.getValue(); counter++; } return solutions; } return new double[]{-2.0}; } }
7bcc28b46a91dc37cc2fd4a3db53ec64aef20f42
[ "Markdown", "Java" ]
3
Markdown
B2RJ/Troll_game
b44d8c5b18e312bb7348f718c950de0de8195a3e
92d88dca96aff6bc4e2d91cfef8aac9d3c98bfe6
refs/heads/master
<file_sep><?php header('Content-Type: text/css;charaset=utf-8'); print ".chat_block{background:#ced;}"; print "body{background-color:lightsteelblue;}".PHP_EOL; ?><file_sep># TECH-BASE_internship ## 概要 TECH-BASEのインターンでの制作物です。 PHPとMySQLを使った掲示板です。 ## 機能 1.送信機能 2.削除機能 3.編集機能 編集、削除はどちらも送信時に設定したパスワードを入力することで実行できます。 ## その他 途中ハッシュについて<https://qiita.com/h1y0r1n/items/a719d308503c28712287>から ```php:sample // $strから乱数で文字列を取得して、$saltにcryptのsaltを生成する $str = array_merge(range('a', 'z'), range('0', '9'), range('A', 'Z'),array(".","/")); // ランダムな文字列を22文字取得 $max = 22; // Blowfishをハッシュ形式に指定、ストレッチ用のコストパラメータを指定 $salt = <PASSWORD>$"; for ($i = 1; $i <= $max; $i++) { $salt .= $str[rand(0, count($str)-1)]; } // ハッシュ化 $hashedPassword = crypt($password, $salt); ``` の部分を引用させてもらいました。 <file_sep><?php header('Content-Type: text/html; charset=UTF-8'); //MySQLへの接続 $dsn='データベース名'; $user='ユーザ名'; $password='<PASSWORD>'; $pdo=new PDO($dsn,$user,$password); //テーブル作成 $make_sql = "CREATE TABLE IF NOT EXISTS bboard " ."(" ."id INT NOT NULL AUTO_INCREMENT PRIMARY KEY," ."name VARCHAR(32)," ."comment TEXT," ."time DATETIME," ."isDeleted BOOLEAN NOT NULL DEFAULT 0," ."password VARCHAR(255)," ."salt VARCHAR(255)" .");"; $stmt=$pdo->query($make_sql); //パスワードの判定 function judge_password($num,$password,$pdo){ $input_edit_sql="SELECT * FROM bboard WHERE id=$num"; $sever_password=$pdo->query($input_edit_sql)->fetchColumn(5); $sever_salt=$pdo->query($input_edit_sql)->fetchColumn(6); //入力されたパスワードをハッシュ $input_password = crypt($password, $sever_salt); if($sever_password===$input_password){ echo "正しいパスワードが入力されました<br>"; return true; }else{ return false; } } //送信POSTで受け取る値 $name=htmlspecialchars($_POST["name"]); $comment=str_replace(array("\r\n","\n","\r"),'<br>',$_POST["comment"]); $password=htmlspecialchars($_POST["password"]); $edit_Num=$_POST["edit_number"]; $edit=$_POST["mode"]; //送信機能 if((isset($comment))&&(isset($name))&&(!($comment===''))&&(!($name===''))&&(isset($password))&&(!($password===''))){ if(preg_match('/^[a-zA-Z0-9]{1,8}+$/',$password)){ //ハッシュする //https://qiita.com/h1y0r1n/items/a719d308503c28712287参考ここから // $strから乱数で文字列を取得して、$saltにcryptのsaltを生成する $str = array_merge(range('a', 'z'), range('0', '9'), range('A', 'Z'),array(".","/")); // ランダムな文字列を22文字取得 $max = 22; // Blowfishをハッシュ形式に指定、ストレッチ用のコストパラメータを指定 $salt = <PASSWORD>$"; for ($i = 1; $i <= $max; $i++) { $salt .= $str[rand(0, count($str)-1)]; } $hashedPassword = crypt($password, $salt); //https://qiita.com/h1y0r1n/items/a719d308503c28712287参考ここまで //hashのsaltとパスワードを送信する $time=date('Y-m-d H:i:s'); if($edit=="false"){ $send_sql=$pdo->prepare("INSERT INTO bboard (id,name,comment,time,password,salt) VALUES ('',:name,:comment,:time,:password,:salt)"); $send_sql->bindValue(':name',$name); $send_sql->bindValue(':comment',$comment); $send_sql->bindValue(':time',$time); $send_sql->bindValue(':password',$<PASSWORD>); $send_sql->bindValue(':salt',$salt); $send_sql->execute(); }else{ $edit_sql="UPDATE bboard SET name='$name',comment='$comment',time='$time',password='$<PASSWORD>',salt='$salt' WHERE id=$edit_Num"; $edit_result=$pdo->query($edit_sql); } }else{ echo "<font color='red'>"."パスワードは半角英数字8文字でお願いします"."</font><br>"; } }else{ echo " 文字を入力して下さい<br>"; } //削除機能 $delete_number=$_POST["delete"]; $delete_password=htmlspecialchars($_POST["delete_password"]); if((isset($delete_number))&&(is_numeric($delete_number))&&(isset($delete_password))&&(!($delete_password===''))){ //番号のデータが存在するかどうか $empty_check_sql="SELECT MAX(id) FROM bboard"; $max=$pdo->query($empty_check_sql)->fetchColumn(); if(($delete_number<1)||($max<$delete_number)){ echo "<font color='red'>".$delete_number."は存在しません</font><br>"; }else{ //削除済みかどうかの判定 $delete_check_sql="SELECT isDeleted FROM bboard WHERE id=$delete_number"; $delete_check_result=$pdo->query($delete_check_sql); $isDeleted = $delete_check_result->fetchAll(PDO::FETCH_ASSOC); $check= $isDeleted[0]['isDeleted']; if($check==1){//削除済みなら echo "<font color='red'>".$delete_number."は削除済みです</font><br>"; }else{ //パスワードの判定 $judge_bool=judge_password($delete_number,$delete_password,$pdo); if($judge_bool){ $delete_sql="UPDATE bboard SET isDeleted=1 WHERE id=$delete_number"; $delete_result=$pdo->query($delete_sql); echo "<font color='red'>".$delete_number."を削除しました</font><br>"; }else{ echo "<font color='red'>不正なパスワードです</font><br>"; } } } } //編集機能 $edit_name =""; $edit_comment=""; $input_edit_number=$_POST["edit"]; $edit_mode=false; $edit_password=htmlspecialchars($_POST["edit_password"]); if((isset($input_edit_number))&&(is_numeric($input_edit_number))&&(isset($edit_password))&&(!($edit_password===''))){//番号欄とパスワード欄が空じゃないなら $check_sql="SELECT COUNT(*) FROM bboard WHERE id=$input_edit_number"; $result=$pdo->query($check_sql)->fetchColumn(); if($result==1){//idの番号の投稿があるとき $delete_check_sql="SELECT isDeleted FROM bboard WHERE id=$input_edit_number"; $delete_check_result=$pdo->query($delete_check_sql); $isDeleted = $delete_check_result->fetchAll(PDO::FETCH_ASSOC); $check= $isDeleted[0]['isDeleted']; if($check==0){//編集する番号は削除済みかどうか $judge_bool=judge_password($input_edit_number,$edit_password,$pdo); if($judge_bool){ $input_edit_sql="SELECT * FROM bboard WHERE id=$input_edit_number"; $edit_name=$pdo->query($input_edit_sql)->fetchColumn(1); $edit_comment=$pdo->query($input_edit_sql)->fetchColumn(2); echo "<font color='blue'>".$input_edit_number."を編集します</font><br>"; echo "<font color='blue'>"."パスワードは再入力してください</font><br>"; $edit_mode=true; }else{ echo "<font color='red'>不正なパスワードです</font><br>"; } }else{ echo "<font color='red'>".$input_edit_number."は削除されています</font><br>"; } }else{ echo "<font color='red'>".$input_edit_number."は存在しません</font><br>"; } } ?> <!DOCTYPE html> <html lang="ja"> <head> <meta http-equiv="content-type" charset="utf-8"> <link rel="stylesheet" type="text/css" href="mission_4_css.php"> </head> <body> <form action="mission_4.php" method="POST"> <div> <span> 名前<br> </span> <input type="text" name="name" maxlength="16" value="<?php echo $edit_name; ?>" > </div> <div> <span> コメント<br> </span> <textarea name="comment" style="width:200px;height:50px;" ><?php echo $edit_comment; ?></textarea> </div> <div> <span> パスワード<br> </span> <input type="<PASSWORD>" name="password" value="" > </div> <input type="hidden" name="mode" value="<?php echo var_export($edit_mode); ?>" > <input type="hidden" name="edit_number" value="<?php echo $input_edit_number; ?>" > <input type="submit" value="送信"> </form> <form action="mission_4.php" method="POST" style="margin:5px;"> <input type="text" name="delete" placeholder="削除したい番号" value=""> <input type="<PASSWORD>" name="delete_password" placeholder="<PASSWORD>" value=""> <input type="submit" value="削除"> </form> <form action="mission_4.php" method="POST" style="margin:5px;"> <input type="text" name="edit" placeholder="編集したい番号" value=""> <input type="<PASSWORD>" name="edit_password" placeholder="<PASSWORD>" value=""> <input type="submit" value="編集"> </form> <?php //テーブル一覧を表示 //順番に並べ替えて$sort_resultに代入 $sort="SELECT * FROM bboard WHERE isDeleted=0 ORDER by id ASC"; $sort_results=$pdo->query($sort); foreach($sort_results as $row){ echo '<div class="chat_block">'; echo $row['id'].':'; echo $row['name']; echo '['.$row['time'].']<br>'; echo str_replace('&lt;br&gt;','<br>',htmlspecialchars($row['comment'])).'<br>'; echo '</div>'; } ?> </body>
c9ffbe7aeec2c07d89e5c09984e6357739b11ee4
[ "Markdown", "PHP" ]
3
PHP
nitta11/TECH-BASE_internship
f995e05bebe26d4a1c71f2c12b4b72988039118a
d8229cc580626010a8e529a7cf07bed32715ca26
refs/heads/master
<file_sep># Windows Volume Control from Arduino's USB Serial # I used an analog knob, so I cut the top and bottom about 20. <file_sep>##serial import import serial import serial.tools.list_ports import time ##volume import from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume ports = list(serial.tools.list_ports.comports()) for p in ports: ##print (str(p)[:4]) if str(p)[7:14] == "Arduino" : conport = str(p)[:4] ### def vol_fnc(volnum): numv = float(1/255*float(volnum)) sessions = AudioUtilities.GetAllSessions() for session in sessions: volume = session._ctl.QueryInterface(ISimpleAudioVolume) volume.SetMasterVolume(numv, None) ### ser = serial.Serial(conport, 9600) ##time.sleep(0.5) def read_ser(): if ser.readable(): res = ser.readline() volnum=res.decode()[:len(res)-1] if int(volnum) < 20 : volnum = 0 if int(volnum) > 235 : volnum = 255 vol_fnc(volnum) ##print(volnum) while True: read_ser()
5cdbb7a9d42393a48b12911e249e1f282d8fc12d
[ "Markdown", "Python" ]
2
Markdown
tmots/Py-Serial-Volume-controller
d5947d28338a244b5d3fcbfcc316905cfc36e438
ba47ffdb9cb048fe34993e885024c0c32a9cf729
refs/heads/master
<repo_name>fredlesser/image-gallery<file_sep>/js/index.js const images = [ { src: "img/afro-soul.jpg", id: 1, title: "Afro Soul Voyage", date: "2017-07-21", category: ["music", "art", "typography"], }, { src: "img/butterfly.jpg", id: 2, title: "Butterfly", date: "2017-07-14", category: ["geometry", "nature"], }, { src: "img/pistol.jpg", id: 3, title: "Pistol", date: "2017-06-19", category: ["pop-art"], }, { src: "img/electric.jpg", id: 4, title: "Electric", date: "2017-06-14", category: ["photo", "typography"], }, { src: "img/eye.jpg", id: 5, title: "Eye", date: "2017-05-21", category: ["typography", "psychedelia"], }, { src: "img/lovehearts.jpg", id: 6, title: "Lovehearts", date: "2017-05-24", category: ["psychedelia", "pop-art"], }, { src: "img/deadhead.jpg", id: 7, title: "Deadhead", date: "2017-08-11", category: ["pop-art", "tattooing"], }, { src: "img/singer.jpg", id: 8, title: "Singer", date: "2017-09-21", category: ["music", "art"], }, { src: "img/smoke.jpg", id: 9, title: "Smoke", date: "2017-09-14", category: ["music", "art"], }, { src: "img/codeseventeen.jpg", id: 10, title: "Code 17", date: "2017-07-16", category: ["photo", "typography"], }, { src: "img/angelheart.jpg", id: 11, title: "Angelheart", date: "2017-08-17", category: ["pop-art", "psychedelia"], }, { src: "img/shadows.jpg", id: 12, title: "Shadows", date: "2017-07-28", category: ["photo", "typography"], }, ]; const toolbar = document.querySelector('.toolbar'); const main = document.querySelector('main'); const menu = document.querySelector('.nav'); const thumbNails = document.querySelector('.thumbnails'); function createThumbs(source) { const thumbs = source.map(image => { return ` <li> <a href="#"> <div style="background-image: url(${image.src})" class="image-thumbnail"> <img src="${image.src}" id="${image.id}" hidden> </div> <h2>${image.title}</h2> </a> </li> `; }).join(''); thumbNails.innerHTML = thumbs; const links = document.querySelectorAll('.thumbnails a'); //Clicking a thumbnail link reveals the poster version and hides the menu links.forEach(link => { link.onclick = function(e) { e.preventDefault(); const imageSrc = this.querySelector('img').getAttribute('src'); menu.classList.add('toggled'); displayImage(imageSrc); } }); } createThumbs(images); function displayImage(imageSrc) { const html = ` <div style="background-image: url(${imageSrc})" class="image-container"> </div> <a href="#" class="close">x</a> `; //Render img and closeBtn main.innerHTML = html; //Fade in img const image = main.querySelector('.image-container'); menu.addEventListener('transitionend', function(){ image.classList.add('fade-in'); }); //Remove img and restore menu function removeImage() { image.classList.remove('fade-in'); image.addEventListener('transitionend', function(){ menu.classList.remove('toggled'); this.remove(); }); } //Click closeBtn to initiate removeImage function and remove closeBtn const closeBtn = main.querySelector('.close'); closeBtn.addEventListener('click', function(e){ e.preventDefault(); this.remove(); removeImage(); }); } //Order by date //Newest First function newestFirst() { const newest = images.sort((a, b) => a.date > b.date ? 1 : -1) createThumbs(images); } toolbar.querySelector('.btn--newest').addEventListener('click', function(){ newestFirst() }); //Oldest first function oldestFirst() { const oldest = images.sort((a, b) => a.date > b.date ? -1 : 1) createThumbs(images); } toolbar.querySelector('.btn--oldest').addEventListener('click', function(){ oldestFirst() }); //Create filterBtns function createFilterButtons() { const categories = images.map(image => image.category); const catsArray = [].concat.apply([], categories); const individualCats = Array.from(new Set(catsArray)); const catButtons = individualCats.map(catButton => { return ` <li> <button type="button" name="button" class="btn" data-filter="${catButton}">${catButton}</button> </li> `; }).join(''); document.querySelector('.filters').innerHTML = catButtons; } createFilterButtons() //Filter based on category function filterCategory() { const keyword = this.dataset['filter']; const categories = images.filter(image => image.category.includes(keyword)); createThumbs(categories); } const filterBtns = Array.from(toolbar.querySelectorAll('.btn[data-filter]')); filterBtns.forEach(filterBtn => { filterBtn.addEventListener('click', filterCategory) }) //Reset document.querySelector('.btn--reset').addEventListener('click', function() { createThumbs(images); });
e611704bec037822a3e0201bbb1663ffce638d85
[ "JavaScript" ]
1
JavaScript
fredlesser/image-gallery
dbd0528067e62de673a55b8c09fff3c8cb8f7bf3
bdcf8ee6225431f2916e2009c076f53d2100e2fc
refs/heads/master
<repo_name>KPetersonRed/school-domain-v-000<file_sep>/lib/school.rb class School attr_accessor :school_name, :roster def initialize(name) #passing in the name of the SCHOOL and setting it = to Instance Var @school_name = school_name @roster = {} end def add_student(student, grade) if @roster.empty? || @roster[grade] == nil #does the hash roster containe any values? Or does the key exist in the hash? @roster[grade] = [] #create an array for the grade key @roster[grade] << student #push the student name into the array for that key else @roster[grade] << student #the key exists so add additional name to array end end def grade(grade) @roster[grade] end def sort @roster.each_value { |students| students.sort!} end end
f7e2417069a412b9dfac63589edbd50af17fb9e1
[ "Ruby" ]
1
Ruby
KPetersonRed/school-domain-v-000
ba3e6e19cbdb49d7f85eb702e675425ed17caaa8
f9bc2ec515320cf84ec19886ba0a59b096fbdcf7
refs/heads/master
<file_sep>import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; class FileWriting { private void writeToFile(String list) throws IOException { File f = new File("C:\\Users\\cosmi\\Desktop/taburi.txt"); System.out.println(f); FileWriter fw = new FileWriter(f, true); System.out.println(fw); try { BufferedWriter bw = new BufferedWriter(fw); System.out.println(bw); bw.newLine(); bw.write(list); bw.flush(); bw.close(); } catch (Exception e) { System.out.println(e); } } }<file_sep># Real-Estatae Small app which should let the user create real-estate properties and then visualize them later in a basic way, by writing and reading in folders. The purpose of this app was to make something somewhat functional with just the basics learned in school.
2b931926a7ba1f05b11d823848655815a4601ca5
[ "Markdown", "Java" ]
2
Java
CosminBughu/RealEstate-JavaSwing
e268d8895cab759456d3c8563b803e2d36853067
02bf952ac96487b50a0d365f272ed68c4e48aab3
refs/heads/master
<file_sep>const express = require("express"); const router = express.Router(); const Place = require("../models/Place.js"); router.get("/places", (req, res, next) => { Place.find() .then(data => { res.render("places/index", { data }); }) .catch(error => { console.log(error); }); }); router.get("/new", (req, res) => res.render("places/new")); router.post("/new", (req, res, next) => { const { name, type } = req.body; let location = { type: "Point", coordinates: [req.body.longitude, req.body.latitude] }; const newPlace = new Place({ name, type, location }); newPlace .save() .then(data => { res.redirect("places"); }) .catch(error => { res.render("places/new", { data }); console.log(error); }); }); router.get("/places/:id/edit", (req, res, next) => { let placeId = req.params.id; Place.findById(placeId) .then(data => { res.render("places/edit", { data }); }) .catch(error => { console.log(error); }); }); router.post("/places/:id/delete", (req, res, next) => { let placeId = req.params.id; Place.findByIdAndRemove(placeId) .then(data => { res.redirect("/places"); }) .catch(error => { console.log(error); }); }); router.post("/places/:id/edit", (req, res, next) => { let location = { type: "Point", coordinates: [req.body.longitude, req.body.latitude] }; const { name, type } = req.body; Place.findByIdAndUpdate(req.params.id, { name, type, location }) .then(data => { res.redirect("/places"); }) .catch(error => { console.log(error); }); }); module.exports = router; <file_sep>// Place.forEach(r => // addMarker( // r.name, // { // lat: r.location.coordinates[0], // lng: r.location.coordinates[1] // }, // map // ) // ); // console.log(Place);
e13856aea12df64ccdfb51b8b42e7276d61e2a86
[ "JavaScript" ]
2
JavaScript
AaronReina/lab-coffee-and-books
a3fc3eb5ee704f48b18fda9de2dbff70b4b59f97
42783b4ee404039fce922c82f7714d45d3b88a49
refs/heads/master
<file_sep>using System; namespace Quantus.Modules { public class InitialPositionModule : IEmitterModule { /* BEGIN MODULE INTERFACE */ private static bool bEditable = false; private static bool bEnabled = false; private static bool bSpawn = true; private static bool bUpdate = false; private static string name = "Initial Position"; private static int priority = 2; private static uint bytes = 12; public bool Enabled { get { return bEnabled; } set { bEnabled = value; } } public bool Editable { get { return bEditable; } } public bool IsSpawnModule { get { return bSpawn; } } public bool IsUpdateModule { get { return bUpdate; } } public string ModuleName { get { return name; } } public uint RequiredBytes { get { return bytes; } } public int SortPriority { get { return priority; } } public string GenerateCode(ref IQuantusCodeGenerator generator) { throw new NotImplementedException(); } /* END MODULE INTERFACE */ } } <file_sep>using System; namespace Quantus.Model { [Flags] public enum EmitterModuleFlag { None = 0x00, InitCol = 1 << 0, InitSiz = 1 << 1, InitPos = 1 << 2, InitVel = 1 << 3, InitAcc = 1 << 4, LifeCol = 1 << 5, LifeSiz = 1 << 6, End = 0xFFFF, } } <file_sep>using System; using System.Linq; using System.Text; using System.CodeDom; using System.CodeDom.Compiler; using System.Reflection; using System.Collections.Generic; using Quantus.Model; namespace Quantus.Compiler { public abstract partial class QuantusCodeGenerator : IQuantusCodeGenerator { /* Fields */ private bool bInitialized = false; private bool bWritingLine = false; private bool bWritingObject = false; private bool bWritingVariable = false; private bool bWritingMethod = false; private bool bWritingCodeBlock = false; private string m_CurrentClassName = null; private string m_CurrentNamespace = null; private string m_CurrentMethodName = null; protected string m_CurrentLoopIndexName = null; private static CodeDomProvider m_Provider = null; private static StringBuilder m_Builder = null; private int m_LineCount = 0; private int m_NestingLevel = 0; private int m_EffectiveIndentation = 0; private static uint m_LoopVariableCounter = 0; private static uint m_ClassVariableCounter = 0; private static uint m_LocalVariableCounter = 0; private static uint m_StaticVariableCounter = 0; private static uint m_NextID = 0; private Dictionary<string, VariableSignature> m_GeneratedVariables = new Dictionary<string, VariableSignature>(); /* End of fields */ /* Properties */ /// <summary> /// /// </summary> public bool IsInitialized { get { return bInitialized; } } /// <summary> /// /// </summary> public bool IsWritingLine { get { return bWritingLine; } } /// <summary> /// /// </summary> public bool IsWritingObject { get { return bWritingObject; } } /// <summary> /// /// </summary> public bool IsWritingVariable { get { return bWritingVariable; } } /// <summary> /// /// </summary> public bool IsWritingMethod { get { return bWritingMethod; } } /// <summary> /// /// </summary> public bool IsWritingCodeBlock { get { return bWritingCodeBlock; } } /// <summary> /// /// </summary> public string CurrentClassName { get { return m_CurrentClassName; } } /// <summary> /// /// </summary> public string CurrentNamespace { get { return m_CurrentNamespace; } } /// <summary> /// /// </summary> public string CurrentMethodName { get { return m_CurrentMethodName; } } /// <summary> /// /// </summary> public static CodeDomProvider CodeProvider { get { return m_Provider; } } /// <summary> /// /// </summary> public static StringBuilder Builder { get { return m_Builder; } } /// <summary> /// /// </summary> public int LineCount { get { return m_LineCount; } } /// <summary> /// /// </summary> public int NestingLevel { get { return m_NestingLevel; } } /// <summary> /// /// </summary> public int EffectiveIndentation { get { return m_EffectiveIndentation; } } /// <summary> /// /// </summary> public static uint NextID { get { return m_NextID; } } /// <summary> /// /// </summary> public Dictionary<string, VariableSignature> GeneratedVariables { get { return m_GeneratedVariables; } } /* End of properties */ /* Public methods */ /// <summary> /// The main method to build source code /// Override this in custom code generators /// </summary> /// <param name="info"></param> /// <returns></returns> public abstract string GenerateSource(IQuantusBuildInfo info = null); /// <summary> /// Initialize the generators built in members /// Resets the generator /// </summary> public void Initialize() { m_LineCount = 0; m_NestingLevel = 0; m_Builder = new StringBuilder(); m_CurrentClassName = null; m_CurrentNamespace = null; m_CurrentMethodName = null; if (m_Provider == null) { m_Provider = CodeDomProvider.CreateProvider("CSharp"); } else { m_Provider = null; m_Provider = CodeDomProvider.CreateProvider("CSharp"); } bInitialized = true; } /* End of public methods */ /* Protected methods */ /// <summary> /// Initializes a new class header and opens the body for writing /// </summary> /// <param name="info"><see cref="IEmitterBuildInfo"/></param> /// <param name="name"></param> /// <param name="type"><see cref="EnumObjectType"/></param> /// <param name="access"><see cref="EnumAccessModifier"/></param> /// <param name="isUnsafe"></param> protected void OpenClass(IEmitterBuildInfo info, string name, EnumObjectType type = EnumObjectType.Class, EnumAccessModifier access = EnumAccessModifier.Default, bool isUnsafe = false) { OpenClass(info, name, new Type[] { null }, type, access, isUnsafe); } /// <summary> /// Initializes a new class header with a single interface and opens the body for writing /// </summary> /// <param name="info"><see cref="IEmitterBuildInfo"/></param> /// <param name="name"></param> /// <param name="interfaces"><see cref="Type"/> The interface to attach to the class. Discarded if not a valid interface</param> /// <param name="type"><see cref="EnumObjectType"/></param> /// <param name="access"><see cref="EnumAccessModifier"/></param> /// <param name="isUnsafe"></param> protected void OpenClass(IEmitterBuildInfo info, string name, Type interfaces, EnumObjectType type = EnumObjectType.Class, EnumAccessModifier access = EnumAccessModifier.Default, bool isUnsafe = false) { OpenClass(info, name, new Type[] { interfaces }, type, access, isUnsafe); } /// <summary> /// Initializes a new class header with a set of interfaces and opens its body for writing /// </summary> /// <param name="info"><see cref="IEmitterBuildInfo"/></param> /// <param name="name"></param> /// <param name="interfaces"><see cref="Type"/> The interfaces to attach to the class. Discarded if not a valid interface</param> /// <param name="type"><see cref="EnumObjectType"/></param> /// <param name="access"><see cref="EnumAccessModifier"/></param> /// <param name="isUnsafe"></param> protected void OpenClass(IEmitterBuildInfo info, string name, Type[] interfaces, EnumObjectType type = EnumObjectType.Class, EnumAccessModifier access = EnumAccessModifier.Default, bool isUnsafe = false) { m_CurrentClassName = name; bWritingObject = true; AppendBlockComment(QuantusConstants.GeneratedClassComment); GenerateClassHeader(name, interfaces, type, access, isUnsafe); OpenCodeBlock(); } /// <summary> /// Closes the opened class. /// Note: A class cannot be re-opened once it is closed /// </summary> /// <param name="info"><see cref="IEmitterBuildInfo"/></param> protected void CloseClass(IEmitterBuildInfo info) { CloseCodeBlock(); AppendFormattingChars(EnumFormatingCharacter.NewLine, 2); m_CurrentClassName = null; bWritingObject = false; } /// <summary> /// Generates a class header with an interface /// </summary> /// <param name="name"></param> /// <param name="interfaces"></param> /// <param name="type"><see cref="EnumObjectType"/></param> /// <param name="access"><see cref="EnumAccessModifier"/></param> /// <param name="isUnsafe"></param> protected void GenerateClassHeader(string name, Type interfaces = null, EnumObjectType type = EnumObjectType.Default, EnumAccessModifier access = EnumAccessModifier.Default, bool isUnsafe = false) { GenerateClassHeader(name, new Type[] { interfaces }, type, access, isUnsafe); } /// <summary> /// Generates a class header with multiple interfaces /// </summary> /// <param name="name"></param> /// <param name="interfaces"></param> /// <param name="type"><see cref="EnumObjectType"/></param> /// <param name="access"><see cref="EnumAccessModifier"/></param> /// <param name="isUnsafe"></param> protected void GenerateClassHeader(string name, Type[] interfaces = null, EnumObjectType type = EnumObjectType.Default, EnumAccessModifier access = EnumAccessModifier.Default, bool isUnsafe = false) { StartNewLine(); GenerateAccessModifier(access); GenerateSafetyDeclaration(isUnsafe); GenerateObjectTypeString(type); GenerateClassName(name); GenerateInterfaces(interfaces); EndLine(); } /// <summary> /// Generates a set of interfaces for a class header /// </summary> /// <param name="interfaces"></param> protected void GenerateInterfaces(Type[] interfaces) { if (interfaces != null) { List<Type> valid = interfaces.Where(i => i != null) .Where(i => i.IsInterface == true) .ToList(); if (valid.Count > 0) { AppendSpaced(":"); } foreach (Type item in valid) { Builder.Append(m_Provider.GetTypeOutput(new CodeTypeReference(item))); if (item != valid.Last()) { AppendPacked(", "); } } } } /// <summary> /// Generates a class name /// </summary> /// <param name="name"></param> protected void GenerateClassName(string name) { AppendSpaced(name); } /// <summary> /// Conditionally generates an 'unsafe' keyword /// </summary> /// <param name="isUnsafe"></param> protected void GenerateSafetyDeclaration(bool isUnsafe) { if (isUnsafe) { AppendKeyword(EnumKeywords.Unsafe); } } /// <summary> /// /// </summary> /// <param name="type"></param> protected void GenerateObjectTypeString(EnumObjectType type) { switch (type) { case EnumObjectType.Class: { AppendSpaced("class"); break; } case EnumObjectType.Struct: { AppendPacked("struct"); break; } } } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="vtype"></param> /// <param name="vinit"></param> /// <param name="access"></param> protected void GenerateVariable(string name, Type vtype, object vinit = null, EnumAccessModifier access = EnumAccessModifier.Default) { VariableSignature signature = GenerateVariableSignature(name, vtype, EnumVariableScope.Class); bWritingVariable = true; StartNewLine(); GenerateAccessModifier(access); GenerateTypeString(vtype); GenerateVariableName(signature.SourceName); if (vinit != null) { GenerateVariableInitialization(vinit); } EndLineWithSemi(); bWritingVariable = false; AddVariable(name, signature); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="vtype"></param> /// <param name="vinit"></param> /// <param name="access"></param> protected void GenerateConstant(string name, Type vtype, object vinit, EnumAccessModifier access = EnumAccessModifier.Default) { VariableSignature signature = GenerateVariableSignature(name, vtype, EnumVariableScope.Class); bWritingVariable = true; StartNewLine(); GenerateAccessModifier(access); GenerateConstModifier(); GenerateTypeString(vtype); GenerateVariableName(signature.SourceName); GenerateVariableInitialization(vinit); EndLineWithSemi(); bWritingVariable = false; AddVariable(name, signature); } /// <summary> /// /// </summary> /// <param name="vtype"></param> /// <param name="vinit"></param> protected void GenerateLocal(Type vtype, object vinit) { string name = GenerateVariableSourceName(vtype, EnumVariableScope.Local); VariableSignature signature = GenerateVariableSignature(name, vtype, EnumVariableScope.Local); bWritingVariable = true; bool WasWriting = bWritingLine; if (!bWritingLine) { StartNewLine(); } GenerateTypeString(vtype); GenerateVariableName(signature.SourceName); if (vinit != null) { GenerateVariableInitialization(vinit); } if (!WasWriting) { EndLineWithSemi(); } bWritingVariable = false; AddVariable(signature.SourceName, signature); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="vtype"></param> /// <param name="vinit"></param> protected void GenerateLocal(string name, Type vtype, object vinit) { VariableSignature signature = GenerateVariableSignature(name, vtype, EnumVariableScope.Local); bWritingVariable = true; bool WasWriting = bWritingLine; if (!bWritingLine) { StartNewLine(); } GenerateTypeString(vtype); GenerateVariableName(signature.SourceName); if (vinit != null) { GenerateVariableInitialization(vinit); } if (!WasWriting) { EndLineWithSemi(); } bWritingVariable = false; AddVariable(name, signature); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="vtype"></param> /// <param name="scope"></param> /// <returns></returns> protected VariableSignature GenerateVariableSignature(string name, Type vtype, EnumVariableScope scope) { string sourceName = GenerateVariableSourceName(vtype, scope); VariableSignature signature = new VariableSignature(name, sourceName, vtype); return signature; } /// <summary> /// /// </summary> /// <param name="vtype"></param> /// <param name="scope"></param> /// <returns></returns> protected string GenerateVariableSourceName(Type vtype, EnumVariableScope scope) { string sourceName = null; switch (scope) { case EnumVariableScope.Class: sourceName = "var_" + m_ClassVariableCounter++.ToString("D" + 3); break; case EnumVariableScope.Local: sourceName = "local_" + m_LocalVariableCounter++.ToString("D" + 1); break; case EnumVariableScope.Static: sourceName = "static_" + m_StaticVariableCounter++.ToString("D" + 3); break; } return sourceName; } /// <summary> /// /// </summary> /// <param name="vinit"></param> protected void GenerateVariableInitialization(object vinit) { Type type = vinit.GetType(); CodeTypeReference reference = new CodeTypeReference(type); PropertyInfo info = type.GetRuntimeProperty("value"); AppendPacked(" = " + vinit); } /// <summary> /// /// </summary> /// <param name="name"></param> protected void GenerateVariableName(string name) { AppendPacked(name); } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="name"></param> protected void OpenMethod(IEmitterBuildInfo info, string name) { OpenMethod(info, name, EnumAccessModifier.Default, null, null); } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="name"></param> /// <param name="access"></param> /// <param name="returns"></param> /// <param name="parameters"></param> protected void OpenMethod(IEmitterBuildInfo info, string name, EnumAccessModifier access, Type returns, params Type[] parameters) { m_CurrentMethodName = name; GenerateMethodSignature(name, access, returns, parameters); OpenCodeBlock(); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="access"></param> /// <param name="returns"></param> /// <param name="parameters"></param> protected void GenerateMethodSignature(string name, EnumAccessModifier access, Type returns, params Type[] parameters) { StartNewLine(); GenerateAccessModifier(access); GenerateReturnType(returns); GenerateMethodName(name); GenerateMethodParameterList(parameters); EndLine(); } /// <summary> /// /// </summary> /// <param name="parameters"></param> protected void GenerateMethodParameterList(params Type[] parameters) { AppendPacked("("); if (parameters.Length > 0) { int parameterCount = 0; foreach (Type vtype in parameters) { parameterCount++; string tName = ResolveTypeOutputName(vtype); GenerateLocal(vtype, null); } } AppendPacked(")"); } /// <summary> /// /// </summary> /// <param name="name"></param> protected void GenerateMethodName(string name) { AppendPacked(name); } /// <summary> /// /// </summary> /// <param name="returns"></param> protected void GenerateReturnType(Type returns) { if (returns == null) { AppendKeyword(EnumKeywords.Void); } else { AppendSpaced(ResolveTypeOutputName(returns)); } } /// <summary> /// /// </summary> protected void CloseMethod() { CloseCodeBlockWithComment(CurrentMethodName); m_CurrentMethodName = null; } /// <summary> /// /// </summary> /// <param name="vtype"></param> protected void GenerateTypeString(Type vtype) { AppendSpaced(ResolveTypeOutputName(vtype)); } /// <summary> /// /// </summary> protected void OpenForLoop(int vfrom, int vto) { GenerateLoopHeader(EnumLoopType.ForLoop, EnumForLoopPattern.LiteralLiteral, vfrom, vto); OpenCodeBlock(); } /// <summary> /// /// </summary> protected void OpenForLoop(int vfrom, string vto) { GenerateLoopHeader(EnumLoopType.ForLoop, EnumForLoopPattern.LiteralVariable, vfrom, vto); OpenCodeBlock(); } /// <summary> /// /// </summary> protected void OpenForLoop(string vfrom, int vto) { GenerateLoopHeader(EnumLoopType.ForLoop, EnumForLoopPattern.VariableLiteral, vfrom, vto); OpenCodeBlock(); } /// <summary> /// /// </summary> protected void OpenForLoop(string vfrom, string vto) { GenerateLoopHeader(EnumLoopType.ForLoop, EnumForLoopPattern.VariableVariable, vfrom, vto); OpenCodeBlock(); } protected void CloseForLoop() { CloseCodeBlock(); m_CurrentLoopIndexName = null; m_LoopVariableCounter = 0; } protected void GenerateLoopHeader(EnumLoopType type, EnumForLoopPattern pattern, object from, object to) { StartNewLine(); AppendKeyword(EnumKeywords.For); AppendPacked("("); m_CurrentLoopIndexName = ("L" + m_LocalVariableCounter); string source; switch (pattern) { case EnumForLoopPattern.LiteralLiteral: GenerateLocal("L" + m_LocalVariableCounter, typeof(int), 0); source = String.Format("; {0} < {2}; {0}++", m_GeneratedVariables[m_CurrentLoopIndexName].SourceName, ((int)from), ((int)to)); AppendPacked(source); break; case EnumForLoopPattern.LiteralVariable: GenerateLocal("L" + m_LocalVariableCounter, typeof(int), 0); source = String.Format("; {0} < {2}; {0}++", m_GeneratedVariables[m_CurrentLoopIndexName].SourceName, ((int)from), ((string)to)); AppendPacked(source); break; } AppendPacked(")"); EndLine(); } /// <summary> /// /// </summary> protected void GenerateConstModifier() { AppendSpaced("const"); } /// <summary> /// /// </summary> /// <param name="access"></param> protected void GenerateAccessModifier(EnumAccessModifier access) { switch (access) { case EnumAccessModifier.Public: AppendKeyword(EnumKeywords.Public); break; case EnumAccessModifier.Private: AppendKeyword(EnumKeywords.Private); break; case EnumAccessModifier.Protected: AppendKeyword(EnumKeywords.Protected); break; case EnumAccessModifier.Internal: AppendKeyword(EnumKeywords.Internal); break; } } /// <summary> /// /// </summary> protected void AddLine() { AppendPacked(Environment.NewLine); m_EffectiveIndentation = 0; m_LineCount++; } /// <summary> /// /// </summary> /// <param name="type"></param> /// <returns></returns> protected static string ResolveTypeOutputName(Type type) { CodeTypeReference reference = new CodeTypeReference(type); return m_Provider.GetTypeOutput(reference); } /// <summary> /// /// </summary> protected void AppendIndentation() { if(EffectiveIndentation > NestingLevel) { m_EffectiveIndentation = NestingLevel; } while(EffectiveIndentation < NestingLevel) { #if DEBUG_PRINT_WHITESPACE m_Builder.Append("--->"); #else Builder.Append("\t"); #endif m_EffectiveIndentation++; } } /// <summary> /// /// </summary> protected void EndLine() { bWritingLine = false; AddLine(); } /// <summary> /// /// </summary> protected void EndLineWithSemi() { GenerateSemi(); EndLine(); } /// <summary> /// /// </summary> protected void StartNewLine() { bWritingLine = true; AppendIndentation(); } /// <summary> /// /// </summary> protected void GenerateSemi() { AppendPacked(";"); } /// <summary> /// /// </summary> /// <param name="type"></param> /// <param name="count"></param> protected void AppendFormattingChars(EnumFormatingCharacter type, int count) { foreach (int i in Utility.EnumerableRange(0, count)) { switch (type) { case EnumFormatingCharacter.NewLine: AddLine(); break; #if DEBUG_PRINT_WHITESPACE case EnumFormatingCharacter.Space: AppendPacked(@"."); break; case EnumFormatingCharacter.Tab: AppendPacked(@"--->"); break; #else case EnumFormatingCharacter.Space: AppendPacked(@" "); break; case EnumFormatingCharacter.Tab: AppendPacked(@"\t"); break; #endif } } } /// <summary> /// /// </summary> protected void OpenCodeBlock() { AppendPacked("{"); bWritingCodeBlock = false; IncrementNestLevel(); AddLine(); bWritingCodeBlock = true; } /// <summary> /// /// </summary> protected void CloseCodeBlock() { DecrementNestLevel(); StartNewLine(); AppendPacked("}"); EndLine(); bWritingCodeBlock = (NestingLevel > 0); } /// <summary> /// /// </summary> /// <param name="comment"></param> protected void CloseCodeBlockWithComment(string comment) { DecrementNestLevel(); StartNewLine(); AppendSpaced("}"); AppendComment(comment); EndLine(); bWritingCodeBlock = (NestingLevel > 0); } /// <summary> /// /// </summary> /// <returns></returns> protected int IncrementNestLevel() { m_NestingLevel += 1; return NestingLevel; } /// <summary> /// /// </summary> /// <returns></returns> protected int DecrementNestLevel() { m_NestingLevel = NestingLevel > 0 ? NestingLevel - 1 : 0; return NestingLevel; } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="vtype"></param> protected void AddVariable(string name, VariableSignature signature) { GeneratedVariables.Add(name, signature); } /// <summary> /// /// </summary> /// <param name="v"></param> protected void AppendRaw(string v) { string[] lines = v.Split('\n'); foreach(string line in lines) { line.Trim('\t', ' '); StartNewLine(); AppendPacked(line); EndLine(); } } /// <summary> /// /// </summary> /// <param name="v"></param> protected void AppendComment(string v) { if (bWritingLine) { AppendPacked("// " + v); } else { StartNewLine(); AppendPacked("// " + v); EndLine(); } } protected void AppendBlockComment(string v) { string[] lines = v.Split('\n'); if (lines.Length > 1) { StartNewLine(); AppendPacked("/*"); EndLine(); foreach (string line in lines) { StartNewLine(); AppendPacked("* " + line); EndLine(); } StartNewLine(); AppendPacked("*/"); EndLine(); } else { StartNewLine(); AppendPacked("/* " + v + " */"); EndLine(); } } /// <summary> /// /// </summary> /// <param name="v"></param> protected void AppendWithNewLine(string v) { AppendPacked(v + Environment.NewLine); } /// <summary> /// /// </summary> /// <param name="v"></param> protected void AppendSpaced(string v) { #if DEBUG_PRINT_WHITESPACE AppendPacked(v + "."); #else AppendPacked(v + " "); #endif } /// <summary> /// /// </summary> /// <param name="v"></param> protected void AppendPacked(string v) { if((bWritingMethod | bWritingObject) & bWritingCodeBlock & !bWritingLine) { AppendIndentation(); Builder.Append(v); } else { Builder.Append(v); } } /// <summary> /// /// </summary> /// <param name="word"></param> protected void AppendKeyword(EnumKeywords word) { switch (word) { case EnumKeywords.Public: AppendSpaced("public"); break; case EnumKeywords.Private: AppendSpaced("private"); break; case EnumKeywords.Protected: AppendSpaced("protected"); break; case EnumKeywords.Internal: AppendSpaced("internal"); break; case EnumKeywords.Void: AppendSpaced("void"); break; case EnumKeywords.Unsafe: AppendSpaced("unsafe"); break; case EnumKeywords.Static: AppendSpaced("static"); break; case EnumKeywords.For: AppendPacked("for"); break; } } /* End of protected methods */ } public struct VariableSignature { public VariableSignature(string name, string source, Type type) { SuppliedName = name; SourceName = source; VariableType = type; } public string SuppliedName { get; } public string SourceName { get; } public Type VariableType { get; } } } <file_sep>using System; using System.Collections.Generic; using Duality; using Quantus.Model; namespace Quantus.Curves { public class VectorCurve : IParticleDataCurve<Vector3> { CurveInterpolationMode mode; List<Tuple<float, Vector3>> points; public CurveInterpolationMode InterpMode { get { return mode; } set { mode = value; } } public List<Tuple<float, Vector3>> Points { get { return points; } set { points = value; } } public Vector3 Interpolate(float val) { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Duality; using Quantus.Model; namespace Quantus { /// <summary> /// Defines a Duality core plugin. /// </summary> public class QuantusCorePlugin : CorePlugin { public string GeneratedCodeNamespace { get { return QuantusConstants.GeneratedCodeNamespace; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus.Model { public static class QuantusConstants { public static string GeneratedCodeNamespace = @"Quantus.Generated"; public static string GeneratedCodeAssembly = @"Quantus.Generated.dll"; public static string VerificationObject = @"public class QGAVerif { public static string Success = true;}"; public static string GeneratedClassComment = @"QUANTUS GENERATED OBJECT"; } } <file_sep>using System; using System.Reflection; using System.CodeDom; using System.CodeDom.Compiler; using Microsoft.CSharp; using Quantus.Interface; namespace Quantus.Compiler { public class EmitterCompiler { public void CompileEmitter(EmitterBuildInfo info, QuantusCodeGenerator source) { CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = false; parameters.OutputAssembly = info.TargetAssemblyName; string rawsource = ""; CompilerResults results = provider.CompileAssemblyFromSource(parameters, rawsource); } public void CompileArbitrary(string source, out Assembly output, out CompilerErrorCollection errors) { CodeDomProvider provider = new CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); parameters.ReferencedAssemblies.Add(@"System.dll"); parameters.ReferencedAssemblies.Add(@"GamePlugin.core.dll"); parameters.ReferencedAssemblies.Add(@"ParticlePluginInterface.dll"); parameters.GenerateExecutable = false; CompilerResults results = provider.CompileAssemblyFromSource(parameters, source); output = results.CompiledAssembly; errors = results.Errors; } } } <file_sep>using System; using Duality; using Quantus.Model; namespace Quantus { public partial class ParticleEmitter { private int bufferSize = 0; private const int bufferMinSize = 8; EnumParticleBufferResizeMode bufferMode = EnumParticleBufferResizeMode.ByTwo; private bool bufferModeLocked = false; private Particle[] particleBuffer; public EnumParticleBufferResizeMode BufferMode { get { return bufferMode; } set { bufferMode = bufferModeLocked ? bufferMode : value; } } private void LockBufferMode() { bufferModeLocked = true; } private void UnlockBufferMode() { bufferModeLocked = false; } private void ResizeBuffer(int size) { Array.Resize<Particle>(ref particleBuffer, size); LockBufferMode(); } private int ExpandBuffer() { int newBufferSize = bufferSize; switch (BufferMode) { case EnumParticleBufferResizeMode.Linear: newBufferSize = bufferSize + bufferMinSize; break; case EnumParticleBufferResizeMode.LinearAdaptive: newBufferSize = bufferSize + bufferMinSize; // TODO break; case EnumParticleBufferResizeMode.ByTwo: newBufferSize = bufferSize * 2; break; case EnumParticleBufferResizeMode.SqrtTwo: newBufferSize = (int)MathF.Round((float)bufferSize * MathF.Sqrt(2.0f), 0); break; } ResizeBuffer(newBufferSize); return newBufferSize; } private int ShrinkBuffer() { int newBufferSize = bufferSize / 2; switch (BufferMode) { case EnumParticleBufferResizeMode.Linear: newBufferSize = bufferSize - bufferMinSize; break; case EnumParticleBufferResizeMode.LinearAdaptive: newBufferSize = bufferSize - bufferMinSize; // TODO break; case EnumParticleBufferResizeMode.ByTwo: newBufferSize = bufferSize * 2; break; case EnumParticleBufferResizeMode.SqrtTwo: newBufferSize = (int)MathF.Round((float)bufferSize / MathF.Sqrt(2.0f), 0); break; } if (particleCount > newBufferSize) { return bufferSize; } else { ResizeBuffer(newBufferSize); } return newBufferSize; } private void InitBuffer() { particleBuffer = new Particle[0]; ResizeBuffer(bufferMinSize); UnlockBufferMode(); } } } <file_sep> namespace Quantus { public interface IQuantusCodeGenerator { string GenerateSource(IQuantusBuildInfo info); void Initialize(); } } <file_sep>using Duality.Drawing; using Quantus.Model; using Quantus.Modules; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus { public partial class ParticleEmitter { public void SpawnParticle() { } } } <file_sep> namespace Quantus.Interface { public interface IACCT_TestClass { string GetTestString(); } } <file_sep>using Duality; using Duality.Drawing; namespace Quantus.Model { public struct Particle { public bool alive; public Vector3 position; public Vector3 prevpos; public Vector3 velocity; public Vector3 acceleration; public float angle; public float angularVelocity; public float angularAcceleration; public float lifetime; public float maxlife; public byte sprite; public int size; public ColorRgba color; } } <file_sep>using System; using System.Collections.Generic; using Duality; using Duality.Components; using Quantus.Model; namespace Quantus { public partial class ParticleEmitter : Renderer, ICmpUpdatable, ICmpInitializable { private int particleCount; private int particleDeadCount; private int particleSpawnCount; private bool isEmitterDead; public bool IsEffectDead { get { return particleCount == particleDeadCount && particleSpawnCount == 0; } } public int ParticleCount { get { return particleCount; } } void SpawnParticles(int count) { particleSpawnCount += count; } void RespawnParticle(ref Particle particle) { particleDeadCount--; particleSpawnCount--; } void ICmpUpdatable.OnUpdate() { if (isEmitterDead) { // TODO } Vector3 basePosition = GameObj.Transform.Pos; float baseScale = GameObj.Transform.Scale; float baseAngle = GameObj.Transform.Angle; float frameDelta = Time.TimeMult; float frameSeconds = Time.MsPFMult * Time.TimeMult; isEmitterDead = true; for (int i = 0; i < particleCount; i++) { Particle particle = particleBuffer[i]; if(particle.alive) { isEmitterDead = false; if(particle.lifetime <= 0.0f) { particle.alive = false; continue; } particle.lifetime -= frameSeconds; particle.velocity += particle.acceleration * frameDelta; particle.position += particle.velocity * frameDelta; particle.angularVelocity += particle.angularAcceleration * frameDelta; particle.angle += particle.angularVelocity * frameDelta; particle.alive = (particle.lifetime > 0.0f); boundsMin.X = particle.position.X < boundsMin.X ? particle.position.X : boundsMin.X; boundsMin.Y = particle.position.Y < boundsMin.Y ? particle.position.Y : boundsMin.Y; boundsMax.X = particle.position.X > boundsMax.X ? particle.position.X : boundsMax.X; boundsMax.Y = particle.position.Y > boundsMax.Y ? particle.position.X : boundsMax.Y; } else { if (particleSpawnCount > 0) { RespawnParticle(ref particle); } } } // Spawn additional particles that couldn't be respawned if(particleSpawnCount > 0) { particleCount += particleSpawnCount; } } void ICmpInitializable.OnInit(InitContext context) { if(context == InitContext.AddToGameObject) { InitBuffer(); InitModules(); } } void ICmpInitializable.OnShutdown(ShutdownContext context) { } } } <file_sep>using System.Collections.Generic; using Quantus.Modules; using System; using Quantus.Model; namespace Quantus.Compiler { public class EmitterBuildInfo : IEmitterBuildInfo { private bool bPrepared = false; private string targetNamespaceName = null; private string targetAssemblyName = null; private IParticleSystem owningSystem = null; private List<IEmitterModule> targetModules = new List<IEmitterModule>(); private List<string> buildTokens = new List<string>(); /// <summary> /// [GET] Has the build info been prepared. Must be true to compile from this /// </summary> public bool IsPrepared { get { return bPrepared; } } public IParticleSystem Owner { get { return owningSystem; } set { owningSystem = value; } } public string TargetNamespaceName { get { return targetNamespaceName; } } public string TargetAssemblyName { get { return targetAssemblyName; } } public List<IEmitterModule> TargetModules { get { return targetModules; } } public uint RequiredBytes { get { uint count = 0; foreach (IEmitterModule item in TargetModules) { count += item.RequiredBytes; } return count; } } /// <summary> /// [GET] The list of generated build tokens /// </summary> public List<string> BuildTokens { get { return buildTokens; } } /// <summary> /// Checks for duplicates based on <c>IEmitterModule.ModuleName</c> and then adds a module to the build info /// </summary> /// <param name="module">The module to add</param> public void AddModule(IEmitterModule module) { bool bDuplicate = false; foreach (IEmitterModule item in targetModules) { if(item.ModuleName == module.ModuleName) { bDuplicate = true; } } if(bDuplicate) { RemoveModuleByName(module); } targetModules.Add(module); bPrepared = false; } /// <summary> /// Removes a module based on <c>IEmitterModule.ModuleName</c> /// </summary> /// <param name="module"></param> public void RemoveModuleByName(IEmitterModule module) { if (targetModules.Count > 0) { targetModules.RemoveAll((m) => String.Equals(m.ModuleName, module.ModuleName)); } } public void Prepare() { targetModules.Sort((m1, m2) => m1.SortPriority.CompareTo(m2.SortPriority)); foreach(IEmitterModule item in targetModules) { buildTokens.Add(MakeToken(item)); } targetNamespaceName = QuantusConstants.GeneratedCodeNamespace; targetAssemblyName = QuantusConstants.GeneratedCodeAssembly; bPrepared = true; } private string MakeToken(IEmitterModule module) { string token = String.Format(@"<Token name=""{0}"" bytes=""{1}"" spawn=""{2}"" update=""{3}"" />", module.ModuleName, module.RequiredBytes, module.IsSpawnModule, module.IsUpdateModule); return token; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus.Model { public enum EnumParticleBufferResizeMode { Linear, LinearAdaptive, ByTwo, SqrtTwo, } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus { public static class Utility { public static IEnumerable<int> EnumerableRange(int from, int to) { if(from == to) { yield break; } if(from < to) { while(from <= to - 1) { yield return from++; } } else { while(from >= to + 1) { yield return from--; } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus { public enum EnumVariableScope { Local, Class, Static, } } <file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using Quantus; using Quantus.Compiler; using Quantus.Modules; using System; namespace Tests.Compiler { [TestClass] public class EmitterBuildInfoTest { const string ModuleTestCategory = "Compiler"; const string LocalTestCategory = "EmitterBuildInfo"; [TestMethod] [TestCategory(ModuleTestCategory), TestCategory(LocalTestCategory)] public void ConstructorTest() { EmitterBuildInfo info = new EmitterBuildInfo(); Assert.AreNotEqual(info, null); } [TestMethod] [TestCategory(ModuleTestCategory), TestCategory(LocalTestCategory)] public void AddModuleTest() { IEmitterModule module = new InitialColorModule(); EmitterBuildInfo info = new EmitterBuildInfo(); Assert.AreEqual(info.TargetModules.Count, 0); info.AddModule(module); Assert.AreEqual(info.TargetModules.Count, 1); Assert.AreEqual(info.TargetModules[0], module); } [TestMethod] [TestCategory(ModuleTestCategory), TestCategory(LocalTestCategory)] public void RemoveModuleByNameTest() { IEmitterModule module = new InitialColorModule(); EmitterBuildInfo info = new EmitterBuildInfo(); info.AddModule(module); Assert.AreEqual(1, info.TargetModules.Count); Assert.AreEqual(module, info.TargetModules[0]); info.RemoveModuleByName(module); Assert.AreEqual(0, info.TargetModules.Count, String.Format(" TargetModules: [{0}]", info.TargetModules.ToString())); } [TestMethod] [TestCategory(ModuleTestCategory), TestCategory(LocalTestCategory)] public void MakeTokenTest() { IEmitterModule module = new InitialColorModule(); EmitterBuildInfo info = new EmitterBuildInfo(); string testToken = @"<Token name=""Initial Color"" bytes=""4"" spawn=""True"" update=""False"" />"; Assert.IsFalse(info.IsPrepared, "EmitterBuildInfo should not be prepared"); info.AddModule(module); Assert.IsFalse(info.IsPrepared, "EmitterBuildInfo should not be prepared"); info.Prepare(); Assert.IsTrue(info.IsPrepared, "EmitterBuildInfo should be prepared"); List<string> tokens = info.BuildTokens; Assert.AreEqual<string>(testToken, tokens[0], "Token equality failed"); } } } <file_sep>namespace Quantus { public interface IQuantusBuildInfo { } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus.Model { public enum EnumParticleEventChannel { Channel_01 = 1 << 0, Channel_02 = 1 << 1, Channel_03 = 1 << 2, Channel_04 = 1 << 3, Channel_05 = 1 << 4, Channel_06 = 1 << 5, Channel_07 = 1 << 6, Channel_08 = 1 << 7, Channel_09 = 1 << 8, Channel_10 = 1 << 9 } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus { public static class QuantusRandom { /* static uint rng_x = 179192401; static uint rng_y = 362436069; static uint rng_z = 384481998; static uint rng_w = 223982932; public static uint Xorshift() { uint x = rng_x, y = rng_y, z = rng_z, w = rng_w; uint t = x ^ (x << 11); x = y; y = z; z = w; w = w ^ (w >> 19) ^ (t ^ (t >> 8)); return w; } */ } } <file_sep> namespace Quantus.Model { public enum CurveInterpolationMode { Linear, } }<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using Quantus.Compiler; using Quantus.Modules; using System; namespace Tests.Compiler { [TestClass] public class EmitterCompilerSourceTest { const string ModuleTestCategory = "Compiler"; const string LocalTestCategory = "EmitterCompilerSource"; [TestMethod] [TestCategory(ModuleTestCategory), TestCategory(LocalTestCategory)] public void ConstructorTest() { QuantusCodeGenerator source = new EmitterCodeGenerator(); Assert.AreNotEqual(source, null); } [TestMethod] [TestCategory(ModuleTestCategory), TestCategory(LocalTestCategory)] public void GenerateSourceTest() { QuantusCodeGenerator source = new EmitterCodeGenerator(); EmitterBuildInfo info = new EmitterBuildInfo(); info.Prepare(); string generated = source.GenerateSource(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CompilerTests.Attributes { [AttributeUsage(AttributeTargets.Class)] class QTestClassAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] class QTestMethodAttribute : Attribute { } } <file_sep>using Quantus.Model; using System; using System.Linq; using System.Text; namespace Quantus.Compiler { public class EmitterCodeGenerator : QuantusCodeGenerator { private IEmitterBuildInfo m_BuildInfo; public override string GenerateSource(IQuantusBuildInfo info) { m_BuildInfo = info as IEmitterBuildInfo; if(info != null) { if (!IsInitialized) { Initialize(); } StringBuilder builder = new StringBuilder(); //GenerateParticleObject(m_BuildInfo); GenerateEmitterObject(m_BuildInfo); } else { AppendPacked("Cannot build emitter. Invalid build info"); } return Builder.ToString(); } private void GenerateEmitterObject(IEmitterBuildInfo info) { OpenClass(info, "Emitter", typeof(IEmitterModule)); GenerateEmitterBody(info); CloseClass(info); } private void GenerateEmitterBody(IEmitterBuildInfo info) { AppendComment("Generated class body"); GenerateConstant("PAYLOAD_BYTES", typeof(uint), info.RequiredBytes); uint LastOffset = 0; foreach(int i in Utility.EnumerableRange(0, info.TargetModules.Count)) { IEmitterModule item = info.TargetModules[i]; string vname = (ResolveTypeOutputName(item.GetType()).ToUpper().Split('.').Last() + "_OFFSET"); GenerateConstant(vname, typeof(uint), LastOffset); LastOffset += item.RequiredBytes; } AppendFormattingChars(EnumFormatingCharacter.NewLine, 1); OpenMethod(info, "SpawnParticles", EnumAccessModifier.Public, null, typeof(int)); AppendComment("Generated method body"); OpenForLoop(0, "C_PAYLOAD_BYTES"); OpenForLoop(0, 1337); AppendBlockComment("Nested forloops???"); OpenForLoop(0, 666); AppendComment("It's for loops all the way down..."); CloseForLoop(); CloseForLoop(); CloseForLoop(); CloseMethod(); } private void GenerateEmitterBodyComment() { AppendComment("Generated class body"); } private void GenerateParticleObject(IEmitterBuildInfo info) { OpenClass(info, "Particle", EnumObjectType.Struct, EnumAccessModifier.Public, true); GenerateParticleBody(info); CloseClass(info); } private void GenerateParticleBody(IEmitterBuildInfo info) { GenerateParticleBodyComment(); AppendIndentation(); Builder.Append(String.Format("fixed byte payload[{0}];", info.RequiredBytes)); } private void GenerateParticleBodyComment() { AppendIndentation(); Builder.Append("// Generated particle body"); Builder.Append(Environment.NewLine); Builder.Append(Environment.NewLine); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus.Model { public enum EnumObjectType { Class, Struct, Default = Class, } } <file_sep>namespace Quantus { public enum EnumFormatingCharacter { NewLine, Tab, Space, } }<file_sep>using Quantus.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus.Curves { public struct ScalarCurve : IParticleDataCurve<float> { CurveInterpolationMode mode; List<Tuple<float, float>> points; public CurveInterpolationMode InterpMode { get { return mode; } set { mode = value; } } public List<Tuple<float, float>> Points { get { return points; } set { points = value; } } public float Interpolate(float val) { float output = 0.0f; switch (mode) { case CurveInterpolationMode.Linear: break; } return output; } } } <file_sep>using Quantus.Model; namespace Quantus { public interface IEmitterModule { /// <summary> /// [GET / SET] Enables or disables the module compilation /// </summary> bool Enabled { get; set; } /// <summary> /// [GET] Determines whether the module is responsible for initializing some particle data /// </summary> bool IsSpawnModule { get; } /// <summary> /// [GET] Determines whether the module is updated every frame /// </summary> bool IsUpdateModule { get; } /// <summary> /// [GET] The modules string name representation (for use in editor) /// </summary> string ModuleName { get; } /// <summary> /// [GET] The number of bytes this module adds to the particle payload /// <returns>uint</returns> /// </summary> uint RequiredBytes { get; } /// <summary> /// [GET] The priority of this module in updates and initialization /// </summary> int SortPriority { get; } string GenerateCode(ref IQuantusCodeGenerator generator); } } <file_sep>using System; using System.Collections.Generic; using Quantus.Model; namespace Quantus { public interface IParticleDataCurve<T> { CurveInterpolationMode InterpMode { get; set; } List<Tuple<float, T>> Points { get; set; } T Interpolate(float val); } } <file_sep>using Quantus.Compiler; using Quantus.Modules; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CompilerTests.Tests { public static class EmitterCompilerSourceTest { public static void Test() { QuantusCodeGenerator generator = new EmitterCodeGenerator(); EmitterBuildInfo info = new EmitterBuildInfo(); info.AddModule(new InitialColorModule()); info.AddModule(new InitialPositionModule()); info.AddModule(new InitialVelocityModule()); info.Prepare(); Console.Write(generator.GenerateSource(info)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus.Model { public enum EnumAccessModifier { Public, Private, Protected, Internal, Default = Public } } <file_sep>using Duality; using Duality.Drawing; using Duality.Resources; namespace Quantus { public partial class ParticleEmitter { private RawList<VertexC1P3T2> vertexBuffer; private ContentRef<Material> particleMaterial; private Vector2 boundsMin; private Vector2 boundsMax; public override float BoundRadius { get { float width = boundsMax.X - boundsMin.X; float height = boundsMax.Y - boundsMin.Y; return MathF.Sqrt(MathF.Pow(width, 2) + MathF.Pow(height, 2)) / 2.0f; } } public override void Draw(IDrawDevice device) { vertexBuffer = new RawList<VertexC1P3T2>(); particleMaterial = null; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus { public enum EnumKeywords { Public, Private, Protected, Internal, Void, Unsafe, Const, Static, For, While, } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus { public enum EnumLoopType { ForLoop, ForeachLoop, WhileLoop, } public enum EnumForLoopPattern { LiteralLiteral, LiteralVariable, VariableLiteral, VariableVariable, } } <file_sep>using System; using System.Reflection; using System.CodeDom.Compiler; using Quantus.Compiler; using Quantus.Interface; using CompilerTests.Tests; namespace CompilerTests { class Program { static void Main(string[] args) { //ACCT_Test(); EmitterCompilerSourceTest.Test(); Console.ReadKey(); } public static void ACCT_Test() { EmitterCompiler compiler = new EmitterCompiler(); string source = @" public class ACCT_TestClass : ParticlePlugin.IACCT_TestClass { public string GetTestString() { return ""TEST SUCCESS""; } } "; Assembly asm; CompilerErrorCollection err; compiler.CompileArbitrary(source, out asm, out err); foreach (CompilerError item in err) { Console.WriteLine("ERR: {0}: {1}", item.Line, item.ErrorText); } IACCT_TestClass obj = asm.CreateInstance("ACCT_TestClass") as IACCT_TestClass; Console.WriteLine("TYPE/ASSEMBLY: \"{0}\" : \"{1}\"", obj.GetType().AssemblyQualifiedName, obj.GetTestString()); } } } <file_sep>using Duality; using Duality.Components; using Duality.Drawing; using Quantus.Model; namespace Quantus { public interface IEmitter { /// <summary> /// Spawns a number of particles /// </summary> /// <param name="count">The number of particles to spawn</param> void SpawnParticles(int count); /// <summary> /// Respawns a dead particle /// </summary> /// <param name="old"></param> void RespawnParticle(ref Particle old); /// <summary> /// Initializes the emitter /// </summary> void Initialize(); /// <summary> /// Shuts down the emitter /// </summary> void Shutdown(); /// <summary> /// Updates all of the particles this emitter is responsible for /// </summary> void Update(); /// <summary> /// Draws particles /// </summary> /// <param name="device"></param> void Draw(IDrawDevice device); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus { public interface IParticleSystem { } } <file_sep>using CompilerTests.Attributes; namespace CompilerTests.Tests { [QTestClass] class EmitterBuildInfoTest { [QTestMethod] void MakeTokenTest() { } } } <file_sep>using System.Collections.Generic; namespace Quantus { public interface IEmitterBuildInfo : IQuantusBuildInfo { List<string> BuildTokens { get; } bool IsPrepared { get; } IParticleSystem Owner { get; set; } uint RequiredBytes { get; } string TargetAssemblyName { get; } List<IEmitterModule> TargetModules { get; } string TargetNamespaceName { get; } void AddModule(IEmitterModule module); void Prepare(); void RemoveModuleByName(IEmitterModule module); } }<file_sep>using Quantus.Model; using Quantus.Modules; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantus { public partial class ParticleEmitter { private List<IEmitterModule> moduleList; public List<IEmitterModule> Modules { get { return moduleList; } set { moduleList = value; } } public void AddModule(IEmitterModule module) { } public void RemoveModule(IEmitterModule module) { } public bool HasModule(EmitterModuleFlag mask) { return false; } public void UpdateModules() { } public void InitModules() { } } }
b7fadaf6b259492d6e29b090de343b832e142fa1
[ "C#" ]
41
C#
JerTH/Quantus
6253eb08ef03f4afea15b75a20b5240b692e7d56
b9c3ff8b6ac18f1d3d195d5285ce3daecfc36e8a
refs/heads/main
<repo_name>MikChanna/employeedirectory<file_sep>/README.md # Employee Directory App **## Description** This app will filter employees (in this app, random 50 users) based on the search parameters given by the user. They may search by first name, last name, email address, or country. **## Table of Contents** - [Employee Directory App](#employee-directory-app) - [Installation Instructions](#installation-instructions) - [Usage Information](#usage-information) - [Questions](#questions) ## Installation Instructions This app was built as a React app. Create a react app by going to your terminal and typing `npx create react-app [app name]`. Once the app has been created, you may clone this repo, and copy over the src folder from the repo to to your new react app. Run app with `npm start`. ## Usage Information This app uses https://randomuser.me/ API to generate 51 random users (employees). In the search bar type in a name, email, or country. Upon hitting the submit button your list of employees will be filtered. Refresh the page start with all your employees again. <img width="1339" alt="Screen Shot 2020-10-12 at 2 50 14 PM" src="https://user-images.githubusercontent.com/61893686/95781229-5cb8a100-0c9b-11eb-9db9-5a438b1e50a9.png"> # Questions For any questions about the project, please feel free to reach out to me on github or via email. Thank you for viewing this project! https://github.com/MikChanna <EMAIL> <file_sep>/build/precache-manifest.6c1715a5de2f378d4d19a5769248310a.js self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "e83570f998a85e27d2ef23a5de21acf2", "url": "/employeedirectory/index.html" }, { "revision": "c281b5e19cbebc6bb655", "url": "/employeedirectory/static/css/2.d9ad5f5c.chunk.css" }, { "revision": "b2dd7cb9d266686aba7f", "url": "/employeedirectory/static/css/main.5625d78b.chunk.css" }, { "revision": "c281b5e19cbebc6bb655", "url": "/employeedirectory/static/js/2.ce0ca2a3.chunk.js" }, { "revision": "849657740f66d00720db130cc1e94c97", "url": "/employeedirectory/static/js/2.ce0ca2a3.chunk.js.LICENSE.txt" }, { "revision": "b2dd7cb9d266686aba7f", "url": "/employeedirectory/static/js/main.7ec00809.chunk.js" }, { "revision": "6502cc3240a1235f4783", "url": "/employeedirectory/static/js/runtime-main.8876b22a.js" } ]);<file_sep>/src/components/Footer/index.js import React from "react"; import "./style.css"; function Footer() { return <footer className="footer mt-auto py-3"> <div className ="container"> <span className = "text-muted">Employee Directory App 2020 CLMC</span> </div> </footer> ; } export default Footer; <file_sep>/src/components/Header/index.js import React from "react"; function Header () { return <div className= "row"> <div className = "col"> </div> <div className = "col"> <h2> First Name </h2> </div> <div className = "col"> <h2> Last Name </h2> </div> <div className = "col"> <h2> Email </h2> </div> <div className = "col"> <h2> Birthday </h2> </div> <div className = "col"> <h2> Country</h2> </div> </div> } export default Header;<file_sep>/src/components/Search/index.js import React from "react"; // import Table from "../Table"; // import API from "../../utils/API"; import "./style.css"; function Search (props) { return <div className="container"> <div className = "row"> <input type="text" className="searchbar col-6" id="searchInput" onChange = {props.handleInputChange}></input> <button className="col-4" id="submitSearch" onClick = {props.handleSearchSubmit}> Submit </button> </div> </div> } export default Search; <file_sep>/src/components/UserRow/index.js import React from "react"; function Userrow(props) { return <tr > <td className = "col"> <img alt = {props.firstName + props.lastName} src = {props.picture} /> </td> <td className = "col"> <p>{props.firstName } </p> </td> <td className = "col"> <p>{props.lastName}</p> </td> <td className = "col"> <p>{props.email}</p> </td> <td className = "col"> <p>{props.birthday}</p> </td> <td className = "col"> <p>{props.country}</p> </td> </tr> } export default Userrow;<file_sep>/src/components/Table/index.js import React from 'react'; import Userrow from "../Userrow"; import "./style.css"; import moment from "moment"; function Table (props) { return <div className = "container"> <table className="table row table-striped"> <thead> <tr> <th className="col ">Photo</th> <th className="col">First Name</th> <th className="col">Last Name</th> <th className="col">Email</th> <th className="col">Birthday</th> <th className="col">Country</th> </tr> </thead> <tbody> {props.user.map(user => ( <Userrow key = {user.registered.date} picture = {user.picture.large} firstName = {user.name.first} lastName = {user.name.last} country = {user.location.country} email = {user.email} birthday = {moment(user.dob.date).format('MMMM Do')} /> ))} </tbody> </table> </div> } export default Table;
d6c1201d406460b0bbefb8666fc26971308f5181
[ "Markdown", "JavaScript" ]
7
Markdown
MikChanna/employeedirectory
9d9539fc77cddce2d2830c0e3b8b7fae9e9a18b6
14e1066d88308e9b69d83236bf7be05f9419fa82
refs/heads/master
<repo_name>cachefish/Thread_mutex<file_sep>/oo_producer_consumer/TaskQueue.cpp #include"TaskQueue.h" using namespace wd; TaskQueue::TaskQueue(size_t queSize) :_queSize(queSize) ,_mutex() ,_notFull(_mutex) ,_notEmpty(_mutex) { } bool TaskQueue::empty()const { return _que.size()==0; } bool TaskQueue::full() const { return _que.size()==_queSize; } void TaskQueue::push(const ElemType&Elem) { MutexLockGuand autoLock(_mutex); while(full()){ //使用while是为了防止条件变量被异常唤醒 _notFull.wait(); } _que.push(Elem); _notEmpty.notify(); } ElemType TaskQueue::pop() { MutexLockGuand autoLock(_mutex); while(empty()){ _notEmpty.wait(); } ElemType temp = _que.front(); _que.pop(); _notFull.notify(); return temp; }<file_sep>/oo_producer_consumer/TestThread.cpp #include "TaskQueue.h" #include "Producer.h" #include "Consumer.h" #include <unistd.h> #include <stdlib.h> #include <iostream> #include <memory> using std::cout; using std::endl; using std::unique_ptr; int main(void) { cout<<"mainThread"<<pthread_self()<<endl; wd::TaskQueue queue(4); unique_ptr<wd::Thread> pProduecer(new wd::Producer(queue)); unique_ptr<wd::Thread> pConsumer(new wd::Consumer(queue)); pProduecer->start(); pConsumer->start(); pProduecer->join(); pConsumer->join(); return 0; }<file_sep>/oo_thread/Noncopyable.h #ifndef __NONCOPYABLE_H__ #define __NONCOPYABLE_H__ class Noncopyable { protected: Noncopyable(){} ~Noncopyable(){} Noncopyable(const Noncopyable&) = delete; Noncopyable&operator=(const Noncopyable&)=delete; }; #endif<file_sep>/processpool/processpool.h #ifndef PROCESSPOOL_H #define PROCESSPOOL_H #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<assert.h> #include<stdio.h> #include<unistd.h> #include<errno.h> #include<string.h> #include<fcntl.h> #include<stdlib.h> #include<sys/epoll.h> #include<signal.h> #include<sys/wait.h> #include<sys/stat.h> //描述一个子进程的类,m_pid是,目标子进程的PID,m_pipefd是父进程和子进程通信用的管道 class process { public: process():m_pid(-1) {} private: pid_t m_pid; int m_pipefd[2]; }; //进程池类,模板参数是用来处理逻辑任务的类 template<typename T> class processpool { private: processpool(int listenfd,int process_number = 8); public: static processpool<T>*create(int listenfd, int process_number = 8) { if(!m_instance){ m_instance = new processpool<T> (listenfd,process_number); } return m_instance; } ~processpool() { delete []m_sub_process; } void run(); private: void setup_sig_pipe(); void run_parent(); void run_child(); private: //允许的最大进程数 static const int MAX_PROCESS_NUMBER = 16; //每个子进程最多处理的客户数量 static const int USER_PER_PROCESS = 65536; //epoll最多处理的事件数 static const int MAX_EVENT_NUMBER = 10000; //进程池中的进程总数 int m_process_number; //子进程在池中的序号 int m_idx; //每个进程都有一个epoll内核事件表,用m_epollfd标示 int m_epollfd; //监听socket int m_listenfd; //子进程通过m_stop来决定是否停止运行 int m_stop; //保存所有子进程的描述信息 process*m_sub_process; //进程池静态实例 static processpool<T>* m_instance; }; template<typename T > processpool<T> * processpool<T>::m_instance = NULL; static int sig_pipefd[2]; //设置非阻塞 static int setnonblocking(int fd) { int old_option = fcntl(fd,F_GETFL); int new_option = old_option | O_NONBLOCK; fcntl(fd,F_SETFL,new_option); } static void addfd(int epollfd,int fd) { epoll_event event; event.data.fd = fd; event.events = EPOLLIN | EPOLLET; epoll_ctl(epollfd,EPOLL_CTL_ADD,fd,&event); setnonblocking(fd); } //从epollfd标识的epoll内核事件中删除fd上的所有注册事件 static void removefd(int epollfd,int fd) { epoll_ctl(epollfd,EPOLL_CTL_DEL,fd,0); close(fd); } static void addsig(int sig,void(handler)(int),bool restart =true) { struct sigaction sa; memset(&sa,'\0',sizeof(sa)); sa.sa_handler = handler; if(restart){ sa.sa_flags |= SA_RESTART; } sigfillset(&sa.sa_mask); //在信号集中设置所有信号 assert(sigaction(sig,&sa,NULL)!=-1); //设置信号处理 } //进程池构造函数,listenfd--监听socket template<typename T> processpool<T>::processpool(int listenfd,int process_number) :m_listenfd(listenfd) ,m_process_number(process_number) ,m_idx(-1) ,m_stop(false) { assert((process_number>0)&&(process_number<=MAX_PROCESS_NUMBER)); m_sub_process = new process[process_number]; assert(m_sub_process); //创建子进程,并建立与父进程之间的管道 for(int i =0;i<process_number;++i){ int ret = socketpair(PF_UNIX,SOCK_STREAM,0,m_sub_process[i].m_pipefd); assert(ret==0); m_sub_process[i].m_pid = fork(); assert(m_sub_process[i].m_pid>=0); if(m_sub_process[i].m_pid>0){ close(m_sub_process[i].m_pipefd[1]); continue; }else{ close(m_sub_process[i].m_pipefd[0]); m_idx = i; break; } } } //统一事件源 template<typename T> void processpool<T>::setup_sig_pipe() { m_epollfd = epoll_create(5); assert(m_epollfd != -1); int ret = socketpair(PF_UNIX,SOCK_STREAM,0,sig_pipefd); assert(ret != -1); setnonblocking(sig_pipefd[1]); addfd(m_epollfd,sig_pipefd[0]); //设置信号处理函数 addsig(SIGCHLD,sig_handler); addsig(SIGTERM, sig_handler); addsig(SIGINT, sig_handler); addsig(SIGPIPE, SIG_IGN); } //父进程中m_idx 为-1,子进程中m_idx值大于等于0 template<typename T> void processpool<T>::run() { if(m_idx==-1){ run_child(); return; } run_parent(); } template<typename T> void processpool<T>::run_child() { setup_sig_pipe(); //每个子进程都通过其在进程池中的序号值m_idx找到与父进程通信的管道 int pipefd = m_sub_process[m_idx].m_pipefd[1]; addfd(m_epollfd,pipefd); epoll_event events[MAX_EVENT_NUMBER]; T *users = new T[USER_PER_PROCESS]; assert(users); int number = 0; int ret =-1; while (!m_stop) { number = epoll_wait(m_epollfd,events,MAX_EVENT_NUMBER,-1); if((number<0)&&(errno!=EINTR)) { printf("epoll failure"); break; } for(int i =0;i<number;i++) { int sockfd = events[i].data.fd; if((sockfd==pipefd)&&(events[i].events&EPOLLIN)) { int client =0; //从管道中读取数据 ret = recv(sockfd,(char*)&client,sizeof(client),0); if(((ret<0)&&(errno!=EAGAIN))||ret==0) { continue; }else{ struct sockaddr_in client_address; socklen_t client_addelength = sizeof(client_address); int connfd = accept(m_listenfd,(struct sockaddr*)&client_address,&client_addelength); if(connfd<0){ printf("errno is : %d\n",errno); continue; } addfd(m_epollfd,connfd); //模板类T实现init方法,以初始化一个客户连接,直接使用connfd来索引逻辑处理对象 users[connfd].init(m_epollfd,connfd,client_address); } }else if((sockfd==sig_pipefd[0])&&(events[i].events&EPOLLIN)) { int sig; char signals[1024]; ret = recv(sig_pipefd[0],signals,sizeof(signals),0); if(ret<=0){ continue; }else{ for(int i =0;i<ret;i++){ switch (signals[i]) { case SIGCHLD: { pid_t pid; int stat; while((pid = waitpid(-1,&stat,WNOHANG))>0) { continue; } break; } case SIGTERM: case SIGINT: { m_stop = true; break; } default: { break; } } } } }else if(events[i].events&EPOLLIN) { users[sockfd].process(); }else{ continue; } } } delete []users; users = NULL; close(pipefd); close(m_epollfd); } template<typename T> void processpool<T>::run_parent() { setup_sig_pipe(); //父进程监听m_listenfd addfd(m_epollfd, m_listenfd); epoll_event events[MAX_EVENT_NUMBER]; int sub_process_counter = 0; int new_conn = 1; int number = 0; int ret = -1; while(!m_stop) { number = epoll_wait(m_epollfd,events,MAX_EVENT_NUMBER,-1); if((number<0)&&(errno!=EINTR)) { printf("epoll failure"); break; } for(int i =0;i<number;i++) { int sockfd = events[i].data.fd; if(sockfd == m_listenfd) { //如果有新连接到来,就采用round robin方式将其分配给一个子进程处理 int i = sub_process_counter; do{ if(m_sub_process[i].m_pid!=-1){ break; } i = (i+1)%m_process_number; }while(i != sub_process_counter); if(m_sub_process[i].m_pid==-1){ m_stop = true; break; } sub_process_counter = (i+1)%m_process_number; send(m_sub_process[i].m_pipefd[0],(char*)&new_conn,sizeof(new_conn),0); printf("send request to child %d\n,i"); } //处理父进程接收到的信号 else if((sockfd==sig_pipefd[0])&&(events[i].events&EPOLLIN)) { int sig; char signals[1024]; ret = recv(sig_pipefd[0],signals,sizeof(signals),0); if(ret<=0){ continue; }else{ for(int i =0;i<ret;++i){ switch (signals[i]) { case SIGCHLD: { pid_t pid; int stat; while((pid=waitpid(-1,&stat,WNOHANG))>0) { for(int i =0;i<m_process_number;++i) { //如果进程池中第i个子进程退出了,则主进程关闭响应的通道管道,并设置相应的m_pid为-1,标记为退出 if(m_sub_process[i].m_pid==pid){ printf("child %d join\n",i); close(m_sub_process[i].m_pid=-1); } } } //如果所有子进程都已经退出了,则父进程也退出 m_stop = true; for(int i =0;i<m_process_number;++i) { if(m_sub_process[i].m_pid!=-1) { m_stop = false; } } break; } case SIGTERM: case SIGINT: { //如果父进程接收到了终止信号,那就杀死所有子进程,并等待他们结束 printf("kill all the_child now\n"); for(int i =0;i<m_process_number;++i){ int pid = m_sub_process[i].m_pid; if(pid != -1) { kill(pid,SIGTERM); } } break; } default: { break; } } } } } else{ continue; } } } close(m_epollfd); } #endif<file_sep>/oo_producer_consumer/Producer.cpp #include"Producer.h" #include"TaskQueue.h" #include<iostream> #include<stdlib.h> #include<unistd.h> using std::cout; using std::endl; using namespace wd; Producer::Producer(TaskQueue&taskQue):_taskQue(taskQue) { } void Producer::run() { //生产数据 ::srand(::clock()); int cnt = 10; while(cnt--){ int number = ::rand()%100; ::sleep(1); _taskQue.push(number); cout<<"producer thread"<<pthread_self()<<"producer number:"<<number<<endl; } }<file_sep>/bo_thread/TestThread.cpp #include "Thread.h" #include <unistd.h> #include <stdlib.h> #include <iostream> #include <memory> using std::cout; using std::endl; using std::unique_ptr; void run() { int cnt = 10; ::srand(::clock()); while(cnt--) { int number = ::rand() % 100; ::sleep(1); cout << ">> subthread " << pthread_self() << ": number = " << number << endl; } } struct Task { void process() { run(); } }; int main(void) { cout << "mainThread: " << pthread_self() << endl; unique_ptr<wd::Thread> p(new wd::Thread(std::bind(&Task::process, Task()))); p->start(); cout << "mainThread: subthread " << p->getThreadId() << endl; p->join(); return 0; } <file_sep>/bo_producer_consumer/Thread.h #ifndef __THREAD_H__ #define __THREAD_H__ #include"Noncopyable.h" #include<pthread.h> #include<functional> namespace wd { class Thread:Noncopyable { public: using ThreadCallback = std::function<void()>; Thread(ThreadCallback&&cb); ~Thread(); void start(); void join(); pthread_t getThreadId()const{return _pthid;} private: static void *threadFunc(void *arg); private: pthread_t _pthid; ThreadCallback _cb; bool _isRunning; }; } #endif<file_sep>/oo_ThreadPool/WorkerThread.h #ifndef __WORKERTHREAD_H__ #define __WORKERTHREAD_H__ #include "Thread.h" #include "Threadpool.h" namespace wd { class WorkerThread : public Thread { public: WorkerThread(Threadpool & threadpool) : _threadpool(threadpool) {} private: void run() { _threadpool.threadFunc(); } private: Threadpool & _threadpool; }; }//end of namespace wd #endif <file_sep>/bo_producer_consumer/TestThread.cpp #include "Thread.h" #include "TaskQueue.h" #include <unistd.h> #include <stdlib.h> #include <iostream> #include <memory> using std::cout; using std::endl; using std::unique_ptr; void run() { int cnt = 10; ::srand(::clock()); while(cnt--) { int number = ::rand() % 100; ::sleep(1); cout << ">> subthread " << pthread_self() << ": number = " << number << endl; } } struct Producer { void produce(wd::TaskQueue & taskQue) { int cnt = 20; ::srand(::clock()); while(cnt--) { int number = ::rand() % 100; taskQue.push(number); ::sleep(1); cout << ">> producerthread " << pthread_self() << ": produce number = " << number << endl; } } }; struct Consumer { void consume(wd::TaskQueue & taskQue) { int cnt = 20; while(cnt--) { int number = taskQue.pop(); ::sleep(2); cout << ">>> consumeThread " << pthread_self() << ": consume a number " << number << endl; } } }; int main(void) { wd::TaskQueue taskqueue(10); cout << "mainThread: " << pthread_self() << endl; unique_ptr<wd::Thread> pProducer( new wd::Thread( //bind绑定参数时,采用的是值传递--> 复制 std::bind(&Producer::produce, Producer(), std::ref(taskqueue)) )); unique_ptr<wd::Thread> pConsumer( new wd::Thread( std::bind(&Consumer::consume, Consumer(), std::ref(taskqueue)) ) ); pProducer->start(); pConsumer->start(); pProducer->join(); pConsumer->join(); return 0; } <file_sep>/oo_thread/TestThread.cpp #include"Thread.h" #include<iostream> #include<ctime> #include<stdlib.h> #include<memory> #include<unistd.h> using std::cout; using std::endl; using std::unique_ptr; class MyThread:public wd::Thread { private: void run() { int cnt =10; while(cnt--) { int number = ::rand()%100; ::sleep(1); cout<<">>number="<<number<<endl; } } }; int main() { unique_ptr<wd::Thread> p(new MyThread()); cout<<"mainThread:subthread"<<p->getThreadId()<<endl; p->start(); p->join(); return 0; }<file_sep>/oo_producer_consumer/Consumer.cpp #include"Consumer.h" #include"TaskQueue.h" #include<unistd.h> #include<iostream> using namespace wd; using std::cout; using std::endl; Consumer::Consumer(TaskQueue&taskQue):_taskQue(taskQue) {} void Consumer::run() { int cnt = 10; while(cnt--) { int number = _taskQue.pop(); ::sleep(2); cout<<"consumer thread"<<pthread_self()<<"consumer number "<<number<<endl;; } }<file_sep>/oo_producer_consumer/MutexLock.h #ifndef __MUTEXLOCK_H__ #define __MUTEXLOCK_H__ #include<pthread.h> namespace wd { class MutexLock { public: MutexLock(); ~MutexLock(); void lock(); void unlock(); pthread_mutex_t*getMutexLockPtr(){return &_mutex;} private: pthread_mutex_t _mutex; bool _islocking; }; class MutexLockGuand { public: MutexLockGuand(MutexLock&mutex):_mutex(mutex) { _mutex.lock(); } ~MutexLockGuand() { _mutex.unlock(); } private: MutexLock&_mutex; }; } // namespace #endif<file_sep>/oo_ThreadPool/Threadpool.h #ifndef __THREADPOOL_H__ #define __THREADPOOL_H__ #include"TaskQueue.h" #include"Thread.h" #include<memory> #include<vector> using std::vector; using std::unique_ptr; namespace wd { class Thread; class WorkThread; class Threadpool { friend WorkThread; public: Threadpool(size_t,size_t); ~Threadpool(); void start(); void stop(); void addTask(Task*); public: Task*getTask(); void threadFunc(); private: size_t _threadNumber; size_t _queSize; vector<unique_ptr<Thread>> _threads; TaskQueue _taskque; bool _isExit; }; } #endif<file_sep>/README.md # 面向对象方式下的生产者消费者模式 # 基于对象方式下的生产者消费者模式<file_sep>/bo_ThreadPool/Condition.h #ifndef _CONDITION_H__ #define _CONDITION_H__ #include"Noncopyable.h" #include"MutexLock.h" #include<pthread.h> namespace wd { class Condition:Noncopyable { public: Condition(MutexLock&mutex); ~Condition(); void wait(); void notify(); void notifyall(); private: pthread_cond_t _cond; MutexLock&_mutex; }; } // namespace wd #endif<file_sep>/bo_ThreadPool/TaskQueue.cpp #include "TaskQueue.h" using namespace wd; TaskQueue::TaskQueue(size_t queSize) : _queSize(queSize) , _mutex() , _notFull(_mutex) , _notEmpty(_mutex) , _flag(true) {} bool TaskQueue::empty() const { return _que.size() == 0; } bool TaskQueue::full() const { return _que.size() == _queSize; } // push方法运行在生产者线程 void TaskQueue::push(const ElemType & value) { MutexLockGuard autolock(_mutex); while(full()) { //使用while是为了防止条件变量被异常唤醒 _notFull.wait(); } _que.push(value); _notEmpty.notify(); } //运行在消费者线程 ElemType TaskQueue::pop() { MutexLockGuard autolock(_mutex); while(_flag && empty()) { _notEmpty.wait(); } if(_flag) { ElemType tmp = _que.front(); _que.pop(); _notFull.notify(); return tmp; } else { return NULL; } } <file_sep>/oo_ThreadPool/Thread.h #ifndef __THREAD_H__ #define __THREAD_H__ #include <pthread.h> namespace wd { class Thread { public: Thread() : _pthid(0) , _isRunning(false) {} virtual ~Thread(); void start(); void join(); pthread_t getThreadId() const { return _pthid; } private: virtual void run() =0; static void * threadFunc(void * arg); private: pthread_t _pthid; bool _isRunning; }; }//end of namespace wd #endif <file_sep>/oo_producer_consumer/Producer.h #include"Thread.h" #include<iostream> using std::cout; using std::endl; namespace wd{ class TaskQueue; class Producer:public Thread { public: Producer(TaskQueue&taskQue); private: void run(); private: TaskQueue&_taskQue; }; }<file_sep>/oo_thread/Thread.h #pragma once #include<pthread.h> namespace wd { class Thread { public: Thread():_pthid(0),_isRunning(false) {} virtual ~Thread(); void start(); void join(); pthread_t getThreadId(){return _pthid;} private: virtual void run()=0; static void *threadFunc(void*arg); private: pthread_t _pthid; bool _isRunning; }; } <file_sep>/bo_ThreadPool/Threadpool.h #ifndef __THREADPOOL_H__ #define __THREADPOOL_H__ #include"TaskQueue.h" #include<vector> #include<memory> #include<functional> using std::vector; using std::unique_ptr; namespace wd { class Thread; class Threadpool { public: typedef std::function<void()> Task; Threadpool(size_t, size_t); ~Threadpool(); void start(); void stop(); void addTask(Task && task); private: Task getTask(); void threadFunc(); private: size_t _threadNumber; size_t _queSize; vector<unique_ptr<Thread> > _threads; TaskQueue _taskque; bool _isExit; }; } #endif<file_sep>/oo_ThreadPool/TaskQueue.h #ifndef __WD_TASKQUEUE_H__ #define __WD_TASKQUEUE_H__ #include "MutexLock.h" #include "Condition.h" #include <queue> using std::queue; namespace wd { class Task; typedef Task * ElemType; class TaskQueue { public: TaskQueue(size_t queSize); bool empty() const; bool full() const; void push(const ElemType & elem); ElemType pop(); void wakeup(){ _flag = false; _notEmpty.notifyall(); } private: size_t _queSize; queue<ElemType> _que; MutexLock _mutex; Condition _notFull; Condition _notEmpty; bool _flag; }; }//end of namespace wd #endif <file_sep>/oo_producer_consumer/TaskQueue.h #ifndef __TASKQUEUE_H__ #define __TASKQUEUE_H__ #include"MutexLock.h" #include"Condition.h" #include<queue> using std::queue; namespace wd { typedef int ElemType; class TaskQueue { public: TaskQueue(size_t queSize); bool empty()const; bool full() const; void push(const ElemType&Elem); ElemType pop(); private: size_t _queSize; queue<ElemType> _que; MutexLock _mutex; Condition _notFull; Condition _notEmpty; }; } #endif<file_sep>/oo_producer_consumer/Consumer.h #ifndef __CONSUMER_H__ #define __CONSUMER_H__ #include"Thread.h" namespace wd { class TaskQueue; class Consumer:public Thread { public: Consumer(TaskQueue&taskQue); private: void run(); private: TaskQueue &_taskQue; }; } #endif
9f38a78e03e8d230c0da5caaece9f9593d3b3aed
[ "Markdown", "C++" ]
23
C++
cachefish/Thread_mutex
f15ee4ee231ae9bed9a20ff9d26cdeba396b6f2c
e9993a964211958c367e435c4e72d7595f1f5cf7
refs/heads/master
<repo_name>ctir006/Coding-interview<file_sep>/F5_2.py str=input("Enter the sting: ") str_arr=str.split(" ") if(len(str_arr)<=1): print("Invalid Input ") else: t=str_arr[0] str_arr[0]=str_arr[1] str_arr[1]=t print(", ".join(str_arr))
e50cf9249af31abf35646aa49b19f6ea7280e62a
[ "Python" ]
1
Python
ctir006/Coding-interview
fb8d23e248cbe04fcadfa3bcf9ab38b55d98ff1a
2d51a18d2d29ab2ada662f9798b72eca3a6f5e7a
refs/heads/master
<file_sep>use crate::{analyses, ir, lattices, loaders, checkers}; use std::collections::HashSet; use std::convert::TryFrom; use analyses::locals_analyzer::LocalsAnalyzer; use analyses::{AbstractAnalyzer, AnalysisResult}; use checkers::Checker; use ir::types::{FunType, IRMap, MemArgs, Stmt, ValSize, Value, VarIndex, X86Regs}; use ir::utils::is_stack_access; use lattices::localslattice::{LocalsLattice, SlotVal}; use lattices::reachingdefslattice::LocIdx; use loaders::utils::is_libcall; use loaders::utils::to_system_v; use yaxpeax_x86::long_mode::Opcode; use SlotVal::*; use ValSize::*; use X86Regs::*; pub struct LocalsChecker<'a> { irmap: &'a IRMap, analyzer: &'a LocalsAnalyzer<'a>, } pub fn check_locals( result: AnalysisResult<LocalsLattice>, irmap: &IRMap, analyzer: &LocalsAnalyzer, ) -> bool { LocalsChecker { irmap, analyzer }.check(result) } fn is_noninit_illegal(v: &Value) -> bool { match v { Value::Mem(memsize, memargs) => !is_stack_access(v), Value::Reg(reg_num, _) => false, // { // *reg_num != Rsp && *reg_num != Rbp && !(X86Regs::is_flag(*reg_num)) // }, // false, Value::Imm(_, _, _) => false, //imm are always "init" Value::RIPConst => false, } } impl LocalsChecker<'_> { fn all_args_are_init(&self, state: &LocalsLattice, sig: FunType) -> bool { for arg in sig.args.iter() { match arg { (VarIndex::Stack(offset), size) => { let bytesize = size.into_bytes(); // -8 is because the return address has not been pushed let v = state.stack.get(i64::from(*offset - 8), bytesize); if v != Init { println!( "found arg that was not initialized: stack[{:?}] sig: {:?}", offset - 8, sig ); return false; } } (VarIndex::Reg(reg), size) => { let v = state.regs.get_reg(*reg, *size); if v != Init { println!( "found arg that was not initialized: {:?} sig: {:?}", reg, sig ); return false; } } } } true } fn ret_is_uninitialized(&self, state: &LocalsLattice) -> bool { let ret_ty = self.analyzer.fun_type.ret; if ret_ty.is_none() { false } else { let (r, sz) = ret_ty.unwrap(); state.regs.get_reg(r, sz) != Init } } // Check if callee-saved registers have been restored properly // RSP and RBP are handled by stack analysis fn regs_not_restored(&self, state: &LocalsLattice) -> bool { for reg in vec![Rbx, R12, R13, R14, R15].iter() { let v = state.regs.get_reg(*reg, Size64); if v != UninitCalleeReg(*reg) { return true; } } false } } impl Checker<LocalsLattice> for LocalsChecker<'_> { fn check(&self, result: AnalysisResult<LocalsLattice>) -> bool { self.check_state_at_statements(result) } fn irmap(&self) -> &IRMap { self.irmap } fn aexec(&self, state: &mut LocalsLattice, ir_stmt: &Stmt, loc: &LocIdx) { self.analyzer.aexec(state, ir_stmt, loc) } fn check_statement(&self, state: &LocalsLattice, stmt: &Stmt, loc_idx: &LocIdx) -> bool { let debug_addrs: HashSet<u64> = vec![].into_iter().collect(); if debug_addrs.contains(&loc_idx.addr) { println!("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); println!("{}", state); println!("check_statement debug 0x{:x?}: {:?}", loc_idx.addr, stmt); let mut cloned = state.clone(); self.aexec(&mut cloned, stmt, loc_idx); println!("{}", cloned); println!("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); } let error = match stmt { // 1. No writes to memory of uninit values Stmt::Clear(dst, srcs) => { (self.analyzer.aeval_vals(state, srcs, loc_idx) != Init) && is_noninit_illegal(dst) } Stmt::Unop(_, dst, src) => { (self.analyzer.aeval_val(state, src, loc_idx) != Init) && is_noninit_illegal(dst) } Stmt::Binop(opcode, dst, src1, src2) => { self.analyzer .aeval_vals(state, &vec![src1.clone(), src2.clone()], loc_idx) != Init && is_noninit_illegal(dst) } // 2. No branch on uninit allowed Stmt::Branch(br_type, val) => match br_type { Opcode::JO | Opcode::JNO => state.regs.get_reg(Of, Size8) != Init, Opcode::JB | Opcode::JNB => state.regs.get_reg(Cf, Size8) != Init, Opcode::JZ | Opcode::JNZ => state.regs.get_reg(Zf, Size8) != Init, Opcode::JA | Opcode::JNA => { state.regs.get_reg(Cf, Size8) != Init || state.regs.get_reg(Zf, Size8) != Init } Opcode::JS | Opcode::JNS => state.regs.get_reg(Sf, Size8) != Init, Opcode::JP | Opcode::JNP => state.regs.get_reg(Pf, Size8) != Init, Opcode::JL | Opcode::JGE => { state.regs.get_reg(Sf, Size8) != Init || state.regs.get_reg(Of, Size8) != Init } Opcode::JG | Opcode::JLE => { state.regs.get_reg(Sf, Size8) != Init || state.regs.get_reg(Sf, Size8) != Init || state.regs.get_reg(Of, Size8) != Init } _ => false, }, // self.analyzer.aeval_val(state, val, loc_idx) != Init, // 3. check that return values are initialized (if the function has any) // 3.1 also check that all caller saved regs have been restored Stmt::Ret => self.ret_is_uninitialized(state) || self.regs_not_restored(state), // 4. check that all function arguments are initialized (if the called function has any) Stmt::Call(val) => { let signature = match val { // 4.1 Check direct calls Value::Imm(_, _, dst) => { let target = (*dst + (loc_idx.addr as i64) + 5) as u64; let name = self.analyzer.name_addr_map.get(&target); let v = name .and_then(|name| self.analyzer.symbol_table.indexes.get(name)) .and_then(|sig_index| { self.analyzer .symbol_table .signatures .get(*sig_index as usize) }); if let Some(n) = name { if is_libcall(n) { return true; } } v } // 4.2 Check indirect calls Value::Reg(_, _) => self .analyzer .call_analyzer .get_fn_ptr_type(&self.analyzer.call_analysis, loc_idx, val) .and_then(|fn_ptr_index| { self.analyzer .symbol_table .signatures .get(fn_ptr_index as usize) }), _ => panic!("bad call value: {:?}", val), }; let type_check_result = if let Some(ty_sig) = signature.map(|sig| to_system_v(sig)) { !self.all_args_are_init(state, ty_sig) } else { true }; // checks that call targets aren't uninitialized values type_check_result || self.analyzer.aeval_val(state, val, loc_idx) != Init } _ => false, }; if error { println!("----------------------------------------"); println!("{}", state); println!("Darn: 0x{:x?}: {:?}", loc_idx.addr, stmt); // println!("", self.irmap.get(loc_idx)); // println!("{:?}", self.analyzer.fun_type); println!("----------------------------------------") } !error } } <file_sep>use crate::{analyses, checkers, ir, loaders}; use analyses::reaching_defs::analyze_reaching_defs; use analyses::reaching_defs::ReachingDefnAnalyzer; use analyses::{run_worklist, SwitchAnalyzer}; use checkers::resolve_jumps; use ir::lift_cfg; use ir::types::IRMap; use ir::utils::has_indirect_jumps; use loaders::types::VwModule; use yaxpeax_core::analyses::control_flow::{get_cfg, VW_CFG}; use yaxpeax_core::arch::x86_64::MergedContextTable; fn try_resolve_jumps( module: &VwModule, contexts: &MergedContextTable, cfg: &VW_CFG, irmap: &IRMap, _addr: u64, strict: bool, ) -> (VW_CFG, IRMap, i32, u32) { println!("Performing a reaching defs pass"); let reaching_defs = analyze_reaching_defs(cfg, &irmap, module.metadata.clone()); println!("Performing a jump resolution pass"); let switch_analyzer = SwitchAnalyzer { metadata: module.metadata.clone(), reaching_defs: reaching_defs, reaching_analyzer: ReachingDefnAnalyzer { cfg: cfg.clone(), irmap: irmap.clone(), }, }; let switch_results = run_worklist(cfg, irmap, &switch_analyzer); let switch_targets = resolve_jumps(&module.program, switch_results, &irmap, &switch_analyzer); let (new_cfg, still_unresolved) = get_cfg( &module.program, contexts, cfg.entrypoint, Some(&switch_targets), ); let irmap = lift_cfg(module, &new_cfg, strict); let num_targets = switch_targets.len(); return (new_cfg, irmap, num_targets as i32, still_unresolved); } fn resolve_cfg( module: &VwModule, contexts: &MergedContextTable, cfg: &VW_CFG, orig_irmap: &IRMap, addr: u64, strict: bool, ) -> (VW_CFG, IRMap) { let (mut cfg, mut irmap, mut resolved_switches, mut still_unresolved) = try_resolve_jumps(module, contexts, cfg, orig_irmap, addr, strict); while still_unresolved != 0 { let (new_cfg, new_irmap, new_resolved_switches, new_still_unresolved) = try_resolve_jumps(module, contexts, &cfg, &irmap, addr, strict); cfg = new_cfg; irmap = new_irmap; if (new_resolved_switches == resolved_switches) && (new_still_unresolved != 0) { panic!("Fixed Point Error"); } resolved_switches = new_resolved_switches; still_unresolved = new_still_unresolved; } assert_eq!(cfg.graph.node_count(), irmap.keys().len()); assert_eq!(still_unresolved, 0); (cfg, irmap) } pub fn fully_resolved_cfg( module: &VwModule, contexts: &MergedContextTable, addr: u64, strict: bool, ) -> (VW_CFG, IRMap) { let (cfg, _) = get_cfg(&module.program, contexts, addr, None); let irmap = lift_cfg(module, &cfg, strict); if !has_indirect_jumps(&irmap) { return (cfg, irmap); } return resolve_cfg(module, contexts, &cfg, &irmap, addr, strict); } <file_sep>use crate::ir::types::{Binopcode, Value}; use crate::lattices::{ConstLattice, VarState}; /// Fields are: (stackgrowth, probestack, rbp_stackgrowth) /// /// `stackgrowth` is a value that indicates how far downward the stack is valid. /// /// `rbp_stackgrowth` is a copy of `stackgrowth` that is saved when `rsp` is /// copied to `rbp` during frame setup in the prologue. When `rsp` is restored /// from `rbp` in the epilogue, it is copied back. pub type StackGrowthLattice = ConstLattice<(i64, i64, i64)>; impl VarState for StackGrowthLattice { type Var = i64; fn get(&self, _index: &Value) -> Option<Self::Var> { unimplemented!() } fn set(&mut self, _index: &Value, _v: Self::Var) -> () { unimplemented!() } fn set_to_bot(&mut self, _index: &Value) -> () { unimplemented!() } fn on_call(&mut self) -> () { unimplemented!() } fn adjust_stack_offset( &mut self, _opcode: &Binopcode, _dst: &Value, _src1: &Value, _src2: &Value, ) { unimplemented!() } } impl StackGrowthLattice { pub fn get_stackgrowth(&self) -> Option<i64> { match self.v { Some((stackgrowth, _, _)) => Some(stackgrowth), None => None, } } pub fn get_probestack(&self) -> Option<i64> { match self.v { Some((_, probestack, _)) => Some(probestack), None => None, } } pub fn get_rbp(&self) -> Option<i64> { match self.v { Some((_, _, rbp)) => Some(rbp), None => None, } } } #[test] fn stack_growth_lattice_test() { use crate::lattices::reachingdefslattice::LocIdx; use crate::lattices::Lattice; let x1 = StackGrowthLattice { v: None }; let x2 = StackGrowthLattice { v: Some((1, 4096, 0)), }; let x3 = StackGrowthLattice { v: Some((1, 4096, 0)), }; let x4 = StackGrowthLattice { v: Some((2, 4096, 0)), }; assert_eq!(x1 == x2, false); assert_eq!(x2 == x3, true); assert_eq!(x3 == x4, false); assert_eq!(x1 != x2, true); assert_eq!(x2 != x3, false); assert_eq!(x3 != x4, true); assert_eq!(x1 > x2, false); assert_eq!(x2 > x3, false); assert_eq!(x3 > x4, false); assert_eq!(x1 < x2, true); assert_eq!(x2 < x3, false); assert_eq!(x3 < x4, false); assert_eq!( x1.meet(&x2, &LocIdx { addr: 0, idx: 0 }) == StackGrowthLattice { v: None }, true ); assert_eq!( x2.meet(&x3, &LocIdx { addr: 0, idx: 0 }) == StackGrowthLattice { v: Some((1, 4096, 0)) }, true ); assert_eq!( x3.meet(&x4, &LocIdx { addr: 0, idx: 0 }) == StackGrowthLattice { v: None }, true ); } <file_sep>#![allow(dead_code, unused_imports, unused_variables)] use veriwasm::{analyses, checkers, ir, loaders, runner}; use analyses::reaching_defs::{analyze_reaching_defs, ReachingDefnAnalyzer}; use analyses::run_worklist; use analyses::{CallAnalyzer, HeapAnalyzer, StackAnalyzer}; use checkers::{check_calls, check_heap, check_stack}; use ir::fully_resolved_cfg; use ir::utils::has_indirect_calls; use loaders::types::VwFuncInfo; use loaders::types::{ExecutableType, VwArch}; use loaders::utils::get_data; use loaders::Loadable; use lucet_module::{Signature, ValueType}; use std::collections::HashMap; use std::panic; use veriwasm::runner::run_locals; use yaxpeax_core::analyses::control_flow::check_cfg_integrity; fn full_test_helper(path: &str, format: ExecutableType, arch: VwArch) { let _ = env_logger::builder().is_test(true).try_init(); let active_passes = runner::PassConfig { stack: true, linear_mem: true, call: true, zero_cost: false, }; let config = runner::Config { module_path: path.to_string(), _num_jobs: 1, output_path: "".to_string(), has_output: false, only_func: None, executable_type: format, active_passes, arch, }; runner::run(config); } fn negative_test_helper(path: &str, func_name: &str, format: ExecutableType, arch: VwArch) { let _ = env_logger::builder().is_test(true).try_init(); let active_passes = runner::PassConfig { stack: true, linear_mem: true, call: true, zero_cost: false, }; let config = runner::Config { module_path: path.to_string(), _num_jobs: 1, output_path: "".to_string(), has_output: false, only_func: Some(func_name.to_string()), executable_type: format, active_passes, arch, }; runner::run(config); } #[test] fn full_test_libgraphite() { full_test_helper( "./veriwasm_public_data/firefox_libs/libgraphitewasm.so", ExecutableType::Lucet, VwArch::X64, ) } #[test] fn full_test_libogg() { full_test_helper( "./veriwasm_public_data/firefox_libs/liboggwasm.so", ExecutableType::Lucet, VwArch::X64, ) } #[test] #[should_panic(expected = "Not Stack Safe")] fn negative_test_1() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_1_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Not Stack Safe")] fn negative_test_2() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_2_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Not Stack Safe")] fn negative_test_3() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_3_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Jump Targets Broken, target = None")] fn negative_test_4() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_4_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Not Call Safe")] fn negative_test_5() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_5_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Jump Targets Broken, target = None")] fn negative_test_6() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_6_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Not Heap Safe")] fn negative_test_7() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_7_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Not Heap Safe")] fn negative_test_8() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_8_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Not Heap Safe")] fn negative_test_9() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_9_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Not Heap Safe")] fn negative_test_10() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_10_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Not Heap Safe")] fn negative_test_11() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_11_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "not implemented")] fn negative_test_12() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_12_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "not implemented")] fn negative_test_13() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_13_testfail", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Not Stack Safe")] fn negative_test_14() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_14_testfail", ExecutableType::Lucet, VwArch::X64, ); } // # NaCl issue #23 #[test] #[should_panic(expected = "Not Call Safe")] fn negative_test_nacl_23() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_nacl_23", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "not implemented")] fn negative_test_nacl_323_1() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_nacl_323_1", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "not implemented")] fn negative_test_nacl_323_2() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_nacl_323_2", ExecutableType::Lucet, VwArch::X64, ); } #[test] #[should_panic(expected = "Not Stack Safe")] fn negative_test_misfit_1() { negative_test_helper( "veriwasm_public_data/negative_tests/negative_tests.so", "guest_func_misfit_1", ExecutableType::Lucet, VwArch::X64, ); } // fn get_proxy_func_signatures() -> VwFuncInfo { // let mut signatures: Vec<Signature> = Vec::new(); // // sig0 :: i32 -> () // let sig0 = Signature { // params: vec![ValueType::I32], // ret_ty: None, // }; // // sig1 :: i32 -> i32 -> () // let sig1 = Signature { // params: vec![ValueType::I32, ValueType::I32], // ret_ty: None, // }; // // sig2 :: i32 -> i32 // let sig2 = Signature { // params: vec![ValueType::I32], // ret_ty: Some(ValueType::I32), // }; // signatures.push(sig0); // signatures.push(sig1); // signatures.push(sig2); // let mut indexes: HashMap<String, u32> = HashMap::new(); // indexes.insert("func1".to_string(), 0); // indexes.insert("func2".to_string(), 0); // indexes.insert("func3".to_string(), 1); // indexes.insert("func4".to_string(), 0); // indexes.insert("func5".to_string(), 0); // indexes.insert("subfunc5".to_string(), 1); // indexes.insert("func6".to_string(), 0); // indexes.insert("func7".to_string(), 2); // indexes.insert("func8".to_string(), 0); // indexes.insert("func9".to_string(), 0); // VwFuncInfo { // signatures, // indexes, // } // } // fn negative_test_with_locals(path: &str, func_name: &str, format: ExecutableType, arch: VwArch) { // let _ = env_logger::builder().is_test(true).try_init(); // let program = format.load_program(&path); // let (x86_64_data, func_addrs, plt, all_addrs) = get_data(&program, &format); // let all_addrs_map = HashMap::from_iter(all_addrs.clone()); // let valid_funcs: Vec<u64> = func_addrs.clone().iter().map(|x| x.0).collect(); // println!("Loading Metadata"); // let metadata = format.load_metadata(&program); // let ((cfg, irmap), x86_64_data) = get_one_resolved_cfg(path, func_name, &program, &format); // println!("Analyzing: {:?}", func_name); // check_cfg_integrity(&cfg.blocks, &cfg.graph); // println!("Checking Stack Safety"); // let stack_analyzer = StackAnalyzer {}; // let stack_result = run_worklist(&cfg, &irmap, &stack_analyzer); // let stack_safe = check_stack(stack_result, &irmap, &stack_analyzer); // assert!(stack_safe); // println!("Checking Heap Safety"); // let heap_analyzer = HeapAnalyzer { // metadata: metadata.clone(), // }; // let heap_result = run_worklist(&cfg, &irmap, &heap_analyzer); // let heap_safe = check_heap(heap_result, &irmap, &heap_analyzer, &all_addrs_map); // assert!(heap_safe); // println!("Checking Call Safety"); // let reaching_defs = analyze_reaching_defs(&cfg, &irmap, metadata.clone()); // let call_analyzer = CallAnalyzer { // metadata: metadata.clone(), // reaching_defs: reaching_defs.clone(), // reaching_analyzer: ReachingDefnAnalyzer { // cfg: cfg.clone(), // irmap: irmap.clone(), // }, // funcs: vec![], // cfg: cfg.clone(), // irmap: irmap.clone(), // }; // let call_result = run_worklist(&cfg, &irmap, &call_analyzer); // let call_safe = check_calls( // call_result.clone(), // &irmap, // &call_analyzer, // &valid_funcs, // &plt, // ); // assert!(call_safe); // // Not actually used by locals checker // let plt = (0, 0); // // Fairly confident this will break // //let func_signatures = format.get_func_signatures(&program); // let func_signatures = get_proxy_func_signatures(); // println!("Checking Locals safety"); // let locals_safe = run_locals( // reaching_defs, // call_result, // plt, // &all_addrs_map, // &func_signatures, // &func_name.to_string(), // &cfg, // &irmap, // &metadata, // &valid_funcs, // ); // assert!(locals_safe); // println!("Done! "); // } // #[test] // #[should_panic(expected = "assertion failed: stack_safe")] // fn negative_test_zerocost_1() { // negative_test_with_locals( // "veriwasm_public_data/negative_tests/negative_tests_locals.so", // "func1", // ExecutableType::Lucet, // VwArch::X64, // ); // } // #[test] // #[should_panic(expected = "assertion failed: stack_safe")] // fn negative_test_zerocost_2() { // negative_test_with_locals( // "veriwasm_public_data/negative_tests/negative_tests_locals.so", // "func2", // ExecutableType::Lucet, // VwArch::X64, // ); // } // #[test] // #[should_panic(expected = "Not Stack Safe")] // fn negative_test_nacl_323_4() { // negative_test_helper( // "veriwasm_public_data/negative_tests/negative_tests.so", // "guest_func_nacl_323_4", // ExecutableType::Lucet, // VwArch::X64, // ); // } // #[should_panic(expected = "assertion failed: stack_safe")] // fn negative_test_zerocost_3() { // negative_test_with_locals( // "veriwasm_public_data/negative_tests/negative_tests_locals.so", // "func3", // ExecutableType::Lucet, // VwArch::X64, // ); // } // #[test] // #[should_panic(expected = "assertion failed: locals_safe")] // fn negative_test_zerocost_4() { // negative_test_with_locals( // "veriwasm_public_data/negative_tests/negative_tests_locals.so", // "func4", // ExecutableType::Lucet, // VwArch::X64, // ); // } // #[test] // #[should_panic(expected = "assertion failed: locals_safe")] // fn negative_test_zerocost_5() { // negative_test_with_locals( // "veriwasm_public_data/negative_tests/negative_tests_locals.so", // "func5", // ExecutableType::Lucet, // VwArch::X64, // ); // } // #[test] // #[should_panic(expected = "assertion failed: locals_safe")] // fn negative_test_zerocost_6() { // negative_test_with_locals( // "veriwasm_public_data/negative_tests/negative_tests_locals.so", // "func6", // ExecutableType::Lucet, // VwArch::X64, // ); // } // #[test] // #[should_panic(expected = "assertion failed: locals_safe")] // fn negative_test_zerocost_7() { // negative_test_with_locals( // "veriwasm_public_data/negative_tests/negative_tests_locals.so", // "func7", // ExecutableType::Lucet, // VwArch::X64, // ); // } // #[should_panic] // fn negative_test_zerocost_8() { // negative_test_with_locals( // "veriwasm_public_data/negative_tests/negative_tests_locals.so", // "func8", // ExecutableType::Lucet, // VwArch::X64, // ); // } // #[test] // #[should_panic(expected = "assertion failed: call_safe")] // fn negative_test_zerocost_9() { // negative_test_with_locals( // "veriwasm_public_data/negative_tests/negative_tests_locals.so", // "func9", // ExecutableType::Lucet, // VwArch::X64, // ); // } // #[test] // fn wasmtime_wasm_callback() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/callback.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_fib() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/fib-wasm.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_fraction_norm() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/fraction-norm.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_hello() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/hello.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_memory() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/memory.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_reflect() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/reflect.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_serialize() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/serialize.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_table() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/table.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_trap() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/trap.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_fib_wasm_dwarf5() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/fib-wasm-dwarf5.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_finalize() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/finalize.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_global() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/global.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_issue_1306() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/issue-1306-name-section-with-u32-max-function-index.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_multi() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/multi.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_reverse_str() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/reverse-str.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_start() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/start.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wasm_threads() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wasm/threads.wasm", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_fuel() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/fuel.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_greeter_reactor() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/greeter_reactor.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_illop_invoke() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/iloop-invoke.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_linking2() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/linking2.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_minimal_reactor() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/minimal-reactor.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_threads() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/threads.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_exit125_wasi_snapshot1() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/exit125_wasi_snapshot1.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_gcd() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/gcd.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_hello_wasi_snapshot0() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/hello_wasi_snapshot0.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_iloop_start() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/iloop-start.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_loop_params() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/loop-params.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_multi() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/multi.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_unreachable() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/unreachable.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_exit_with_saved_fprs() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/exit_with_saved_fprs.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_greeter_callable_command() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/greeter_callable_command.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_interrupt() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/interrupt.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_memory() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/memory.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_rs2wasm_add_func() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/rs2wasm-add-func.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_externref() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/externref.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_greeter_command() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/greeter_command.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_hello() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/hello.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_linking1() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/linking1.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_minimal_command() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/minimal-command.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } // #[test] // fn wasmtime_wat_simple() { // full_test_helper( // "./veriwasm_public_data/wasmtime/bin/wat/simple.wat", // ExecutableType::Wasmtime, // VwArch::X64, // ) // } <file_sep>#![allow(non_camel_case_types)] use lucet_module::{Signature, ValueType}; use std::collections::HashMap; use crate::ir::types::{FunType, ValSize, VarIndex, X86Regs}; use crate::loaders::types::ExecutableType; use crate::loaders::Loadable; use yaxpeax_arch::Arch; use yaxpeax_core::arch::x86_64::x86_64Data; use yaxpeax_core::arch::{BaseUpdate, Library, Symbol, SymbolQuery}; use yaxpeax_core::goblin::elf::program_header::ProgramHeader; use yaxpeax_core::memory::repr::process::{ ELFExport, ELFImport, ELFSection, ELFSymbol, ModuleData, ModuleInfo, }; use yaxpeax_core::memory::MemoryRepr; use yaxpeax_core::ContextWrite; use yaxpeax_x86::long_mode::Arch as AMD64; use X86Regs::*; pub fn is_libcall(name: &String) -> bool { vec!["floor", "ceil", "trunc", "ceil"].contains(&&name[..]) } //return addr of symbol if present, else None pub fn get_symbol_addr(symbols: &Vec<ELFSymbol>, name: &str) -> Option<u64> { symbols .iter() .find(|sym| sym.name == name) .map(|sym| sym.addr) } pub fn deconstruct_elf( program: &ModuleData, ) -> ( &Vec<ProgramHeader>, &Vec<ELFSection>, &u64, &Vec<ELFImport>, &Vec<ELFExport>, &Vec<ELFSymbol>, ) { match (program as &dyn MemoryRepr<<AMD64 as Arch>::Address>).module_info() { Some(ModuleInfo::ELF( isa, _header, program_header, sections, entry, _relocs, imports, exports, symbols, )) => (program_header, sections, entry, imports, exports, symbols), Some(other) => { panic!("Module isn't an elf, but is a {:?}?", other); } None => { panic!("Module doesn't appear to be a binary yaxpeax understands."); } } } fn get_function_starts( entrypoint: &u64, symbols: &Vec<ELFSymbol>, imports: &Vec<ELFImport>, exports: &Vec<ELFExport>, _text_section_idx: usize, ) -> x86_64Data { let mut x86_64_data = x86_64Data::default(); // start queuing up places we expect to find functions x86_64_data.contexts.put( *entrypoint as u64, BaseUpdate::Specialized(yaxpeax_core::arch::x86_64::x86Update::FunctionHint), ); // copy in symbols (not really necessary here) for sym in symbols { if sym.name != "" { x86_64_data.contexts.put( sym.addr as u64, BaseUpdate::DefineSymbol(Symbol(Library::This, sym.name.clone())), ); } } //All symbols in text section should be function starts for sym in symbols { x86_64_data.contexts.put( sym.addr as u64, BaseUpdate::Specialized(yaxpeax_core::arch::x86_64::x86Update::FunctionHint), ); } // and copy in names for imports for import in imports { x86_64_data.contexts.put( import.value as u64, BaseUpdate::DefineSymbol(Symbol(Library::Unknown, import.name.clone())), ); } // exports are probably functions? hope for the best for export in exports { x86_64_data.contexts.put( export.addr as u64, BaseUpdate::Specialized(yaxpeax_core::arch::x86_64::x86Update::FunctionHint), ); } x86_64_data } // pub fn get_data( // program: &ModuleData, // format: &ExecutableType, // ) -> (x86_64Data, Vec<(u64, std::string::String)>, (u64, u64)) { // let (_, sections, entrypoint, imports, exports, symbols) = deconstruct_elf(program); // let text_section_idx = sections.iter().position(|x| x.name == ".text").unwrap(); // let mut x86_64_data = // get_function_starts(entrypoint, symbols, imports, exports, text_section_idx); // let plt_bounds = if let Some(plt_idx) = sections.iter().position(|x| x.name == ".plt") { // let plt = sections.get(plt_idx).unwrap(); // (plt.start, plt.start + plt.size) // } else { // (0, 0) // }; // let text_section = sections.get(text_section_idx).unwrap(); // let mut addrs: Vec<(u64, std::string::String)> = Vec::new(); // while let Some(addr) = x86_64_data.contexts.function_hints.pop() { // if !((addr >= text_section.start) && (addr < (text_section.start + text_section.size))) { // continue; // } // if let Some(symbol) = x86_64_data.symbol_for(addr) { // if format.is_valid_func_name(&symbol.1) { // addrs.push((addr, symbol.1.clone())); // } // } // } // (x86_64_data, addrs, plt_bounds) // } pub fn get_data( program: &ModuleData, format: &ExecutableType, ) -> ( x86_64Data, Vec<(u64, String)>, (u64, u64), Vec<(u64, String)>, ) { let (_, sections, entrypoint, imports, exports, symbols) = deconstruct_elf(program); let text_section_idx = sections.iter().position(|x| x.name == ".text").unwrap(); let mut x86_64_data = get_function_starts(entrypoint, symbols, imports, exports, text_section_idx); let plt_bounds = if let Some(plt_idx) = sections.iter().position(|x| x.name == ".plt") { let plt = sections.get(plt_idx).unwrap(); (plt.start, plt.start + plt.size) } else { (0, 0) }; let text_section = sections.get(text_section_idx).unwrap(); let mut addrs: Vec<(u64, std::string::String)> = Vec::new(); let mut all_addrs: Vec<(u64, std::string::String)> = Vec::new(); while let Some(addr) = x86_64_data.contexts.function_hints.pop() { if let Some(symbol) = x86_64_data.symbol_for(addr) { all_addrs.push((addr, symbol.1.clone())); } if !((addr >= text_section.start) && (addr < (text_section.start + text_section.size))) { continue; } if let Some(symbol) = x86_64_data.symbol_for(addr) { if format.is_valid_func_name(&symbol.1) { addrs.push((addr, symbol.1.clone())); } } } (x86_64_data, addrs, plt_bounds, all_addrs) } // libcalls don't implicitly pass vmctx as the first argument pub fn to_libcall(sig: &Signature) -> FunType { let mut arg_locs = Vec::new(); let mut i_ctr = 0; // integer arg # let mut f_ctr = 0; // floating point arg # let mut stack_offset = 0; arg_locs.push((VarIndex::Reg(Rdi), ValSize::Size64)); for arg in &sig.params { match arg { ValueType::I32 | ValueType::I64 => { let index = match i_ctr { 0 => VarIndex::Reg(Rdi), 1 => VarIndex::Reg(Rsi), 2 => VarIndex::Reg(Rdx), 3 => VarIndex::Reg(Rcx), 4 => VarIndex::Reg(R8), 5 => VarIndex::Reg(R9), _ => { stack_offset += 8; VarIndex::Stack(stack_offset) } }; match arg { ValueType::I32 => arg_locs.push((index, ValSize::Size32)), ValueType::I64 => arg_locs.push((index, ValSize::Size64)), _ => (), }; i_ctr += 1; } ValueType::F32 | ValueType::F64 => { let index = match f_ctr { 0 => VarIndex::Reg(Zmm0), 1 => VarIndex::Reg(Zmm1), 2 => VarIndex::Reg(Zmm2), 3 => VarIndex::Reg(Zmm3), 4 => VarIndex::Reg(Zmm4), 5 => VarIndex::Reg(Zmm5), 6 => VarIndex::Reg(Zmm6), 7 => VarIndex::Reg(Zmm7), _ => { stack_offset += 8; //stack slots are 8 byte aligned VarIndex::Stack(stack_offset) } }; match arg { ValueType::F32 => arg_locs.push((index, ValSize::Size32)), ValueType::F64 => arg_locs.push((index, ValSize::Size64)), _ => (), }; f_ctr += 1; } } } return FunType { args: arg_locs, ret: to_system_v_ret_ty(sig), }; } // TODO: unify this with other register and stack variable slot representations // RDI, RSI, RDX, RCX, R8, R9, // 7, 6, 3, 2, 8, 9, then stack slots pub fn to_system_v(sig: &Signature) -> FunType { let mut arg_locs = Vec::new(); let mut i_ctr = 0; // integer arg # let mut f_ctr = 0; // floating point arg # let mut stack_offset = 0; arg_locs.push((VarIndex::Reg(Rdi), ValSize::Size64)); for arg in &sig.params { match arg { ValueType::I32 | ValueType::I64 => { let index = match i_ctr { 0 => VarIndex::Reg(Rsi), 1 => VarIndex::Reg(Rdx), 2 => VarIndex::Reg(Rcx), 3 => VarIndex::Reg(R8), 4 => VarIndex::Reg(R9), _ => { stack_offset += 8; VarIndex::Stack(stack_offset) } }; match arg { ValueType::I32 => arg_locs.push((index, ValSize::Size32)), ValueType::I64 => arg_locs.push((index, ValSize::Size64)), _ => (), }; i_ctr += 1; } ValueType::F32 | ValueType::F64 => { let index = match f_ctr { 0 => VarIndex::Reg(Zmm0), 1 => VarIndex::Reg(Zmm1), 2 => VarIndex::Reg(Zmm2), 3 => VarIndex::Reg(Zmm3), 4 => VarIndex::Reg(Zmm4), 5 => VarIndex::Reg(Zmm5), 6 => VarIndex::Reg(Zmm6), 7 => VarIndex::Reg(Zmm7), _ => { stack_offset += 8; //stack slots are 8 byte aligned VarIndex::Stack(stack_offset) } }; match arg { ValueType::F32 => arg_locs.push((index, ValSize::Size32)), ValueType::F64 => arg_locs.push((index, ValSize::Size64)), _ => (), }; f_ctr += 1; } } } return FunType { args: arg_locs, ret: to_system_v_ret_ty(sig), }; } pub fn to_system_v_ret_ty(sig: &Signature) -> Option<(X86Regs, ValSize)> { sig.ret_ty.and_then(|ty| match ty { ValueType::I32 => Some((Rax, ValSize::Size32)), ValueType::I64 => Some((Rax, ValSize::Size64)), ValueType::F32 => Some((Zmm0, ValSize::Size32)), ValueType::F64 => Some((Zmm0, ValSize::Size64)), }) } <file_sep>//! Library entry point for stack and heap validation, given a single //! function's machine code and basic-block offsets. #![allow(dead_code, unused_imports, unused_variables)] pub mod analyses; pub mod checkers; pub mod ir; pub mod lattices; pub mod loaders; pub mod runner; use analyses::run_worklist; use analyses::HeapAnalyzer; use checkers::check_heap; use ir::lift_cfg; use ir::types::IRMap; use loaders::types::{ExecutableType, VwArch, VwMetadata, VwModule}; use petgraph::graphmap::GraphMap; use std::collections::BTreeMap; use yaxpeax_core::analyses::control_flow::{VW_Block, VW_CFG}; use yaxpeax_core::memory::repr::process::{ModuleData, ModuleInfo, Segment}; #[derive(Clone, Copy, Debug)] pub enum ValidationError { HeapUnsafe, } impl std::fmt::Display for ValidationError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { std::fmt::Debug::fmt(self, f) } } impl std::error::Error for ValidationError {} /// How the Wasm heap is accessed in machine code. This will allow the /// check to be parameterized to work with different VMs -- first /// Lucet, eventually Wasmtime, perhaps others -- that have slightly /// different VM-context data structure layouts. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HeapStrategy { /// The first argument to functions is a hidden argument that is /// the heap base. Accesses to the heap are computed relative to /// this base. The virtual-memory layout has sufficient guard /// regions that no bounds-checks are necessary as long as only an /// unsigned 32-bit offset is added to the base. /// /// This corresponds to Lucet's design. HeapPtrFirstArgWithGuards, /// The first argument to functions is a hidden VM-context struct /// pointer, and another pointer within this struct points to the /// Wasm heap. The guard region is assumed to be present as /// above. The offset to the heap-base pointer within vmctx is /// configurable. /// /// This corresponds to Wasmtime's design. VMCtxFirstArgWithGuards { vmctx_heap_base_ptr_offset: usize }, } fn func_body_and_bbs_to_cfg( code: &[u8], basic_blocks: &[usize], cfg_edges: &[(usize, usize)], ) -> (VW_CFG, IRMap, VwModule) { // We build the VW_CFG manually; we skip the CFG-recovery // algorithm that has to analyze the machine code and compute // reaching-defs in a fixpoint loop. let mut cfg = VW_CFG { entrypoint: 0, blocks: BTreeMap::new(), graph: GraphMap::new(), }; for i in 0..basic_blocks.len() { let start = basic_blocks[i] as u64; let end = if i == basic_blocks.len() - 1 { code.len() as u64 } else { basic_blocks[i + 1] as u64 }; assert!(end > start, "block has zero length: {} -> {}", start, end); let end = end - 1; // `end` is inclusive! let bb = VW_Block { start, end }; cfg.blocks.insert(start, bb); cfg.graph.add_node(start); } for &(from, to) in cfg_edges { cfg.graph.add_edge(from as u64, to as u64, ()); } let seg = Segment { start: 0, data: code.iter().cloned().collect(), name: ".text".to_owned(), }; let header = yaxpeax_core::goblin::elf::header::Header { e_ident: [ 0x7f, 0x45, 0x4c, 0x4f, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ], e_type: 0x0003, e_machine: 0x003e, e_version: 0x00000001, e_entry: 0, e_phoff: 0, e_shoff: 0, e_flags: 0, e_ehsize: 0, e_phentsize: 0, e_phnum: 0, e_shentsize: 0, e_shnum: 0, e_shstrndx: 0, }; let module_info = ModuleInfo::ELF( yaxpeax_core::memory::repr::process::ISAHint::Hint(yaxpeax_core::arch::ISA::x86_64), header, vec![], vec![], 0, vec![], vec![], vec![], vec![], ); let data = ModuleData { segments: vec![seg], name: "function.o".to_owned(), module_info, }; let lucet = VwMetadata { guest_table_0: 0x123456789abcdef0, lucet_tables: 0x123456789abcdef0, lucet_probestack: 0x123456789abcdef0, }; let module = VwModule { program: data, metadata: lucet, format: ExecutableType::Lucet, arch: VwArch::X64, }; let irmap = lift_cfg(&module, &cfg, false); (cfg, irmap, module) // TODO: regalloc checker from Lucet too. // TODO: audit opcodes. Fallback to just clear dest(s) on unknown? // TODO: how hard would this be to adapt to Wasmtime? Extra level of indirection: // heap-base loaded from vmctx (rdi) instead. Take a mode argument? // "Heap-access style" } pub fn validate_heap( code: &[u8], basic_blocks: &[usize], cfg_edges: &[(usize, usize)], heap_strategy: HeapStrategy, ) -> Result<(), ValidationError> { log::debug!( "validate_heap: basic_blocks = {:?}, edges = {:?}", basic_blocks, cfg_edges ); // For now, we don't support Wasmtime-style heap accesses. // TODO: implement these: // - Add a lattice value: VMCtxPtr // - Add a rule: load from [VMCtxPtr + heap_base_ptr_offset] -> HeapBase match heap_strategy { HeapStrategy::HeapPtrFirstArgWithGuards => {} _ => { log::debug!("Unknown heap strategy: {:?}", heap_strategy); return Err(ValidationError::HeapUnsafe); } } let (cfg, irmap, module) = func_body_and_bbs_to_cfg(code, basic_blocks, cfg_edges); // This entry point is designed to allow checking of a single // function body, just after it has been generated in memory, // without the metadata that would usually come along with an ELF // binary. // // Without symbols/relocs, we don't know which calls are to // `lucet_probestack()`, so we can't do a stack-use soundness // check, and we don't know which globals are `lucet_tables` and // `guest_table_0`, so we can't check instance function calls. We // also can't really do the full CFG recovery analysis and CFI // checks because it's very expensive (the reaching-defs analysis // has not been optimized) and requires knowing other function // addresses. // // However, the heap check is the most important one, and we *can* // do that. Why are the others less important? Mainly because we // trust their implementations a little more: e.g., the br_table // code is a single open-coded sequence that is generated just at // machine-code emission, after all optimizations and regalloc, // with its bounds-check embedded inside. The CFG lowering itself // is handled by the MachBuffer in the new Cranelift backend, and // this has a correctness proof. Stack probes are either present // or not, and we have tests to ensure that they are when the // frame is large enough. The address computation that goes into a // heap access is the most exposed -- it's just ordinary CLIF IR // that goes through the compilation pipeline with opt passes like // all other code. It's also the fastest and simplest to check. let heap_analyzer = HeapAnalyzer { metadata: module.metadata.clone(), }; let heap_result = run_worklist(&cfg, &irmap, &heap_analyzer); // let heap_safe = check_heap(heap_result, &irmap, &heap_analyzer); // if !heap_safe { // return Err(ValidationError::HeapUnsafe); // } Ok(()) } <file_sep>use crate::lattices; use lattices::reachingdefslattice::{LocIdx, ReachingDefnLattice}; use lattices::Lattice; use std::cmp::Ordering; // Dependent Abstract Value #[derive(Clone, PartialEq, Eq, Debug)] pub enum DAV { Unknown, Unchecked(ReachingDefnLattice), Checked, } impl PartialOrd for DAV { fn partial_cmp(&self, other: &DAV) -> Option<Ordering> { match (self, other) { (DAV::Unknown, DAV::Unknown) => Some(Ordering::Equal), (DAV::Unknown, _) => Some(Ordering::Less), (DAV::Unchecked(x), DAV::Unchecked(y)) => { if x == y { Some(Ordering::Equal) } else { None } } (DAV::Unchecked(_), DAV::Checked) => Some(Ordering::Less), (DAV::Checked, DAV::Checked) => Some(Ordering::Equal), (DAV::Checked, DAV::Unchecked(_)) => Some(Ordering::Greater), (DAV::Unchecked(_), DAV::Unknown) => Some(Ordering::Greater), (DAV::Checked, DAV::Unknown) => Some(Ordering::Greater), } } } impl Lattice for DAV { fn meet(&self, other: &Self, _loc_idx: &LocIdx) -> Self { match (self, other) { (DAV::Unknown, _) => DAV::Unknown, (_, DAV::Unknown) => DAV::Unknown, (DAV::Unchecked(x), DAV::Unchecked(y)) => { if x == y { self.clone() } else { DAV::Unknown } } (DAV::Checked, DAV::Checked) => self.clone(), (DAV::Unchecked(_), DAV::Checked) => self.clone(), (DAV::Checked, DAV::Unchecked(_)) => other.clone(), } } } //What is a default index? This might be wrong. //Perhaps default is what index should be at start of function. impl Default for DAV { fn default() -> Self { DAV::Unknown } } <file_sep>use crate::ir::types::Stmt; use crate::VwMetadata; pub fn lift( instr: &yaxpeax_x86::long_mode::Instruction, addr: &u64, metadata: &VwMetadata, strict: bool, ) -> Vec<Stmt> { unimplemented!() } <file_sep>use crate::{analyses, checkers, ir, lattices}; use analyses::StackAnalyzer; use analyses::{AbstractAnalyzer, AnalysisResult}; use checkers::Checker; use ir::types::{IRMap, MemArgs, Stmt, Value}; use ir::utils::{get_imm_mem_offset, is_bp_access, is_stack_access}; use lattices::reachingdefslattice::LocIdx; use lattices::stackgrowthlattice::StackGrowthLattice; pub struct StackChecker<'a> { irmap: &'a IRMap, analyzer: &'a StackAnalyzer, } pub fn check_stack( result: AnalysisResult<StackGrowthLattice>, irmap: &IRMap, analyzer: &StackAnalyzer, ) -> bool { StackChecker { irmap: irmap, analyzer: analyzer, } .check(result) } impl Checker<StackGrowthLattice> for StackChecker<'_> { fn check(&self, result: AnalysisResult<StackGrowthLattice>) -> bool { self.check_state_at_statements(result) } fn irmap(&self) -> &IRMap { self.irmap } fn aexec(&self, state: &mut StackGrowthLattice, ir_stmt: &Stmt, loc: &LocIdx) { self.analyzer.aexec(state, ir_stmt, loc) } fn check_statement( &self, state: &StackGrowthLattice, ir_stmt: &Stmt, _loc_idx: &LocIdx, ) -> bool { //1, stackgrowth is never Bottom or >= 0 match state.v { None => { println!("Failure Case at {:?}: Stackgrowth = None", ir_stmt); return false; } Some((stackgrowth, _, _)) => { if stackgrowth > 0 { return false; } } } // 2. Reads and writes are in bounds match ir_stmt { //encapsulates both load and store Stmt::Unop(_, dst, src) => // stack write: probestack <= stackgrowth + c < 0 { if is_stack_access(dst) { if !self.check_stack_write(state, dst) { log::debug!( "check_stack_write failed: access = {:?} state = {:?}", dst, state ); return false; } } if is_bp_access(dst) { if !self.check_bp_write(state, dst) { log::debug!( "check_bp_write failed: access = {:?} state = {:?}", dst, state ); return false; } } //stack read: probestack <= stackgrowth + c < 8K if is_stack_access(src) { if !self.check_stack_read(state, src) { log::debug!( "check_stack_read failed: access = {:?} state = {:?}", src, state ); return false; } } else if is_bp_access(src) { if !self.check_bp_read(state, src) { log::debug!( "check_bp_read failed: access = {:?} state = {:?}", src, state ); return false; } } } _ => (), } // 3. For all rets stackgrowth = 0 if let Stmt::Ret = ir_stmt { if let Some((stackgrowth, _, _)) = state.v { if stackgrowth != 0 { log::debug!("stackgrowth != 0 at ret: stackgrowth = {:?}", stackgrowth); return false; } } } true } } impl StackChecker<'_> { fn check_stack_read(&self, state: &StackGrowthLattice, src: &Value) -> bool { if let Value::Mem(_, memargs) = src { match memargs { MemArgs::Mem1Arg(_memarg) => { return (-state.get_probestack().unwrap() <= state.get_stackgrowth().unwrap()) && (state.get_stackgrowth().unwrap() < 8096) } MemArgs::Mem2Args(_memarg1, memarg2) => { let offset = get_imm_mem_offset(memarg2); return (-state.get_probestack().unwrap() <= state.get_stackgrowth().unwrap() + offset) && (state.get_stackgrowth().unwrap() + offset < 8096); } _ => return false, //stack accesses should never have 3 args } } panic!("Unreachable") } fn check_bp_read(&self, state: &StackGrowthLattice, src: &Value) -> bool { if let Value::Mem(_, memargs) = src { match memargs { MemArgs::Mem1Arg(_memarg) => { return (-state.get_probestack().unwrap() <= state.get_rbp().unwrap()) && (state.get_rbp().unwrap() < 8096) } MemArgs::Mem2Args(_memarg1, memarg2) => { let offset = get_imm_mem_offset(memarg2); return (-state.get_probestack().unwrap() <= state.get_rbp().unwrap() + offset) && (state.get_rbp().unwrap() + offset < 8096); } _ => return false, //stack accesses should never have 3 args } } panic!("Unreachable") } fn check_stack_write(&self, state: &StackGrowthLattice, dst: &Value) -> bool { if let Value::Mem(_, memargs) = dst { match memargs { MemArgs::Mem1Arg(_memarg) => { return (-state.get_probestack().unwrap() <= state.get_stackgrowth().unwrap()) && (state.get_stackgrowth().unwrap() < 0); } MemArgs::Mem2Args(_memarg1, memarg2) => { let offset = get_imm_mem_offset(memarg2); return (-state.get_probestack().unwrap() <= state.get_stackgrowth().unwrap() + offset) && (state.get_stackgrowth().unwrap() + offset < 0); } _ => return false, //stack accesses should never have 3 args } } panic!("Unreachable") } fn check_bp_write(&self, state: &StackGrowthLattice, dst: &Value) -> bool { if let Value::Mem(_, memargs) = dst { match memargs { MemArgs::Mem1Arg(_memarg) => { return (-state.get_probestack().unwrap() <= state.get_rbp().unwrap()) && (state.get_rbp().unwrap() < 0); } MemArgs::Mem2Args(_memarg1, memarg2) => { let offset = get_imm_mem_offset(memarg2); return (-state.get_probestack().unwrap() <= state.get_rbp().unwrap() + offset) && (state.get_rbp().unwrap() + offset < 0); } _ => return false, //stack accesses should never have 3 args } } panic!("Unreachable") } } <file_sep>pub mod calllattice; pub mod davlattice; pub mod heaplattice; pub mod localslattice; pub mod reachingdefslattice; pub mod regslattice; pub mod stackgrowthlattice; pub mod stacklattice; pub mod switchlattice; use crate::{ir, lattices}; use ir::types::{Binopcode, MemArg, MemArgs, ValSize, Value, X86Regs}; use ir::utils::{get_imm_offset, is_rsp}; use lattices::reachingdefslattice::LocIdx; use lattices::regslattice::X86RegsLattice; use lattices::stacklattice::StackLattice; use std::cmp::Ordering; use std::fmt::Debug; use X86Regs::*; #[derive(PartialEq, Eq, Clone, Debug)] pub struct VarSlot<T> { pub size: u32, pub value: T, } impl<T: PartialOrd> PartialOrd for VarSlot<T> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { if self.size != other.size { None } else { self.value.partial_cmp(&other.value) } } } pub trait Lattice: PartialOrd + Eq + Default + Debug { fn meet(&self, other: &Self, loc: &LocIdx) -> Self; } pub trait VarState { type Var; fn get(&self, index: &Value) -> Option<Self::Var>; fn set(&mut self, index: &Value, v: Self::Var) -> (); fn set_to_bot(&mut self, index: &Value) -> (); fn on_call(&mut self) -> (); fn adjust_stack_offset(&mut self, opcode: &Binopcode, dst: &Value, src1: &Value, src2: &Value); } #[derive(Eq, Clone, Copy, Debug)] pub struct BooleanLattice { v: bool, } impl PartialOrd for BooleanLattice { fn partial_cmp(&self, other: &BooleanLattice) -> Option<Ordering> { Some(self.v.cmp(&other.v)) } } impl PartialEq for BooleanLattice { fn eq(&self, other: &BooleanLattice) -> bool { self.v == other.v } } impl Lattice for BooleanLattice { fn meet(&self, other: &Self, _loc_idx: &LocIdx) -> Self { BooleanLattice { v: self.v && other.v, } } } impl Default for BooleanLattice { fn default() -> Self { BooleanLattice { v: false } } } pub type Constu32Lattice = ConstLattice<u32>; #[derive(Eq, Clone, Debug)] pub struct ConstLattice<T: Eq + Clone + Debug> { pub v: Option<T>, } impl<T: Eq + Clone + Debug> PartialOrd for ConstLattice<T> { fn partial_cmp(&self, other: &ConstLattice<T>) -> Option<Ordering> { match (self.v.as_ref(), other.v.as_ref()) { (None, None) => Some(Ordering::Equal), (None, _) => Some(Ordering::Less), (_, None) => Some(Ordering::Greater), (Some(x), Some(y)) => { if x == y { Some(Ordering::Equal) } else { None } } } } } impl<T: Eq + Clone + Debug> PartialEq for ConstLattice<T> { fn eq(&self, other: &ConstLattice<T>) -> bool { self.v == other.v } } impl<T: Eq + Clone + Debug> Lattice for ConstLattice<T> { fn meet(&self, other: &Self, _loc_idx: &LocIdx) -> Self { if self.v == other.v { ConstLattice { v: self.v.clone() } } else { ConstLattice { v: None } } } } impl<T: Eq + Clone + Debug> Default for ConstLattice<T> { fn default() -> Self { ConstLattice { v: None } } } impl<T: Eq + Clone + Debug> ConstLattice<T> { pub fn new(v: T) -> Self { ConstLattice { v: Some(v) } } } #[derive(PartialEq, Eq, PartialOrd, Default, Clone, Debug)] pub struct VariableState<T> { pub regs: X86RegsLattice<T>, pub stack: StackLattice<T>, } impl<T: std::fmt::Debug + Clone> std::fmt::Display for VariableState<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{{\n\t{:?}\n\n\t{}\n}}", self.regs, self.stack) } } // offset from current stack pointer // returns None if points to heap pub fn mem_to_stack_offset(memargs: &MemArgs) -> Option<i64> { match memargs { MemArgs::Mem1Arg(arg) => { if let MemArg::Reg(regnum, _) = arg { if *regnum == Rsp { return Some(0); } } } MemArgs::Mem2Args(arg1, arg2) => { if let MemArg::Reg(regnum, _) = arg1 { if *regnum == Rsp { if let MemArg::Imm(_, _, offset) = arg2 { return Some(*offset); } } } } _ => (), } return None; } impl<T: Lattice + Clone> Lattice for VariableState<T> { fn meet(&self, other: &Self, loc_idx: &LocIdx) -> Self { VariableState { regs: self.regs.meet(&other.regs, loc_idx), stack: self.stack.meet(&other.stack, loc_idx), } } } impl<T: Lattice + Clone> VarState for VariableState<T> { type Var = T; fn set(&mut self, index: &Value, value: T) -> () { match index { Value::Mem(memsize, memargs) => { if let Some(offset) = mem_to_stack_offset(memargs) { self.stack.update(offset, value, memsize.into_bytes()) } } Value::Reg(regnum, s2) => self.regs.set_reg(*regnum, *s2, value), Value::Imm(_, _, _) => panic!("Trying to write to an immediate value"), Value::RIPConst => panic!("Trying to write to a RIP constant"), } } fn get(&self, index: &Value) -> Option<T> { match index { Value::Mem(memsize, memargs) => mem_to_stack_offset(memargs) .map(|offset| self.stack.get(offset, memsize.into_bytes())), Value::Reg(regnum, s2) => Some(self.regs.get_reg(*regnum, *s2)), Value::Imm(_, _, _) => None, Value::RIPConst => None, } } fn set_to_bot(&mut self, index: &Value) { self.set(index, Default::default()) } fn on_call(&mut self) { self.regs.clear_caller_save_regs(); } fn adjust_stack_offset(&mut self, opcode: &Binopcode, dst: &Value, src1: &Value, src2: &Value) { if is_rsp(dst) { if is_rsp(src1) { let adjustment = get_imm_offset(src2); match opcode { Binopcode::Add => self.stack.update_stack_offset(adjustment), Binopcode::Sub => self.stack.update_stack_offset(-adjustment), _ => panic!("Illegal RSP write"), } } else { panic!("Illegal RSP write") } } } } #[test] fn boolean_lattice_test() { let x = BooleanLattice { v: false }; let y = BooleanLattice { v: true }; assert_eq!(x < y, true); assert_eq!(x > y, false); assert_eq!(x.lt(&y), true); } #[test] fn u32_lattice_test() { let x1 = ConstLattice::<u32> { v: Some(1) }; let x2 = ConstLattice::<u32> { v: Some(1) }; let y1 = ConstLattice::<u32> { v: Some(2) }; let y2 = ConstLattice::<u32> { v: Some(2) }; let z1 = Constu32Lattice { v: Some(3) }; let z2 = Constu32Lattice { v: Some(3) }; assert_eq!(x1 < y1, false); assert_eq!(y1 < x1, false); assert_eq!(x1 == x2, true); assert_eq!(x1 != x2, false); assert_eq!(y2 != x1, true); assert_eq!(x1 >= y1, false); assert_eq!(x1 > x2, false); assert_eq!(x1 >= x2, true); assert_eq!(z1 == z2, true); assert_eq!(z1 == x1, false); assert_eq!(x1.lt(&y1), false); } <file_sep>use std::convert::TryFrom; use std::mem::discriminant; use crate::ir::types::*; use crate::ir::utils::{mk_value_i64, valsize}; use crate::loaders::types::{VwMetadata, VwModule}; use yaxpeax_arch::{AddressBase, Arch, LengthedInstruction}; use yaxpeax_core::analyses::control_flow::VW_CFG; use yaxpeax_core::arch::x86_64::analyses::data_flow::Location; use yaxpeax_core::arch::InstructionSpan; use yaxpeax_core::data::{Direction, ValueLocations}; use yaxpeax_x86::long_mode::Opcode::*; use yaxpeax_x86::long_mode::{ register_class, Arch as AMD64, Instruction as X64Instruction, Opcode, Operand, RegSpec, }; use ValSize::{Size128, Size16, Size256, Size32, Size512, Size64, Size8}; use X86Regs::*; fn get_reg_size(reg: yaxpeax_x86::long_mode::RegSpec) -> ValSize { let size = match reg.class() { register_class::Q => Size64, register_class::D => Size32, register_class::W => Size16, register_class::B => Size8, register_class::RB => Size8, register_class::RIP => panic!("Write to RIP: {:?}", reg.class()), register_class::EIP => panic!("Write to EIP: {:?}", reg.class()), register_class::X => Size128, register_class::Y => Size256, register_class::Z => Size512, _ => panic!("Unknown register bank: {:?}", reg.class()), }; return size; } fn convert_reg(reg: yaxpeax_x86::long_mode::RegSpec) -> Value { let (num, size) = match (reg.num(), reg.class()) { (n, register_class::Q) => (n, Size64), (n, register_class::D) => (n, Size32), (n, register_class::W) => (n, Size16), (n, register_class::B) => (n, Size8), (n, register_class::RB) => (n, Size8), (_, register_class::RIP) => panic!("Write to RIP: {:?}", reg.class()), (_, register_class::EIP) => panic!("Write to EIP: {:?}", reg.class()), (n, register_class::X) => (n + ValSize::fp_offset(), Size128), (n, register_class::Y) => (n + ValSize::fp_offset(), Size256), (n, register_class::Z) => (n + ValSize::fp_offset(), Size512), _ => panic!("Unknown register bank: {:?}", reg.class()), }; Value::Reg(X86Regs::try_from(num).unwrap(), size) } fn convert_memarg_reg(reg: yaxpeax_x86::long_mode::RegSpec) -> MemArg { let size = match reg.class() { register_class::Q => Size64, register_class::D => Size32, register_class::W => Size16, register_class::B => Size8, _ => panic!("Unknown register bank: {:?}", reg.class()), }; MemArg::Reg(X86Regs::try_from(reg.num()).unwrap(), size) } fn convert_operand(op: yaxpeax_x86::long_mode::Operand, memsize: ValSize) -> Value { match op { Operand::ImmediateI8(imm) => Value::Imm(ImmType::Signed, Size8, imm as i64), Operand::ImmediateU8(imm) => Value::Imm(ImmType::Unsigned, Size8, imm as i64), Operand::ImmediateI16(imm) => Value::Imm(ImmType::Signed, Size16, imm as i64), Operand::ImmediateU16(imm) => Value::Imm(ImmType::Unsigned, Size16, imm as i64), Operand::ImmediateU32(imm) => Value::Imm(ImmType::Unsigned, Size32, imm as i64), Operand::ImmediateI32(imm) => Value::Imm(ImmType::Signed, Size32, imm as i64), Operand::ImmediateU64(imm) => Value::Imm(ImmType::Unsigned, Size64, imm as i64), Operand::ImmediateI64(imm) => Value::Imm(ImmType::Signed, Size64, imm as i64), Operand::Register(reg) => {log::debug!("convert_operand widths {:?} {:?}", op, op.width()); convert_reg(reg)}, //u32 and u64 are address sizes Operand::DisplacementU32(imm) => Value::Mem( memsize, MemArgs::Mem1Arg(MemArg::Imm(ImmType::Unsigned, Size32, imm as i64)), ), //mem[c] Operand::DisplacementU64(imm) => Value::Mem( memsize, MemArgs::Mem1Arg(MemArg::Imm(ImmType::Unsigned, Size64, imm as i64)), ), //mem[c] Operand::RegDeref(reg) if reg == RegSpec::rip() => Value::RIPConst, Operand::RegDeref(reg) => Value::Mem(memsize, MemArgs::Mem1Arg(convert_memarg_reg(reg))), // mem[reg] Operand::RegDisp(reg, _) if reg == RegSpec::rip() => Value::RIPConst, Operand::RegDisp(reg, imm) => Value::Mem( memsize, MemArgs::Mem2Args( convert_memarg_reg(reg), MemArg::Imm(ImmType::Signed, Size32, imm as i64), ), ), //mem[reg + c] Operand::RegIndexBase(reg1, reg2) => Value::Mem( memsize, MemArgs::Mem2Args(convert_memarg_reg(reg1), convert_memarg_reg(reg2)), ), // mem[reg1 + reg2] Operand::RegIndexBaseDisp(reg1, reg2, imm) => Value::Mem( memsize, MemArgs::Mem3Args( convert_memarg_reg(reg1), convert_memarg_reg(reg2), MemArg::Imm(ImmType::Signed, Size32, imm as i64), ), ), //mem[reg1 + reg2 + c] Operand::RegScale(_, _) => panic!("Memory operations with scaling prohibited"), // mem[reg * c] Operand::RegScaleDisp(_, _, _) => panic!("Memory operations with scaling prohibited"), //mem[reg*c1 + c2] Operand::RegIndexBaseScale(reg1, reg2, scale) => //mem[reg1 + reg2*c] { if scale == 1 { Value::Mem( memsize, MemArgs::Mem2Args(convert_memarg_reg(reg1), convert_memarg_reg(reg2)), ) } else { Value::Mem( memsize, MemArgs::MemScale( convert_memarg_reg(reg1), convert_memarg_reg(reg2), MemArg::Imm(ImmType::Signed, Size32, scale as i64), ), ) } } Operand::RegIndexBaseScaleDisp(reg1, reg2, scale, imm) => { assert_eq!(scale, 1); Value::Mem( memsize, MemArgs::Mem3Args( convert_memarg_reg(reg1), convert_memarg_reg(reg2), MemArg::Imm(ImmType::Signed, Size32, imm as i64), ), ) } //mem[reg1 + reg2*c1 + c2] Operand::Nothing => panic!("Nothing Operand?"), op => { panic!("Unhandled operand {}", op); } } } // Captures all register and flag sources // TODO: Memory? fn get_sources(instr: &X64Instruction) -> Vec<Value> { let uses_vec = <AMD64 as ValueLocations>::decompose(instr); let mut sources = Vec::new(); for (loc, dir) in uses_vec { match (loc, dir) { (Some(Location::Register(reg)), Direction::Read) => { sources.push(convert_reg(reg)); } (Some(Location::ZF), Direction::Read) => { sources.push(Value::Reg(Zf, Size8)); } (Some(Location::CF), Direction::Read) => { sources.push(Value::Reg(Cf, Size8)); } (Some(Location::UnevalMem(op)), Direction::Read) => { sources.push(convert_operand(op, Size32)); // is Size32 right? } _ => {} } } return sources; } // Captures all register and flag destinations // TODO: Memory? fn get_destinations(instr: &X64Instruction) -> Vec<Value> { let uses_vec = <AMD64 as ValueLocations>::decompose(instr); let mut destinations = Vec::new(); for (loc, dir) in uses_vec { match (loc, dir) { (Some(Location::Register(reg)), Direction::Write) => { // println!("destination: {:?} width = {:?}", reg, reg.width()); destinations.push(convert_reg(reg)); } (Some(Location::ZF), Direction::Write) => { destinations.push(Value::Reg(Zf, Size8)); } (Some(Location::CF), Direction::Write) => { destinations.push(Value::Reg(Cf, Size8)); } (Some(Location::UnevalMem(op)), Direction::Read) => { destinations.push(convert_operand(op, Size32)); // is Size32 right? } _ => {} } } return destinations; } fn generic_clear(instr: &X64Instruction) -> Vec<Stmt> { let mut stmts = vec![]; let sources = get_sources(&instr); let dsts = get_destinations(&instr); for dst in dsts { stmts.push(Stmt::Clear(dst, sources.clone())); } stmts } fn get_operand_size(op: &yaxpeax_x86::long_mode::Operand) -> Option<ValSize> { match op { Operand::ImmediateI8(_) | Operand::ImmediateU8(_) => Some(Size8), Operand::ImmediateI16(_) | Operand::ImmediateU16(_) => Some(Size16), Operand::ImmediateU32(_) | Operand::ImmediateI32(_) => Some(Size32), Operand::ImmediateU64(_) | Operand::ImmediateI64(_) => Some(Size64), Operand::Register(reg) => Some(get_reg_size(*reg)), //u32 and u64 are address sizes Operand::DisplacementU32(_) | Operand::DisplacementU64(_) | Operand::RegDeref(_) | Operand::RegDisp(_, _) | Operand::RegIndexBase(_, _) | Operand::RegIndexBaseDisp(_, _, _) | Operand::RegScale(_, _) | Operand::RegScaleDisp(_, _, _) | Operand::RegIndexBaseScale(_, _, _) | Operand::RegIndexBaseScaleDisp(_, _, _, _) | Operand::Nothing => None, op => { panic!("unsupported operand size: {}", op); } } } fn set_from_flags(operand: Operand, flags: Vec<X86Regs>) -> Stmt { Stmt::Clear( convert_operand(operand, Size8), flags.iter().map(|flag| Value::Reg(*flag, Size8)).collect(), ) } fn unop(opcode: Unopcode, instr: &X64Instruction) -> Stmt { let memsize = match ( get_operand_size(&instr.operand(0)), get_operand_size(&instr.operand(1)), ) { (None, None) => panic!("Two Memory Args?"), (Some(x), None) => x, (None, Some(x)) => x, (Some(x), Some(_y)) => x, }; Stmt::Unop( opcode, convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(1), memsize), ) } fn unop_w_memsize(opcode: Unopcode, instr: &X64Instruction, memsize: ValSize) -> Stmt { Stmt::Unop( opcode, convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(1), memsize), ) } fn binop(opcode: Binopcode, instr: &X64Instruction) -> Stmt { let memsize = match ( get_operand_size(&instr.operand(0)), get_operand_size(&instr.operand(1)), ) { (None, None) => panic!("Two Memory Args?"), (Some(x), None) => x, (None, Some(x)) => x, (Some(x), Some(_y)) => x, }; // if two operands than dst is src1 if instr.operand_count() == 2 { Stmt::Binop( opcode, convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(1), memsize), ) } else { Stmt::Binop( opcode, convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(1), memsize), convert_operand(instr.operand(2), memsize), ) } } fn branch(instr: &X64Instruction) -> Stmt { Stmt::Branch(instr.opcode(), convert_operand(instr.operand(0), Size64)) } fn call(instr: &X64Instruction, _metadata: &VwMetadata) -> Stmt { let dst = convert_operand(instr.operand(0), Size64); Stmt::Call(dst) } fn lea(instr: &X64Instruction, addr: &Addr) -> Vec<Stmt> { let dst = instr.operand(0); let src1 = instr.operand(1); if let Operand::RegDisp(reg, disp) = src1 { if reg == RegSpec::rip() { //addr + instruction length + displacement let length = 0u64.wrapping_offset(instr.len()).to_linear(); let target = (*addr as i64) + (length as i64) + (disp as i64); return vec![Stmt::Unop( Unopcode::Mov, convert_operand(dst.clone(), get_operand_size(&dst).unwrap()), Value::Imm(ImmType::Signed, Size64, target), )]; } } match convert_operand(src1, get_operand_size(&dst).unwrap()) { Value::Mem(_, memargs) => match memargs { MemArgs::Mem1Arg(arg) => match arg { MemArg::Imm(_, _, _val) => vec![unop(Unopcode::Mov, instr)], _ => generic_clear(instr), //clear_dst(instr), }, _ => generic_clear(instr), //clear_dst(instr), }, _ => panic!("Illegal lea"), } } pub fn lift(instr: &X64Instruction, addr: &Addr, metadata: &VwMetadata, strict: bool) -> Vec<Stmt> { log::debug!("lift: addr 0x{:x} instr {:?}", addr, instr); let mut instrs = Vec::new(); match instr.opcode() { Opcode::MOV => instrs.push(unop(Unopcode::Mov, instr)), Opcode::MOVQ => instrs.push(unop_w_memsize(Unopcode::Mov, instr, Size64)), Opcode::MOVZX_b | Opcode::MOVZX_w => instrs.push(unop(Unopcode::Mov, instr)), Opcode::MOVD => instrs.push(unop_w_memsize(Unopcode::Mov, instr, Size32)), Opcode::MOVSD => instrs.push(unop_w_memsize(Unopcode::Mov, instr, Size64)), Opcode::MOVSX | Opcode::MOVSX_w | Opcode::MOVSX_b | Opcode::MOVSXD => instrs.push(unop(Unopcode::Movsx, instr)), Opcode::LEA => instrs.extend(lea(instr, addr)), Opcode::TEST => { let memsize = match ( get_operand_size(&instr.operand(0)), get_operand_size(&instr.operand(1)), ) { (None, None) => panic!("Two Memory Args?"), (Some(x), None) => x, (None, Some(x)) => x, (Some(x), Some(_y)) => x, }; instrs.push(Stmt::Binop( Binopcode::Test, Value::Reg(Zf, Size8), convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(1), memsize), )); instrs.push(Stmt::Binop( Binopcode::Test, Value::Reg(Cf, Size8), convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(1), memsize), )); } Opcode::UCOMISS | Opcode::UCOMISD | Opcode::CMP => { let memsize = match ( get_operand_size(&instr.operand(0)), get_operand_size(&instr.operand(1)), ) { (None, None) => panic!("Two Memory Args?"), (Some(x), None) => x, (None, Some(x)) => x, (Some(x), Some(_y)) => x, }; instrs.push(Stmt::Binop( Binopcode::Cmp, Value::Reg(Zf, Size8), convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(1), memsize), )); instrs.push(Stmt::Binop( Binopcode::Cmp, Value::Reg(Cf, Size8), convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(1), memsize), )); instrs.push(Stmt::Binop( Binopcode::Cmp, Value::Reg(Pf, Size8), convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(1), memsize), )); instrs.push(Stmt::Binop( Binopcode::Cmp, Value::Reg(Sf, Size8), convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(1), memsize), )); instrs.push(Stmt::Binop( Binopcode::Cmp, Value::Reg(Of, Size8), convert_operand(instr.operand(0), memsize), convert_operand(instr.operand(1), memsize), )); }, Opcode::AND => { instrs.push(binop(Binopcode::And, instr)); instrs.push(Stmt::Clear( Value::Reg(Zf, Size8), get_sources(instr), )) } Opcode::ADD => { instrs.push(binop(Binopcode::Add, instr)); instrs.push(Stmt::Clear( Value::Reg(Zf, Size8), get_sources(instr), )) } Opcode::SUB => { instrs.push(binop(Binopcode::Sub, instr)); instrs.push(Stmt::Clear( Value::Reg(Zf, Size8), get_sources(instr), )) } Opcode::SHL => { instrs.push(binop(Binopcode::Shl, instr)); instrs.push(Stmt::Clear( Value::Reg(Zf, Size8), get_sources(instr), )) } Opcode::CMOVNB => { // Part of Spectre mitigation. Assume CMOV never happens (if it does, we just trap). /* nothing */ } Opcode::UD2 => instrs.push(Stmt::Undefined), Opcode::RETURN => instrs.push(Stmt::Ret), Opcode::JMP => instrs.push(branch(instr)), Opcode::JO | Opcode::JNO | Opcode::JB | Opcode::JNB | Opcode::JZ | Opcode::JNZ | Opcode::JA | Opcode::JNA | Opcode::JS | Opcode::JNS | Opcode::JP | Opcode::JNP | Opcode::JL | Opcode::JGE | Opcode::JLE | Opcode::JG => instrs.push(branch(instr)), Opcode::CALL => instrs.push(call(instr, metadata)), Opcode::PUSH => { let width = instr.operand(0).width(); assert_eq!(width, 8); //8 bytes instrs.push(Stmt::Binop( Binopcode::Sub, Value::Reg(Rsp, Size64), Value::Reg(Rsp, Size64), mk_value_i64(width.into()), )); instrs.push(Stmt::Unop( Unopcode::Mov, Value::Mem( valsize((width * 8) as u32), MemArgs::Mem1Arg(MemArg::Reg(Rsp, Size64)), ), convert_operand(instr.operand(0), Size64), )) } Opcode::POP => { let width = instr.operand(0).width(); assert_eq!(width, 8); //8 bytes instrs.push(Stmt::Unop( Unopcode::Mov, convert_operand(instr.operand(0), Size64), Value::Mem( valsize((width * 8) as u32), MemArgs::Mem1Arg(MemArg::Reg(Rsp, Size64)), ), )); instrs.push(Stmt::Binop( Binopcode::Add, Value::Reg(Rsp, Size64), Value::Reg(Rsp, Size64), mk_value_i64(width.into()), )) } Opcode::NOP | Opcode::FILD | Opcode::STD | Opcode::CLD | Opcode::STI => (), // Opcode::IDIV | Opcode::DIV => { // // instrs.push(Stmt::Clear(Value::Reg(Zf, ValSize::Size8), vec![])); // instrs.push(Stmt::Clear(Value::Reg(Rax, Size64), vec![])); // clear RAX // instrs.push(Stmt::Clear(Value::Reg(Rdx, Size64), vec![])); // clear RDX // instrs.push(Stmt::Clear( // Value::Reg(Zf, Size8), // get_sources(instr), // )); // } Opcode::XORPS // TODO: do we need to generalize the size logic? | Opcode::XORPD | Opcode::XOR => { //XOR reg, reg => mov reg, 0 if instr.operand_count() == 2 && instr.operand(0) == instr.operand(1) { instrs.push(Stmt::Unop( Unopcode::Mov, convert_operand(instr.operand(0), Size64), Value::Imm(ImmType::Signed, Size64, 0), )); instrs.push(Stmt::Clear( Value::Reg(Zf, Size8), get_sources(instr), )); } else { instrs.extend(generic_clear(instr)); // instrs.extend(clear_dst(instr)) } } Opcode::CDQ | Opcode::CDQE => { // clear rax instrs.push(Stmt::Clear(Value::Reg(Rax, ValSize::Size64), vec![])); // clear rdx instrs.push(Stmt::Clear(Value::Reg(Rdx, ValSize::Size64), vec![])); } SETG | SETLE => instrs.push(set_from_flags(instr.operand(0), vec![Zf, Sf, Of])), SETO | SETNO => instrs.push(set_from_flags(instr.operand(0), vec![Of])), SETS | SETNS => instrs.push(set_from_flags(instr.operand(0), vec![Sf])), SETGE | SETL => instrs.push(set_from_flags(instr.operand(0), vec![Sf, Of])), SETNZ | SETZ => instrs.push(set_from_flags(instr.operand(0), vec![Zf])), SETAE | SETB => instrs.push(set_from_flags(instr.operand(0), vec![Cf])), SETA | SETBE => instrs.push(set_from_flags(instr.operand(0), vec![Cf, Zf])), SETP | SETNP => instrs.push(set_from_flags(instr.operand(0), vec![Pf])), Opcode::BSF => { instrs.push(Stmt::Clear( Value::Reg(Zf, Size8), vec![convert_operand(instr.operand(1), get_operand_size(&instr.operand(1)).unwrap())], )); instrs.push(Stmt::Clear( convert_operand(instr.operand(0), get_operand_size(&instr.operand(0)).unwrap()), vec![ // convert_operand(instr.operand(0), get_operand_size(&instr.operand(0)).unwrap()), convert_operand(instr.operand(1), get_operand_size(&instr.operand(1)).unwrap()), ], )); } Opcode::BSR => { instrs.push(Stmt::Clear( Value::Reg(Zf, Size8), vec![convert_operand(instr.operand(1), get_operand_size(&instr.operand(1)).unwrap())], )); instrs.push(Stmt::Clear( convert_operand(instr.operand(0), get_operand_size(&instr.operand(0)).unwrap()), vec![ convert_operand(instr.operand(1), get_operand_size(&instr.operand(1)).unwrap()), ], )); } Opcode::LZCNT | Opcode::TZCNT => { instrs.push(Stmt::Clear( Value::Reg(Zf, Size8), vec![convert_operand(instr.operand(1), get_operand_size(&instr.operand(1)).unwrap())], )); instrs.push(Stmt::Clear( convert_operand(instr.operand(0), get_operand_size(&instr.operand(0)).unwrap()), vec![ convert_operand(instr.operand(1), get_operand_size(&instr.operand(1)).unwrap()), ], )); } // TODO: is this right? Opcode::MOVSS => { instrs.push(unop_w_memsize(Unopcode::Mov, instr, Size32)); } Opcode::MOVAPS => { instrs.push(unop(Unopcode::Mov, instr)); } Opcode::CVTSI2SS => { instrs.push(Stmt::Clear( convert_operand(instr.operand(0), get_operand_size(&instr.operand(0)).unwrap()), vec![ convert_operand(instr.operand(1), get_operand_size(&instr.operand(1)).unwrap()), ], )); } Opcode::OR // | Opcode::CDQ // | Opcode::CDQE | Opcode::IDIV | Opcode::DIV | Opcode::SHR | Opcode::RCL | Opcode::RCR | Opcode::ROL | Opcode::ROR | Opcode::CMOVA | Opcode::CMOVB | Opcode::CMOVG | Opcode::CMOVGE | Opcode::CMOVL | Opcode::CMOVLE | Opcode::CMOVNA /* | Opcode::CMOVNB -- see above */ | Opcode::CMOVNO | Opcode::CMOVNP | Opcode::CMOVNS | Opcode::CMOVNZ | Opcode::CMOVO | Opcode::CMOVP | Opcode::CMOVS | Opcode::CMOVZ | Opcode::SAR | Opcode::ADC | Opcode::ROUNDSS | Opcode::MUL | Opcode::IMUL | Opcode::POR | Opcode::PSHUFB | Opcode::PSHUFD | Opcode::PTEST | Opcode::PXOR | Opcode::ANDNPS | Opcode::CMPPD | Opcode::CMPPS | Opcode::ANDPS | Opcode::ORPS | Opcode::DIVSD | Opcode::MULSS | Opcode::ADDSD | Opcode::SUBSS | Opcode::ROUNDSD | Opcode::NOT | Opcode::POPCNT | Opcode::SUBSD | Opcode::MULSD | Opcode::DIVSS // | Opcode::LZCNT | Opcode::DIVPD | Opcode::DIVPS | Opcode::BLENDVPS | Opcode::BLENDVPD | Opcode::MAXPD | Opcode::MAXPS | Opcode::MAXSD | Opcode::MAXSS | Opcode::MINPD | Opcode::MINPS | Opcode::MINSD | Opcode::MINSS | Opcode::MULPD | Opcode::MULPS | Opcode::PMULLW | Opcode::PMULLD | Opcode::CVTDQ2PS | Opcode::CVTSD2SS | Opcode::CVTSI2SD | Opcode::CVTSS2SD | Opcode::CVTTSS2SI | Opcode::ADDPS | Opcode::ADDPD | Opcode::ADDSS | Opcode::PSLLW | Opcode::PSLLD | Opcode::PSLLQ | Opcode::PSRLW | Opcode::PSRLD | Opcode::PSRLQ | Opcode::PSRAW | Opcode::PSRAD | Opcode::PSUBB | Opcode::PSUBW | Opcode::PSUBD | Opcode::PSUBQ | Opcode::PSUBSB | Opcode::PSUBSW | Opcode::PSUBUSB | Opcode::PSUBUSW | Opcode::PUNPCKHBW | Opcode::PUNPCKHWD | Opcode::PUNPCKHDQ | Opcode::PUNPCKHQDQ | Opcode::PUNPCKLBW | Opcode::PUNPCKLWD | Opcode::PUNPCKLDQ | Opcode::PUNPCKLQDQ | Opcode::PACKSSWB | Opcode::PACKSSDW | Opcode::PADDB | Opcode::PADDD | Opcode::PADDQ | Opcode::PADDW | Opcode::PADDSB | Opcode::PADDSW | Opcode::PADDUSB | Opcode::PADDUSW | Opcode::PAND | Opcode::PANDN | Opcode::PAVGB | Opcode::PAVGW | Opcode::PCMPEQB | Opcode::PCMPEQD | Opcode::PCMPEQQ | Opcode::PCMPEQW | Opcode::PCMPGTB | Opcode::PCMPGTD | Opcode::PCMPGTQ | Opcode::PCMPGTW | Opcode::PEXTRB | Opcode::PEXTRW | Opcode::PINSRB | Opcode::PINSRW | Opcode::PMAXSB | Opcode::PMAXSW | Opcode::PMAXUB | Opcode::PMAXUD | Opcode::PMAXUW | Opcode::PMINSB | Opcode::PMINSD | Opcode::PMINSW | Opcode::PMINUB | Opcode::PMINUD | Opcode::PMINUW | Opcode::PMOVSXBW | Opcode::PMOVSXWD | Opcode::PMOVSXDQ | Opcode::PMOVZXBW | Opcode::PMOVZXWD | Opcode::PMOVZXDQ | Opcode::SQRTPD | Opcode::SQRTPS | Opcode::SQRTSD | Opcode::SQRTSS | Opcode::MOVLPS | Opcode::MOVLHPS | Opcode::MOVUPS | Opcode::SUBPD | Opcode::SUBPS | Opcode::SBB | Opcode::ANDPD | Opcode::CVTTSD2SI | Opcode::ORPD => instrs.extend(generic_clear(instr)),/*instrs.extend(clear_dst(instr)),*/ _ => if strict{ unimplemented!() } else { instrs.extend(generic_clear(instr)) }, }; instrs } fn parse_probestack_arg<'a>( instrs: BlockInstrs<'a>, metadata: &VwMetadata, strict: bool, ) -> IResult<'a, (u64, StmtResult)> { let (rest, (addr, move_instr)) = parse_single_instr(instrs, metadata, strict)?; if move_instr.len() != 1 { return Err(ParseErr::Error(instrs)); } if let Stmt::Unop(Unopcode::Mov, Value::Reg(Rax, Size32), Value::Imm(_, _, x)) = move_instr[0] { return Ok((rest, (x as u64, (addr, move_instr)))); } Err(ParseErr::Error(instrs)) } fn parse_probestack_call<'a>( instrs: BlockInstrs<'a>, metadata: &VwMetadata, strict: bool, ) -> IResult<'a, StmtResult> { let (rest, (addr, call_instr)) = parse_single_instr(instrs, metadata, strict)?; if call_instr.len() != 1 { return Err(ParseErr::Error(instrs)); } if let Stmt::Call(Value::Imm(_, _, offset)) = call_instr[0] { if 5 + offset + (addr as i64) == metadata.lucet_probestack as i64 { return Ok((rest, (addr, call_instr))); } } Err(ParseErr::Error(instrs)) } fn parse_probestack_suffix<'a>( instrs: BlockInstrs<'a>, metadata: &VwMetadata, strict: bool, probestack_arg: u64, ) -> IResult<'a, (i64,StmtResult)> { let (rest, (addr, sub_instr)) = parse_single_instr(instrs, metadata, strict)?; log::info!( "Found potential probestack suffix: {:x} {:?}", addr, sub_instr ); if let Stmt::Binop( Binopcode::Sub, Value::Reg(Rsp, Size64), Value::Reg(Rsp, Size64), Value::Reg(Rax, Size64), ) = sub_instr[0] { return Ok((rest, (0, (addr, sub_instr)))); } if let Stmt::Binop( Binopcode::Sub, Value::Reg(Rsp, Size64), Value::Reg(Rsp, Size64), Value::Imm(_, _, imm), ) = sub_instr[0] { return Ok((rest, (imm - (probestack_arg as i64), (addr, sub_instr)))); } Err(ParseErr::Error(instrs)) } fn parse_probestack<'a>( instrs: BlockInstrs<'a>, metadata: &VwMetadata, strict: bool, ) -> IResult<'a, StmtResult> { let (rest, (probestack_arg, (addr, mov_instr))) = parse_probestack_arg(instrs, metadata, strict)?; log::info!("Found potential probestack: 0x{:x}", addr); let (rest, (_, call_instr)) = parse_probestack_call(rest, metadata, strict)?; log::info!("Found probestack call: 0x{:x}", addr); let (rest, ( stack_adjustment,(_, suffix_instr))) = parse_probestack_suffix(rest, metadata, strict, probestack_arg)?; log::info!("Completed probestack: 0x{:x}", addr); let mut stmts = Vec::new(); stmts.extend(mov_instr); stmts.push(Stmt::ProbeStack(probestack_arg)); if stack_adjustment != 0{ stmts.push(Stmt::Binop(Binopcode::Sub, Value::Reg(Rsp, Size64), Value::Reg(Rsp, Size64), mk_value_i64(stack_adjustment))); } Ok((rest, (addr, stmts))) } // returns (addr, operand(0), operand(1)) fn parse_bsf<'a>(instrs: BlockInstrs<'a>) -> IResult<'a, (Addr, Value, Value)> { if let Some(((addr, instr), rest)) = instrs.split_first() { if let Opcode::BSF = instr.opcode() { return Ok(( rest, ( *addr, convert_operand( instr.operand(0), get_operand_size(&instr.operand(0)).unwrap(), ), convert_operand( instr.operand(1), get_operand_size(&instr.operand(1)).unwrap(), ), ), )); } } Err(ParseErr::Incomplete) } // returns (addr, operand(0), operand(1)) fn parse_bsr<'a>(instrs: BlockInstrs<'a>) -> IResult<'a, (Addr, Value, Value)> { if let Some(((addr, instr), rest)) = instrs.split_first() { if let Opcode::BSR = instr.opcode() { return Ok(( rest, ( *addr, convert_operand( instr.operand(0), get_operand_size(&instr.operand(0)).unwrap(), ), convert_operand( instr.operand(1), get_operand_size(&instr.operand(1)).unwrap(), ), ), )); } } Err(ParseErr::Incomplete) } // returns src of the cmove (dst must be the same) // although it says bsf, it also handles bsr fn parse_cmovez<'a>(instrs: BlockInstrs<'a>, bsf_dst: &Value) -> IResult<'a, (Addr, Value)> { if let Some(((addr, instr), rest)) = instrs.split_first() { if let Opcode::CMOVZ = instr.opcode() { let mov_dst = convert_operand( instr.operand(0), get_operand_size(&instr.operand(0)).unwrap(), ); if let (Value::Reg(bsf_dst_reg, _), Value::Reg(mov_dst_reg, _)) = (bsf_dst, mov_dst) { if *bsf_dst_reg == mov_dst_reg { return Ok(( rest, ( *addr, convert_operand( instr.operand(1), get_operand_size(&instr.operand(1)).unwrap(), ), ), )); } } } } Err(ParseErr::Error(instrs)) } fn parse_bsf_cmove<'a>(instrs: BlockInstrs<'a>, metadata: &VwMetadata) -> IResult<'a, StmtResult> { let (rest, (addr, bsf_dst, bsf_src)) = parse_bsf(instrs)?; let (rest, (_addr, mov_src)) = parse_cmovez(rest, &bsf_dst)?; let mut stmts = Vec::new(); stmts.push(Stmt::Clear(Value::Reg(Zf, Size8), vec![bsf_src.clone()])); stmts.push(Stmt::Clear(bsf_dst, vec![bsf_src, mov_src])); Ok((rest, (addr, stmts))) } fn parse_bsr_cmove<'a>(instrs: BlockInstrs<'a>, metadata: &VwMetadata) -> IResult<'a, StmtResult> { let (rest, (addr, bsr_dst, bsr_src)) = parse_bsr(instrs)?; let (rest, (_addr, mov_src)) = parse_cmovez(rest, &bsr_dst)?; let mut stmts = Vec::new(); stmts.push(Stmt::Clear(Value::Reg(Zf, Size8), vec![bsr_src.clone()])); stmts.push(Stmt::Clear(bsr_dst, vec![bsr_src, mov_src])); Ok((rest, (addr, stmts))) } fn parse_single_instr<'a>( instrs: BlockInstrs<'a>, metadata: &VwMetadata, strict: bool, ) -> IResult<'a, StmtResult> { if let Some(((addr, instr), rest)) = instrs.split_first() { Ok((rest, (*addr, lift(instr, addr, metadata, strict)))) } else { Err(ParseErr::Incomplete) } } fn parse_instr<'a>( instrs: BlockInstrs<'a>, metadata: &VwMetadata, strict: bool, ) -> IResult<'a, StmtResult> { if let Ok((rest, stmt)) = parse_bsf_cmove(instrs, metadata) { Ok((rest, stmt)) } else if let Ok((rest, stmt)) = parse_bsr_cmove(instrs, metadata) { Ok((rest, stmt)) } else if let Ok((rest, stmt)) = parse_probestack(instrs, metadata, strict) { Ok((rest, stmt)) } else { parse_single_instr(instrs, metadata, strict) } } fn parse_instrs<'a>( instrs: BlockInstrs, metadata: &VwMetadata, strict: bool, ) -> Vec<(Addr, Vec<Stmt>)> { let mut block_ir: Vec<(Addr, Vec<Stmt>)> = Vec::new(); let mut rest = instrs; while let Ok((more, (addr, stmts))) = parse_instr(rest, metadata, strict) { rest = more; if stmts.len() == 1 { if let Stmt::Branch(Opcode::JMP, _) = stmts[0] { // Don't continue past an unconditional jump -- // Cranelift's new backend embeds constants in the // code stream at points (e.g. jump tables) and we // should not disassemble them as code. block_ir.push((addr, stmts)); break; } } log::info!("Lifted block: 0x{:x} {:?}", addr, stmts); block_ir.push((addr, stmts)); } block_ir } pub fn lift_cfg(module: &VwModule, cfg: &VW_CFG, strict: bool) -> IRMap { let mut irmap = IRMap::new(); let g = &cfg.graph; for block_addr in g.nodes() { let block = cfg.get_block(block_addr); let instrs_vec: Vec<(u64, X64Instruction)> = module .program .instructions_spanning(<AMD64 as Arch>::Decoder::default(), block.start, block.end) .collect(); let instrs = instrs_vec.as_slice(); let block_ir = parse_instrs(instrs, &module.metadata, strict); irmap.insert(block_addr, block_ir); } irmap } // TODO: baby version of nom, resolve crate incompatibilities later type IResult<'a, O> = Result<(BlockInstrs<'a>, O), ParseErr<BlockInstrs<'a>>>; type StmtResult = (Addr, Vec<Stmt>); type Addr = u64; enum ParseErr<E> { Incomplete, // input too short Error(E), // recoverable Failure(E), // unrecoverable } type BlockInstrs<'a> = &'a [(Addr, X64Instruction)]; <file_sep>use crate::{analyses, ir, lattices, loaders}; use analyses::{run_worklist, AbstractAnalyzer, AnalysisResult}; use ir::types::{Binopcode, IRMap, Stmt, Unopcode, ValSize, X86Regs}; use lattices::reachingdefslattice::{loc, singleton, LocIdx, ReachLattice}; use lattices::VarState; use loaders::types::VwMetadata; use yaxpeax_core::analyses::control_flow::VW_CFG; use ValSize::*; use X86Regs::*; //Top level function pub fn analyze_reaching_defs( cfg: &VW_CFG, irmap: &IRMap, _metadata: VwMetadata, ) -> AnalysisResult<ReachLattice> { run_worklist( cfg, irmap, &ReachingDefnAnalyzer { cfg: cfg.clone(), irmap: irmap.clone(), }, ) } pub struct ReachingDefnAnalyzer { pub cfg: VW_CFG, pub irmap: IRMap, } impl ReachingDefnAnalyzer { //1. get enclosing block addr //2. get result for that block start //3. run reaching def up to that point pub fn fetch_def( &self, result: &AnalysisResult<ReachLattice>, loc_idx: &LocIdx, ) -> ReachLattice { if self.cfg.blocks.contains_key(&loc_idx.addr) { return result.get(&loc_idx.addr).unwrap().clone(); } let block_addr = self.cfg.prev_block(loc_idx.addr).unwrap().start; let irblock = self.irmap.get(&block_addr).unwrap(); let mut def_state = result.get(&block_addr).unwrap().clone(); for (addr, instruction) in irblock.iter() { for (idx, ir_insn) in instruction.iter().enumerate() { if &loc_idx.addr == addr && (loc_idx.idx as usize) == idx { return def_state; } self.aexec( &mut def_state, ir_insn, &LocIdx { addr: *addr, idx: idx as u32, }, ); } } unimplemented!() } } impl AbstractAnalyzer<ReachLattice> for ReachingDefnAnalyzer { fn init_state(&self) -> ReachLattice { let mut s: ReachLattice = Default::default(); s.regs.set_reg(Rax, Size64, loc(0xdeadbeef, 0)); s.regs.set_reg(Rcx, Size64, loc(0xdeadbeef, 1)); s.regs.set_reg(Rdx, Size64, loc(0xdeadbeef, 2)); s.regs.set_reg(Rbx, Size64, loc(0xdeadbeef, 3)); s.regs.set_reg(Rbp, Size64, loc(0xdeadbeef, 4)); s.regs.set_reg(Rsi, Size64, loc(0xdeadbeef, 5)); s.regs.set_reg(Rdi, Size64, loc(0xdeadbeef, 6)); s.regs.set_reg(R8, Size64, loc(0xdeadbeef, 7)); s.regs.set_reg(R9, Size64, loc(0xdeadbeef, 8)); s.regs.set_reg(R10, Size64, loc(0xdeadbeef, 9)); s.regs.set_reg(R11, Size64, loc(0xdeadbeef, 10)); s.regs.set_reg(R12, Size64, loc(0xdeadbeef, 11)); s.regs.set_reg(R13, Size64, loc(0xdeadbeef, 12)); s.regs.set_reg(R14, Size64, loc(0xdeadbeef, 13)); s.regs.set_reg(R15, Size64, loc(0xdeadbeef, 14)); s.stack.update(0x8, loc(0xdeadbeef, 15), 4); s.stack.update(0x10, loc(0xdeadbeef, 16), 4); s.stack.update(0x18, loc(0xdeadbeef, 17), 4); s.stack.update(0x20, loc(0xdeadbeef, 18), 4); s.stack.update(0x28, loc(0xdeadbeef, 18), 4); s } fn aexec(&self, in_state: &mut ReachLattice, ir_instr: &Stmt, loc_idx: &LocIdx) -> () { match ir_instr { Stmt::Clear(dst, _) => in_state.set(dst, singleton(loc_idx.clone())), Stmt::Unop(Unopcode::Mov, dst, src) | Stmt::Unop(Unopcode::Movsx, dst, src) => { if let Some(v) = in_state.get(src) { if v.defs.is_empty() { in_state.set(dst, singleton(loc_idx.clone())); } else { in_state.set(dst, v); } } else { in_state.set(dst, singleton(loc_idx.clone())); } //in_state.set(dst, singleton(loc_idx.clone())) } Stmt::Binop(Binopcode::Cmp, _, _, _) => { //Ignore compare } Stmt::Binop(Binopcode::Test, _, _, _) => { //Ignore test } Stmt::Binop(opcode, dst, src1, src2) => { in_state.adjust_stack_offset(opcode, dst, src1, src2); in_state.set(dst, singleton(loc_idx.clone())) } Stmt::Call(_) => { in_state.regs.set_reg(Rax, Size64, loc(loc_idx.addr, 0)); in_state.regs.set_reg(Rcx, Size64, loc(loc_idx.addr, 1)); in_state.regs.set_reg(Rdx, Size64, loc(loc_idx.addr, 2)); in_state.regs.set_reg(Rbx, Size64, loc(loc_idx.addr, 3)); in_state.regs.set_reg(Rbp, Size64, loc(loc_idx.addr, 4)); in_state.regs.set_reg(Rsi, Size64, loc(loc_idx.addr, 5)); in_state.regs.set_reg(Rdi, Size64, loc(loc_idx.addr, 6)); in_state.regs.set_reg(R8, Size64, loc(loc_idx.addr, 7)); in_state.regs.set_reg(R9, Size64, loc(loc_idx.addr, 8)); in_state.regs.set_reg(R10, Size64, loc(loc_idx.addr, 9)); in_state.regs.set_reg(R11, Size64, loc(loc_idx.addr, 10)); in_state.regs.set_reg(R12, Size64, loc(loc_idx.addr, 11)); in_state.regs.set_reg(R13, Size64, loc(loc_idx.addr, 12)); in_state.regs.set_reg(R14, Size64, loc(loc_idx.addr, 13)); in_state.regs.set_reg(R15, Size64, loc(loc_idx.addr, 14)); } _ => (), } } } <file_sep>[package] name = "veriwasm" version = "0.1.1" authors = ["enjhnsn2 <<EMAIL>>"] edition = "2018" license-file = "LICENSE" readme = "README.md" repository = "https://github.com/PLSysSec/veriwasm" description = "A safety verifier for native-compiled WebAssembly code" keywords = ["verification", "WebAssembly", "security", "static-analysis", "binary-analysis"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] # This commit (`f9dc5c2...`) is the `vw-tweaks` branch. yaxpeax-core = { git = "https://github.com/mkolosick/yaxpeax-core/", branch = "veriwasm" } yaxpeax-arch = { version = "0.0.4", features = ["use-serde"] } yaxpeax-x86 = { git = "https://github.com/mkolosick/yaxpeax-x86/", branch = "veriwasm" } "petgraph" = "0.4.13" clap = "2.33.3" object = "0.21.0" byteorder = "1.3.4" colored = "2.0.0" serde_json = "1.0.59" log = "0.4.14" env_logger = "0.8.4" goblin = "0.4.1" itertools = "0.10.1" # This should be an optional compile target wasmtime = "0.28.0" #wasmtime = {path = "../wasmtime/crates/wasmtime"} #wasmtime-jit = { path = "../wasmtime/crates/jit"} #wasmtime-jit = "0.28.0" #lucet-module = { path = "../lucet_sandbox_compiler/lucet-module", version = "0.1.1", package="lucet-module-wasmsbx" } lucet-module = "0.5.1" #capstone = { version = "0.8.0" } # log = "*" # env_logger = "*" # goblin = "*" # wasmtime = { path = "../wasmtime/crates/wasmtime" } # wasmtime-jit = { path = "../wasmtime/crates/jit" } # lucet-module = { path = "../lucet_sandbox_compiler/lucet-module", version = "0.1.1", package="lucet-module-wasmsbx" } # # lucet-module = { git = "https://github.com/bytecodealliance/lucet.git" } elfkit = "0.0.4" <file_sep>mod aarch64; mod cfg; pub mod types; pub mod utils; mod x64; pub use self::cfg::fully_resolved_cfg; pub use self::x64::lift_cfg; use crate::ir::types::Stmt; use crate::loaders::types::VwArch; use crate::VwMetadata; use core::str::FromStr; pub trait Liftable { fn lift( &self, instr: &yaxpeax_x86::long_mode::Instruction, addr: &u64, metadata: &VwMetadata, strict: bool, ) -> Vec<Stmt>; } // TODO: make static dispatch impl Liftable for VwArch { fn lift( &self, instr: &yaxpeax_x86::long_mode::Instruction, addr: &u64, metadata: &VwMetadata, strict: bool, ) -> Vec<Stmt> { match self { VwArch::X64 => x64::lift(instr, addr, metadata, strict), VwArch::Aarch64 => aarch64::lift(instr, addr, metadata, strict), } } } <file_sep>mod call_analyzer; mod heap_analyzer; mod jump_analyzer; pub mod locals_analyzer; pub mod reaching_defs; mod stack_analyzer; use crate::ir::types::{Binopcode, IRBlock, IRMap, Stmt, Unopcode, Value}; use crate::lattices::reachingdefslattice::LocIdx; use crate::lattices::{Lattice, VarState}; use std::collections::{HashMap, VecDeque}; use yaxpeax_core::analyses::control_flow::VW_CFG; /* Public API */ pub use self::call_analyzer::CallAnalyzer; pub use self::heap_analyzer::HeapAnalyzer; pub use self::jump_analyzer::SwitchAnalyzer; pub use self::stack_analyzer::StackAnalyzer; pub type AnalysisResult<T> = HashMap<u64, T>; pub trait AbstractAnalyzer<State: Lattice + VarState + Clone> { fn init_state(&self) -> State { Default::default() } fn process_branch( &self, _irmap: &IRMap, in_state: &State, succ_addrs: &Vec<u64>, _addr: &u64, ) -> Vec<(u64, State)> { succ_addrs .into_iter() .map(|addr| (addr.clone(), in_state.clone())) .collect() } fn aexec_unop( &self, in_state: &mut State, _opcode: &Unopcode, dst: &Value, _src: &Value, _loc_idx: &LocIdx, ) -> () { in_state.set_to_bot(dst) } fn aexec_binop( &self, in_state: &mut State, opcode: &Binopcode, dst: &Value, _src1: &Value, _src2: &Value, _loc_idx: &LocIdx, ) -> () { match opcode { Binopcode::Cmp => (), Binopcode::Test => (), _ => in_state.set_to_bot(dst), } } fn aexec(&self, in_state: &mut State, ir_instr: &Stmt, loc_idx: &LocIdx) -> () { match ir_instr { Stmt::Clear(dst, _srcs) => in_state.set_to_bot(dst), Stmt::Unop(opcode, dst, src) => self.aexec_unop(in_state, opcode, &dst, &src, loc_idx), Stmt::Binop(opcode, dst, src1, src2) => { self.aexec_binop(in_state, opcode, dst, src1, src2, loc_idx); in_state.adjust_stack_offset(opcode, dst, src1, src2) } Stmt::Call(_) => in_state.on_call(), _ => (), } } fn analyze_block(&self, state: &State, irblock: &IRBlock) -> State { let mut new_state = state.clone(); for (addr, instruction) in irblock.iter() { for (idx, ir_insn) in instruction.iter().enumerate() { log::debug!( "Analyzing insn @ 0x{:x}: {:?}: state = {:?}", addr, ir_insn, new_state ); self.aexec( &mut new_state, ir_insn, &LocIdx { addr: *addr, idx: idx as u32, }, ); } } new_state } } fn align_succ_addrs(addr: u64, succ_addrs: Vec<u64>) -> Vec<u64> { if succ_addrs.len() != 2 { return succ_addrs; } let a1 = succ_addrs[0]; let a2 = succ_addrs[1]; if a1 < addr { return vec![a2, a1]; } if a2 < addr { return vec![a1, a2]; } if a1 < a2 { return vec![a1, a2]; } if a1 >= a2 { return vec![a2, a1]; } panic!("Unreachable"); } pub fn run_worklist<T: AbstractAnalyzer<State>, State: VarState + Lattice + Clone>( cfg: &VW_CFG, irmap: &IRMap, analyzer: &T, ) -> AnalysisResult<State> { let mut statemap: HashMap<u64, State> = HashMap::new(); let mut worklist: VecDeque<u64> = VecDeque::new(); worklist.push_back(cfg.entrypoint); statemap.insert(cfg.entrypoint, analyzer.init_state()); while !worklist.is_empty() { let addr = worklist.pop_front().unwrap(); let irblock = irmap.get(&addr).unwrap(); let state = statemap.get(&addr).unwrap(); let new_state = analyzer.analyze_block(state, irblock); let succ_addrs_unaligned: Vec<u64> = cfg.graph.neighbors(addr).collect(); let succ_addrs: Vec<u64> = align_succ_addrs(addr, succ_addrs_unaligned); log::debug!("Processing Block: 0x{:x} -> {:?}", addr, succ_addrs); for (succ_addr, branch_state) in analyzer.process_branch(irmap, &new_state, &succ_addrs, &addr) { let has_change = if statemap.contains_key(&succ_addr) { let old_state = statemap.get(&succ_addr).unwrap(); let merged_state = old_state.meet(&branch_state, &LocIdx { addr: addr, idx: 0 }); if merged_state > *old_state { log::debug!("{:?} {:?}", merged_state, old_state); panic!("Meet monoticity error"); } let has_change = *old_state != merged_state; log::debug!( "At block 0x{:x}: merged input {:?}", succ_addr, merged_state ); statemap.insert(succ_addr, merged_state); has_change } else { log::debug!("At block 0x{:x}: new input {:?}", succ_addr, branch_state); statemap.insert(succ_addr, branch_state); true }; if has_change && !worklist.contains(&succ_addr) { worklist.push_back(succ_addr); } } } statemap } <file_sep>use crate::{analyses, checkers, ir, lattices}; use analyses::{AbstractAnalyzer, AnalysisResult, CallAnalyzer}; use checkers::Checker; use ir::types::{IRMap, MemArg, MemArgs, Stmt, ValSize, Value}; use lattices::calllattice::{CallCheckLattice, CallCheckValue}; use lattices::davlattice::DAV; use lattices::reachingdefslattice::LocIdx; use CallCheckValue::*; use ValSize::*; pub struct CallChecker<'a> { irmap: &'a IRMap, analyzer: &'a CallAnalyzer, funcs: &'a Vec<u64>, plt: &'a (u64, u64), } pub fn check_calls( result: AnalysisResult<CallCheckLattice>, irmap: &IRMap, analyzer: &CallAnalyzer, funcs: &Vec<u64>, plt: &(u64, u64), ) -> bool { CallChecker { irmap, analyzer, funcs, plt, } .check(result) } impl Checker<CallCheckLattice> for CallChecker<'_> { fn check(&self, result: AnalysisResult<CallCheckLattice>) -> bool { self.check_state_at_statements(result) } fn irmap(&self) -> &IRMap { self.irmap } fn aexec(&self, state: &mut CallCheckLattice, ir_stmt: &Stmt, loc: &LocIdx) { self.analyzer.aexec(state, ir_stmt, loc) } fn check_statement(&self, state: &CallCheckLattice, ir_stmt: &Stmt, loc_idx: &LocIdx) -> bool { //1. Check that all indirect calls use resolved function pointer if let Stmt::Call(v) = ir_stmt { if !self.check_indirect_call(state, v, loc_idx) { println!("0x{:x} Failure Case: Indirect Call {:?}", loc_idx.addr, v); return false; } } // 2. Check that lookup is using resolved DAV if let Stmt::Unop(_, _, Value::Mem(_, memargs)) = ir_stmt { if !self.check_calltable_lookup(state, memargs) { println!( "0x{:x} Failure Case: Lookup Call: {:?}", loc_idx.addr, memargs ); print_mem_access(state, memargs); return false; } } true } } impl CallChecker<'_> { fn check_indirect_call( &self, state: &CallCheckLattice, target: &Value, loc_idx: &LocIdx, ) -> bool { match target { Value::Reg(regnum, size) => { if let Some(FnPtr(c)) = state.regs.get_reg(*regnum, *size).v { return true; } else { log::debug!("{:?}", state.regs.get_reg(*regnum, *size).v) } } Value::Mem(_, _) => return false, Value::Imm(_, _, imm) => { let target = (*imm + (loc_idx.addr as i64) + 5) as u64; let (plt_start, plt_end) = self.plt; return self.funcs.contains(&target) || ((target >= *plt_start) && (target < *plt_end)); } Value::RIPConst => { return true; } } false } fn check_calltable_lookup(&self, state: &CallCheckLattice, memargs: &MemArgs) -> bool { log::debug!("Call Table Lookup: {:?}", memargs); match memargs { MemArgs::Mem3Args( MemArg::Reg(regnum1, Size64), MemArg::Reg(regnum2, Size64), MemArg::Imm(_, _, 8), ) => match ( state.regs.get_reg(*regnum1, Size64).v, state.regs.get_reg(*regnum2, Size64).v, ) { (Some(GuestTableBase), Some(PtrOffset(DAV::Checked))) => return true, (Some(PtrOffset(DAV::Checked)), Some(GuestTableBase)) => return true, (Some(TypedPtrOffset(_)), Some(GuestTableBase)) => return true, (Some(GuestTableBase), Some(TypedPtrOffset(_))) => return true, (_x, Some(GuestTableBase)) | (Some(GuestTableBase), _x) => return false, (_x, _y) => return true, // not a calltable lookup }, _ => return true, //not a calltable lookup? } } } pub fn memarg_repr(state: &CallCheckLattice, memarg: &MemArg) -> String { match memarg { MemArg::Reg(regnum, size) => { format!("r{:?}: {:?}", regnum, state.regs.get_reg(*regnum, *size).v) } MemArg::Imm(_, _, x) => format!("{:?}", x), } } pub fn print_mem_access(state: &CallCheckLattice, memargs: &MemArgs) { match memargs { MemArgs::Mem1Arg(x) => log::debug!("mem[{:?}]", memarg_repr(state, x)), MemArgs::Mem2Args(x, y) => log::debug!( "mem[{:?} + {:?}]", memarg_repr(state, x), memarg_repr(state, y) ), MemArgs::Mem3Args(x, y, z) => log::debug!( "mem[{:?} + {:?} + {:?}]", memarg_repr(state, x), memarg_repr(state, y), memarg_repr(state, z) ), MemArgs::MemScale(x, y, z) => log::debug!( "mem[{:?} + {:?} * {:?}]", memarg_repr(state, x), memarg_repr(state, y), memarg_repr(state, z) ), } } <file_sep># VeriWasm: SFI safety for native-compiled Wasm This repository contains all the code and data necessary for building VeriWasm and reproducing the results presented in our NDSS'21 paper [Доверя́й, но проверя́й: SFI safety for native-compiled Wasm](http://cseweb.ucsd.edu/~dstefan/pubs/johnson:2021:veriwasm.pdf). ## Abstract WebAssembly (Wasm) is a platform-independent bytecode that offers both good performance and runtime isolation. To implement isolation, the compiler inserts safety checks when it compiles Wasm to native machine code. While this approach is cheap, it also requires trust in the compiler's correctness—trust that the compiler has inserted each necessary check, correctly formed, in each proper place. Unfortunately, subtle bugs in the Wasm compiler can break—and have broken—isolation guarantees. To address this problem, we propose verifying memory isolation of Wasm binaries post-compilation. We implement this approach in VeriWasm, a static offline verifier for native x86-64 binaries compiled from Wasm; we prove the verifier's soundness, and find that it can detect bugs with no false positives. Finally, we describe our deployment of VeriWasm at Fastly. ## Build VeriWasm You first need to install several dependencies: - git - Rust - nasm (to compile test cases) - gcc (to compile test cases) - python3 (for scripts) Once you have these, you can build VeriWasm: ```bash git submodule update --init --recursive cargo build --release ``` ## Run VeriWasm To run VeriWasm on your own binaries, you just need to point it to the module you want to check: ```bash cargo run --release -- -i <input path> ``` Usage: ``` VeriWasm 0.1.0 Validates safety of native Wasm code USAGE: veriwasm [FLAGS] [OPTIONS] -i <module path> FLAGS: -h, --help Prints help information -q, --quiet -V, --version Prints version information OPTIONS: -j, --jobs <jobs> Number of parallel threads (default 1) -i <module path> path to native Wasm module to validate -o, --output <stats output path> Path to output stats file ``` ## Reproducing evaluation results This repo contains all the infrastructure necessary for reproducing the results described in the paper. Once you build VeriWasm you can run our tests and and performance benchmarks. ### Running the evaluation suite To verify all the binaries described in the paper, except the SPEC CPU 2006 binaries (they are proprietary) and the Fastly production binaries, run: ```bash git clone https://github.com/PLSysSec/veriwasm_public_data.git cd veriwasm_public_data && sh setup.sh && sh build_negative_tests.sh && cd .. cargo test --release ``` To get get the performance statistics for the binaries, run: ```bash make compute_stats python3 graph_stats.py stats/* ``` ### Fuzzing VeriWasm To fuzz VeriWasm, you'll need to install `cmake` and then build the fuzzers (and the tooling they rely on): ```bash make build_fuzzers ``` Then, either run the [Csmith](https://embed.cs.utah.edu/csmith/)-based fuzzer: ```bash cd veriwasm_fuzzing make csmith_fuzz ``` or the Wasm-based fuzzer: ```bash cd veriwasm_fuzzing make wasm_fuzz ``` By default, `make` will use four cores; you may want to change this. ## Related repos - **Binaries used for evaluation**: The binaries we verified as part of our evaluation are [here](https://github.com/PLSysSec/veriwasm_public_data.git). - **Fuzzing scripts**: The scripts we used to fuzz VeriWasm are [here](https://github.com/PLSysSec/veriwasm_fuzzing). - **Mechanized proofs**: The proofs from our paper are [here](https://github.com/PLSysSec/veriwasm-verification). <file_sep>use crate::{analyses, ir, lattices, loaders}; use analyses::reaching_defs::ReachingDefnAnalyzer; use analyses::{AbstractAnalyzer, AnalysisResult}; use ir::types::{ Binopcode, IRBlock, IRMap, MemArg, MemArgs, Stmt, Unopcode, ValSize, Value, X86Regs, }; use ir::utils::{extract_stack_offset, is_stack_access}; use lattices::calllattice::{CallCheckLattice, CallCheckValue, CallCheckValueLattice}; use lattices::davlattice::DAV; use lattices::reachingdefslattice::{LocIdx, ReachLattice}; use lattices::{VarSlot, VarState}; use loaders::types::VwMetadata; use std::convert::TryFrom; use std::default::Default; use yaxpeax_core::analyses::control_flow::VW_CFG; use yaxpeax_x86::long_mode::Opcode; use CallCheckValue::*; use ValSize::*; use X86Regs::*; pub struct CallAnalyzer { pub metadata: VwMetadata, pub reaching_defs: AnalysisResult<ReachLattice>, pub reaching_analyzer: ReachingDefnAnalyzer, pub funcs: Vec<u64>, pub irmap: IRMap, pub cfg: VW_CFG, } impl CallAnalyzer { //1. get enclosing block addr //2. get result for that block start //3. get result for specific addr pub fn fetch_result( &self, result: &AnalysisResult<CallCheckLattice>, loc_idx: &LocIdx, ) -> CallCheckLattice { if self.cfg.blocks.contains_key(&loc_idx.addr) { return result.get(&loc_idx.addr).unwrap().clone(); } let block_addr = self.cfg.prev_block(loc_idx.addr).unwrap().start; let irblock = self.irmap.get(&block_addr).unwrap(); let mut a_state = result.get(&block_addr).unwrap().clone(); for (addr, instruction) in irblock.iter() { for (idx, ir_insn) in instruction.iter().enumerate() { if &loc_idx.addr == addr && (loc_idx.idx as usize) == idx { return a_state; } self.aexec( &mut a_state, ir_insn, &LocIdx { addr: *addr, idx: idx as u32, }, ); } } unimplemented!() } pub fn get_fn_ptr_type( &self, result: &AnalysisResult<CallCheckLattice>, loc_idx: &LocIdx, src: &Value, ) -> Option<u32> { let def_state = self.fetch_result(result, loc_idx); if let Value::Reg(regnum, size) = src { let aval = def_state.regs.get_reg(*regnum, *size); if let Some(FnPtr(ty)) = aval.v { return Some(ty); } } None } } impl AbstractAnalyzer<CallCheckLattice> for CallAnalyzer { fn analyze_block(&self, state: &CallCheckLattice, irblock: &IRBlock) -> CallCheckLattice { let mut new_state = state.clone(); for (addr, instruction) in irblock.iter() { for (idx, ir_insn) in instruction.iter().enumerate() { log::debug!( "Call analyzer: stmt at 0x{:x}: {:?} with state {:?}", addr, ir_insn, new_state ); self.aexec( &mut new_state, ir_insn, &LocIdx { addr: *addr, idx: idx as u32, }, ); } } new_state } fn aexec_unop( &self, in_state: &mut CallCheckLattice, _opcode: &Unopcode, dst: &Value, src: &Value, _loc_idx: &LocIdx, ) -> () { in_state.set(dst, self.aeval_unop(in_state, src)) } fn aexec_binop( &self, in_state: &mut CallCheckLattice, opcode: &Binopcode, dst: &Value, src1: &Value, src2: &Value, loc_idx: &LocIdx, ) -> () { match (opcode, src1, src2) { (Binopcode::Cmp, Value::Reg(regnum1, size1), Value::Reg(regnum2, size2)) => { if let Some(TableSize) = in_state.regs.get_reg(*regnum2, *size2).v { in_state.regs.set_reg( Zf, Size64, CallCheckValueLattice::new(CheckFlag(0, *regnum1)), ) } if let Some(TableSize) = in_state.regs.get_reg(*regnum1, *size1).v { in_state.regs.set_reg( Zf, Size64, CallCheckValueLattice::new(CheckFlag(0, *regnum2)), ) } } (Binopcode::Cmp, Value::Reg(regnum, size), Value::Imm(_, _, c)) => { if let Some(TypeOf(r)) = in_state.regs.get_reg(*regnum, *size).v { log::debug!( "{:x}: Settng zf = TypeCheckFlag({:?}, {:?}) from {:?}", loc_idx.addr, X86Regs::try_from(r).unwrap(), c, X86Regs::try_from(*regnum).unwrap() ); in_state.regs.set_reg( Zf, Size64, CallCheckValueLattice::new(TypeCheckFlag(r, *c as u32)), ) } } (Binopcode::Test, _, _) => (), _ => in_state.set(dst, self.aeval_binop(in_state, opcode, src1, src2, loc_idx)), } } fn process_branch( &self, irmap: &IRMap, in_state: &CallCheckLattice, succ_addrs: &Vec<u64>, addr: &u64, ) -> Vec<(u64, CallCheckLattice)> { log::info!("Processing branch: 0x{:x}", addr); if succ_addrs.len() == 2 { let br_stmt = irmap .get(addr) .expect("no instruction at given address") .last() .expect("no instructions in block") .1 .last() .expect("no IR instructions for last disassembled instruction"); let br_opcode = match br_stmt { Stmt::Branch(op, _) => Some(op), _ => None, }; let (is_unsigned_cmp, is_je, flip) = match br_opcode { Some(Opcode::JB) => (true, false, false), Some(Opcode::JNB) => (true, false, true), Some(Opcode::JZ) => (false, true, false), _ => (false, false, false), }; log::debug!( "{:x}: is_unsigned_cmp {} is_je {} flip {}", addr, is_unsigned_cmp, is_je, flip ); let mut not_branch_state = in_state.clone(); let mut branch_state = in_state.clone(); if is_unsigned_cmp { if let Some(CheckFlag(_, regnum)) = not_branch_state.regs.get_reg(Zf, Size64).v { log::debug!("branch at 0x{:x}: CheckFlag for reg {:?}", addr, regnum); let new_val = CallCheckValueLattice { v: Some(CheckedVal), }; branch_state.regs.set_reg(regnum, Size64, new_val.clone()); //1. propagate checked values let defs_state = self.reaching_defs.get(addr).unwrap(); let ir_block = irmap.get(addr).unwrap(); let defs_state = self.reaching_analyzer.analyze_block(defs_state, ir_block); let checked_defs = defs_state.regs.get_reg(regnum, Size64); for idx in X86Regs::iter() { let reg_def = defs_state.regs.get_reg(idx, Size64); if (!reg_def.is_empty()) && (reg_def == checked_defs) { branch_state.regs.set_reg(idx, Size64, new_val.clone()); } } for (stack_offset, stack_slot) in defs_state.stack.map.iter() { if !checked_defs.is_empty() && (stack_slot.value == checked_defs) { let vv = VarSlot { size: stack_slot.size, value: new_val.clone(), }; branch_state.stack.map.insert(*stack_offset, vv); } } //3. resolve ptr thunks in registers let checked_ptr = CallCheckValueLattice { v: Some(PtrOffset(DAV::Checked)), }; for idx in X86Regs::iter() { let reg_val = branch_state.regs.get_reg(idx, Size64); if let Some(PtrOffset(DAV::Unchecked(reg_def))) = reg_val.v { if checked_defs.is_empty() && reg_def == checked_defs { branch_state.regs.set_reg(idx, Size64, checked_ptr.clone()); } } } //4. resolve ptr thunks in stack slots -- for (stack_offset, stack_slot) in not_branch_state.stack.map.iter() { let stack_val = stack_slot.value.v.clone(); if let Some(PtrOffset(DAV::Unchecked(stack_def))) = stack_val { if !checked_defs.is_empty() && (stack_def == checked_defs) { let v = VarSlot { size: stack_slot.size, value: checked_ptr.clone(), }; branch_state.stack.map.insert(*stack_offset, v); } } } } } else if is_je { //Handle TypeCheck if let Some(TypeCheckFlag(regnum, c)) = not_branch_state.regs.get_reg(Zf, Size64).v { log::debug!( "branch at 0x{:x}: TypeCheckFlag for reg {:?}. Making TypedPtrOffset({:?})", addr, regnum, c ); let new_val = CallCheckValueLattice { v: Some(TypedPtrOffset(c)), }; branch_state.regs.set_reg(regnum, Size64, new_val.clone()); } } branch_state.regs.set_reg(Zf, Size64, Default::default()); not_branch_state .regs .set_reg(Zf, Size64, Default::default()); log::debug!( " -> branch_state @ 0x{:x} = {:?}", succ_addrs[1], branch_state ); log::debug!( " -> not_branch_state @ 0x{:x} = {:?}", succ_addrs[0], not_branch_state ); if flip { vec![ (succ_addrs[0].clone(), branch_state), (succ_addrs[1].clone(), not_branch_state), ] } else { vec![ (succ_addrs[0].clone(), not_branch_state), (succ_addrs[1].clone(), branch_state), ] } } else { succ_addrs .into_iter() .map(|addr| (addr.clone(), in_state.clone())) .collect() } } } // mem[LucetTableBase + 8] pub fn is_table_size(in_state: &CallCheckLattice, memargs: &MemArgs) -> bool { if let MemArgs::Mem2Args(MemArg::Reg(regnum1, size), MemArg::Imm(_, _, 8)) = memargs { if let Some(LucetTablesBase) = in_state.regs.get_reg(*regnum1, *size).v { return true; } } false } pub fn is_fn_ptr(in_state: &CallCheckLattice, memargs: &MemArgs) -> Option<u32> { if let MemArgs::Mem3Args( MemArg::Reg(regnum1, size1), MemArg::Reg(regnum2, size2), MemArg::Imm(_, _, immval), ) = memargs { match ( in_state.regs.get_reg(*regnum1, *size1).v, in_state.regs.get_reg(*regnum2, *size2).v, immval, ) { (Some(GuestTableBase), Some(TypedPtrOffset(c)), 8) => return Some(c), (Some(TypedPtrOffset(c)), Some(GuestTableBase), 8) => return Some(c), _ => return None, } } None } // returns none if not a typeof op // returns Some(regnum) if result is type of regnum pub fn is_typeof(in_state: &CallCheckLattice, memargs: &MemArgs) -> Option<X86Regs> { if let MemArgs::Mem2Args(MemArg::Reg(regnum1, size1), MemArg::Reg(regnum2, size2)) = memargs { match ( in_state.regs.get_reg(*regnum1, *size1).v, in_state.regs.get_reg(*regnum2, *size2).v, ) { (Some(GuestTableBase), Some(PtrOffset(DAV::Checked))) => return Some(*regnum2), (Some(PtrOffset(DAV::Checked)), Some(GuestTableBase)) => return Some(*regnum1), _ => return None, } } None } impl CallAnalyzer { fn is_func_start(&self, addr: u64) -> bool { self.funcs.contains(&addr) } pub fn aeval_unop(&self, in_state: &CallCheckLattice, value: &Value) -> CallCheckValueLattice { match value { Value::Mem(memsize, memargs) => { if is_table_size(in_state, memargs) { return CallCheckValueLattice { v: Some(TableSize) }; } else if is_fn_ptr(in_state, memargs).is_some() { let ty = is_fn_ptr(in_state, memargs).unwrap(); log::debug!("Making FnPtr({:?})", ty); return CallCheckValueLattice { v: Some(FnPtr(ty)) }; } else if is_typeof(in_state, memargs).is_some() { let reg = is_typeof(in_state, memargs).unwrap(); log::debug!( "Typeof operation: args: {:?} => r{:?} is base", memargs, reg ); return CallCheckValueLattice { v: Some(TypeOf(reg)), }; } else if is_stack_access(value) { let offset = extract_stack_offset(memargs); return in_state.stack.get(offset, memsize.into_bytes()); } } Value::Reg(regnum, size) => return in_state.regs.get_reg(*regnum, *size), Value::Imm(_, _, immval) => { if (*immval as u64) == self.metadata.guest_table_0 { return CallCheckValueLattice { v: Some(GuestTableBase), }; } else if (*immval as u64) == self.metadata.lucet_tables { return CallCheckValueLattice { v: Some(LucetTablesBase), }; } else if self.is_func_start(*immval as u64) { return CallCheckValueLattice { v: Some(FnPtr(1337)), //dummy value, TODO remove }; } } Value::RIPConst => { // The backend uses rip-relative data to embed constant function pointers. return CallCheckValueLattice { v: Some(FnPtr(1337)), //Dummy value, TODO remove }; } } Default::default() } //checked_val << 4 pub fn aeval_binop( &self, in_state: &CallCheckLattice, opcode: &Binopcode, src1: &Value, src2: &Value, loc_idx: &LocIdx, ) -> CallCheckValueLattice { if let Binopcode::Shl = opcode { if let (Value::Reg(regnum1, size1), Value::Imm(_, _, 4)) = (src1, src2) { if let Some(CheckedVal) = in_state.regs.get_reg(*regnum1, *size1).v { return CallCheckValueLattice { v: Some(PtrOffset(DAV::Checked)), }; } else { let def_state = self .reaching_analyzer .fetch_def(&self.reaching_defs, loc_idx); let reg_def = def_state.regs.get_reg(*regnum1, *size1); return CallCheckValueLattice { v: Some(PtrOffset(DAV::Unchecked(reg_def))), }; } } } Default::default() } } <file_sep>import json import sys import math import matplotlib import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import MultipleLocator #matplotlib.use('tkagg') def median(lst): n = len(lst) s = sorted(lst) return (sum(s[n//2-1:n//2+1])/2.0, s[n//2])[n % 2] if n else None def graph_blocks_vs_time(dataset): for data in dataset.values(): times = [x[1] for x in data] block_counts = [x[2] + x[3] + x[4] + x[5] for x in data] plt.plot(block_counts, times, 'o') plt.show() #raise NotImplementedError def graph_funcs_vs_time(dataset): func_count = [] total_times = [] for data in dataset.values(): func_count.append(len(data)) total_time = sum([x[1] for x in data]) total_times.append(total_time) plt.plot(func_count, total_times, 'o') plt.show() def get_data(filenames): dataset = {} for filename in filenames: with open(filename) as f: data = json.load(f) dataset[filename] = data return dataset def get_aggregate_data(dataset): aggregate_data = [] #print(len(dataset.keys())) for name,data in dataset.items(): name = name.split('/')[-1].split(".")[0] times = [x[2] + x[3] + x[4] + x[5] + x[6] for x in data] average_t = sum(times) / len(times) median_t = median(times) max_t = max(times) min_t = min(times) total_t = sum(times) num_funcs = len(times) N = len(times) // 100 print("top 1% = ", N, " functions out of", len(times)) top_n = sorted(data, key=lambda x: (x[2] + x[3] + x[4] + x[5] + x[6]), reverse = True)[:N] top_percent = sum([x[2] + x[3] + x[4] + x[5] + x[6] for x in top_n]) / total_t top_percent_medians = median([x[1] for x in top_n]) cfg_percent = sum([x[2] for x in data]) / total_t stack_percent = sum([x[3] for x in data]) / total_t heap_percent = sum([x[4] for x in data]) / total_t call_percent = sum([x[5] for x in data]) / total_t locals_percent = sum([x[6] for x in data]) / total_t print(top_n, top_percent) median_blocks = median([x[1] for x in data]) aggregate_data.append( (name,average_t,median_t,max_t,min_t,num_funcs,total_t,top_percent, cfg_percent, stack_percent, heap_percent, call_percent, locals_percent, median_blocks, top_percent_medians)) return aggregate_data def generate_summary_table(aggregate_data): names_row = " &" average_row = "Average Function Validation Time (s) & " median_row = "Median Function Validation Time (s) & " max_row = "Max Function Validation Time (s) & " min_row = "Min Function Validation Time (s) & " num_funcs_row = "\\# Functions in Module & " total_row = "Total Validation Time (s) & " #for name,average_t,median_t,max_t,min_t in aggregate_data: names_row += " & ".join([str(d[0]) for d in aggregate_data]) + "\\\\" average_row += " & ".join([str(round(d[1],2)) for d in aggregate_data]) + "\\\\" median_row += " & ".join([str(round(d[2],2)) for d in aggregate_data]) + "\\\\" max_row += " & ".join([str(round(d[3],2)) for d in aggregate_data]) + "\\\\" min_row += " & ".join([str(round(d[4],2)) for d in aggregate_data]) + "\\\\" num_funcs_row += " & ".join([str(round(d[5],2)) for d in aggregate_data]) + "\\\\" total_row += " & ".join([str(round(d[6],2)) for d in aggregate_data]) + "\\\\" table_str = "\n".join([names_row, average_row, median_row, max_row, min_row, num_funcs_row, total_row]) + "\n" return table_str #print out some quick statistics def summarise_data(aggregate_data): medians = [round(d[2],2) for d in aggregate_data] maxes = [round(d[3],2) for d in aggregate_data] num_funcs = [round(d[5],2) for d in aggregate_data] times = [round(d[6],2) for d in aggregate_data] one_percent = [d[7] for d in aggregate_data] cfg_percent = [d[8] for d in aggregate_data] stack_percent = [d[9] for d in aggregate_data] heap_percent = [d[10] for d in aggregate_data] call_percent = [d[11] for d in aggregate_data] locals_percent = [d[12] for d in aggregate_data] median_blocks = [d[13] for d in aggregate_data] top_percent_median_blocks = [d[14] for d in aggregate_data] #print(averages) #medians = [round(d[2],2) for d in aggregate_data] #print(medians) print(f"Number of binaries = {len(times)}") print(f"Median function validation time: {median(medians)}") num_above_min = len([time for time in maxes if time > 60.0]) print(f"Number of binariess with a function that took > 1 minute to validate: {num_above_min}") print(f"Top 1% of functions account for (on average) {sum(one_percent) / len(one_percent) * 100}% of total execution time") print(f"{sum(cfg_percent) / len(one_percent) * 100}% of verification time spent making CFGs") print(f"{sum(stack_percent) / len(stack_percent) * 100}% of verification time spent checking stack") print(f"{sum(heap_percent) / len(heap_percent) * 100}% of verification time spent checking heap") print(f"{sum(call_percent) / len(call_percent) * 100}% of verification time spent checking calls") print(f"{sum(locals_percent) / len(locals_percent) * 100}% of verification time spent checking locals") print(f"Average Time = {sum(times) / len(times)}") #print(f"Average Max function Time = {sum(maxes) / len(maxes)}") print(f"Min Validation Time: {min(times)}") print(f"Max Validation Time: {max(times)}") print(f"Median Validation Time = {median(times)}") print(f"Min Functions: {min(num_funcs)}") print(f"Max Functions: {max(num_funcs)}") print(f"Median Functions: {median(num_funcs)}") print(f"Median of Median of blocks in modules: {median(median_blocks)}") print(f"Median of Median of blocks in top 1% of functions in modules: {median(top_percent_median_blocks)}") fig, ax = plt.subplots() ax.xaxis.set_minor_locator(MultipleLocator(5)) plt.xlabel('Module Validation Time (s)') plt.ylabel('# of Modules') plt.hist(times, bins= math.ceil((max(times) - min(times))/5) ) print("Histogram Created") plt.savefig("performance.pdf") print("Histogram Saved") def run(filenames): dataset = get_data(filenames) #graph_blocks_vs_time(dataset) #graph_funcs_vs_time(dataset) aggregate_data = get_aggregate_data(dataset) summarise_data(aggregate_data) table = generate_summary_table(aggregate_data) print(table) def main(): filename = sys.argv[1] print(sys.argv) filenames = sys.argv[1:] run(filenames) if __name__ == "__main__": main() <file_sep>use crate::ir::types::X86Regs; use crate::lattices::reachingdefslattice::LocIdx; use crate::lattices::Lattice; pub use crate::lattices::{VarState, VariableState}; use std::cmp::Ordering; use std::convert::TryFrom; use Ordering::*; use X86Regs::*; #[derive(PartialEq, Clone, Eq, Debug, Copy, Hash)] pub enum SlotVal { Uninit, Init, UninitCalleeReg(X86Regs), } impl PartialOrd for SlotVal { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { match (self, other) { (Uninit, Uninit) => Some(Equal), (Uninit, _) => Some(Less), (_, Uninit) => Some(Greater), (Init, Init) => Some(Equal), (Init, _) => Some(Greater), (_, Init) => Some(Less), (UninitCalleeReg(r1), UninitCalleeReg(r2)) => { if r1 == r1 { Some(Equal) } else { None } } } } } use self::SlotVal::*; impl Default for SlotVal { fn default() -> Self { Uninit } } impl Lattice for SlotVal { fn meet(&self, other: &Self, _loc: &LocIdx) -> Self { match (self, other) { (Init, Init) => Init, (Uninit, _) => Uninit, (_, Uninit) => Uninit, (Init, UninitCalleeReg(_)) => Uninit, (UninitCalleeReg(_), Init) => Uninit, (UninitCalleeReg(r1), UninitCalleeReg(r2)) => { if r1 == r2 { UninitCalleeReg(*r1) } else { Uninit } } } } } pub type LocalsLattice = VariableState<SlotVal>; <file_sep>mod lucet; pub mod types; pub mod utils; mod wasmtime; use crate::loaders; use crate::runner::Config; use loaders::lucet::*; use loaders::types::*; use loaders::wasmtime::*; use yaxpeax_core::memory::repr::process::ModuleData; // TODO: this should be static dispatch, not dynamic dispatch // not performance critical, but static dispatch is more rusty pub fn load_program(config: &Config) -> VwModule { match config.executable_type { ExecutableType::Lucet => load_lucet_program(config), ExecutableType::Wasmtime => load_wasmtime_program(config), } } pub trait Loadable { fn is_valid_func_name(&self, name: &String) -> bool; fn get_func_signatures(&self, program: &ModuleData) -> VwFuncInfo; fn get_plt_funcs(&self, binpath: &str) -> Vec<(u64, String)>; } impl Loadable for ExecutableType { fn is_valid_func_name(&self, name: &String) -> bool { match self { ExecutableType::Lucet => is_valid_lucet_func_name(name), ExecutableType::Wasmtime => is_valid_wasmtime_func_name(name), } } fn get_func_signatures(&self, program: &ModuleData) -> VwFuncInfo { match self { ExecutableType::Lucet => get_lucet_func_signatures(program), ExecutableType::Wasmtime => get_wasmtime_func_signatures(program), } } fn get_plt_funcs(&self, binpath: &str) -> Vec<(u64, String)> { match self { ExecutableType::Lucet => lucet_get_plt_funcs(binpath), ExecutableType::Wasmtime => wasmtime_get_plt_funcs(binpath), } } } <file_sep>use crate::{analyses, checkers, ir, lattices, loaders}; use crate::lattices::calllattice::CallCheckLattice; use crate::lattices::reachingdefslattice::ReachingDefnLattice; use crate::lattices::VariableState; use crate::{IRMap, VwMetadata, VW_CFG}; use analyses::locals_analyzer::LocalsAnalyzer; use analyses::reaching_defs::{analyze_reaching_defs, ReachingDefnAnalyzer}; use analyses::{run_worklist, AnalysisResult}; use analyses::{CallAnalyzer, HeapAnalyzer, StackAnalyzer}; use checkers::locals_checker::check_locals; use checkers::{check_calls, check_heap, check_stack}; use ir::fully_resolved_cfg; use ir::types::FunType; use ir::utils::has_indirect_calls; use loaders::load_program; use loaders::types::{ExecutableType, VwArch, VwFuncInfo}; use loaders::utils::get_data; use loaders::utils::to_system_v; use std::collections::HashMap; use std::convert::TryFrom; use std::iter::FromIterator; // use loaders::get_plt_funcs; use loaders::Loadable; use serde_json; use std::fs; use std::panic; use std::time::Instant; use yaxpeax_core::analyses::control_flow::check_cfg_integrity; #[derive(Debug)] pub struct PassConfig { pub stack: bool, pub linear_mem: bool, pub call: bool, pub zero_cost: bool, } pub struct Config { pub module_path: String, pub _num_jobs: u32, pub output_path: String, pub has_output: bool, pub only_func: Option<String>, pub executable_type: ExecutableType, pub active_passes: PassConfig, pub arch: VwArch, } pub fn run_locals( reaching_defs: AnalysisResult<VariableState<ReachingDefnLattice>>, call_analysis: AnalysisResult<CallCheckLattice>, plt_bounds: (u64, u64), all_addrs_map: &HashMap<u64, String>, // index into func_signatures.signatures func_signatures: &VwFuncInfo, func_name: &String, cfg: &VW_CFG, irmap: &IRMap, metadata: &VwMetadata, valid_funcs: &Vec<u64>, ) -> bool { let fun_type = func_signatures .indexes .get(func_name) .and_then(|index| { func_signatures .signatures .get(usize::try_from(*index).unwrap()) }) .map(to_system_v) .unwrap_or(FunType { args: Vec::new(), ret: None, }); let call_analyzer = CallAnalyzer { metadata: metadata.clone(), reaching_defs: reaching_defs.clone(), reaching_analyzer: ReachingDefnAnalyzer { cfg: cfg.clone(), irmap: irmap.clone(), }, funcs: valid_funcs.clone(), irmap: irmap.clone(), cfg: cfg.clone(), }; let locals_analyzer = LocalsAnalyzer { fun_type, plt_bounds, symbol_table: func_signatures, name_addr_map: all_addrs_map, call_analysis, call_analyzer, }; let locals_result = run_worklist(&cfg, &irmap, &locals_analyzer); let locals_safe = check_locals(locals_result, &irmap, &locals_analyzer); locals_safe } fn run_stack(cfg: &VW_CFG, irmap: &IRMap) -> bool { let stack_analyzer = StackAnalyzer {}; let stack_result = run_worklist(&cfg, &irmap, &stack_analyzer); let stack_safe = check_stack(stack_result, &irmap, &stack_analyzer); stack_safe } fn run_heap( cfg: &VW_CFG, irmap: &IRMap, metadata: &VwMetadata, all_addrs_map: &HashMap<u64, String>, ) -> bool { let heap_analyzer = HeapAnalyzer { metadata: metadata.clone(), }; let heap_result = run_worklist(&cfg, &irmap, &heap_analyzer); let heap_safe = check_heap(heap_result, &irmap, &heap_analyzer, &all_addrs_map); heap_safe } fn run_calls( cfg: &VW_CFG, irmap: &IRMap, metadata: &VwMetadata, valid_funcs: &Vec<u64>, plt: (u64, u64), ) -> ( bool, AnalysisResult<CallCheckLattice>, AnalysisResult<VariableState<ReachingDefnLattice>>, ) { let reaching_defs = analyze_reaching_defs(&cfg, &irmap, metadata.clone()); let call_analyzer = CallAnalyzer { metadata: metadata.clone(), reaching_defs: reaching_defs.clone(), reaching_analyzer: ReachingDefnAnalyzer { cfg: cfg.clone(), irmap: irmap.clone(), }, funcs: valid_funcs.clone(), irmap: irmap.clone(), cfg: cfg.clone(), }; let call_result = run_worklist(&cfg, &irmap, &call_analyzer); let call_safe = check_calls( call_result.clone(), &irmap, &call_analyzer, &valid_funcs, &plt, ); (call_safe, call_result, reaching_defs) } pub fn run(config: Config) { let strict = false; // should probably be a commandline option let module = load_program(&config); let (x86_64_data, func_addrs, plt, mut all_addrs) = get_data(&module.program, &config.executable_type); // let plt_funcs = config.executable_type.get_plt_funcs(&config.module_path); // all_addrs.extend(plt_funcs); let mut func_counter = 0; let mut info: Vec<(std::string::String, usize, f64, f64, f64, f64, f64)> = vec![]; let valid_funcs: Vec<u64> = func_addrs.clone().iter().map(|x| x.0).collect(); // let func_signatures = config.executable_type.get_func_signatures(&module.program); let all_addrs_map = HashMap::from_iter(all_addrs.clone()); for (addr, func_name) in func_addrs { if config.only_func.is_some() && func_name != config.only_func.as_ref().unwrap().as_str() { continue; } println!("Generating CFG for {:?}", func_name); let start = Instant::now(); let (cfg, irmap) = fully_resolved_cfg(&module, &x86_64_data.contexts, addr, strict); func_counter += 1; println!("Analyzing 0x{:x?}: {:?}", addr, func_name); check_cfg_integrity(&cfg.blocks, &cfg.graph); let stack_start = Instant::now(); if config.active_passes.stack { println!("Checking Stack Safety"); let stack_safe = run_stack(&cfg, &irmap); if !stack_safe { panic!("Not Stack Safe"); } } let heap_start = Instant::now(); if config.active_passes.linear_mem { println!("Checking Heap Safety"); let heap_safe = run_heap(&cfg, &irmap, &module.metadata, &all_addrs_map); if !heap_safe { panic!("Not Heap Safe"); } } let call_start = Instant::now(); if config.active_passes.call { // if config.active_passes.linear_mem { println!("Checking Call Safety"); let (call_safe, indirect_calls_result, reaching_defs) = run_calls(&cfg, &irmap, &module.metadata, &valid_funcs, plt); if !call_safe { panic!("Not Call Safe"); } // println!("Checking Locals Safety"); // let locals_safe = run_locals( // reaching_defs, // indirect_calls_result, // plt, // &all_addrs_map, // &func_signatures, // &func_name, // &cfg, // &irmap, // &module.metadata, // &valid_funcs, // ); // if !locals_safe { // panic!("Not Locals Safe"); // } } let locals_start = Instant::now(); //alwyas 0 right now, locals time grouped with calls let end = Instant::now(); info.push(( func_name.to_string(), cfg.blocks.len(), (stack_start - start).as_secs_f64(), (heap_start - stack_start).as_secs_f64(), (call_start - heap_start).as_secs_f64(), (locals_start - call_start).as_secs_f64(), // TODO: proper timing (end - locals_start).as_secs_f64(), )); println!( "Verified {:?} at {:?} blocks. CFG: {:?}s Stack: {:?}s Heap: {:?}s Calls: {:?}s locals {:?}s", func_name, cfg.blocks.len(), (stack_start - start).as_secs_f64(), (heap_start - stack_start).as_secs_f64(), (call_start - heap_start).as_secs_f64(), (locals_start - call_start).as_secs_f64(), (end - locals_start).as_secs_f64(), // TODO: proper timing ); } if config.has_output { let data = serde_json::to_string(&info).unwrap(); println!("Dumping Stats to {}", config.output_path); fs::write(config.output_path, data).expect("Unable to write file"); } let mut total_cfg_time = 0.0; let mut total_stack_time = 0.0; let mut total_heap_time = 0.0; let mut total_call_time = 0.0; let mut total_locals_time = 0.0; for (_, _, cfg_time, stack_time, heap_time, call_time, locals_time) in &info { total_cfg_time += cfg_time; total_stack_time += stack_time; total_heap_time += heap_time; total_call_time += call_time; total_locals_time += locals_time; } println!("Verified {:?} functions", func_counter); println!( "Total time = {:?}s CFG: {:?} Stack: {:?}s Heap: {:?}s Call: {:?}s Locals {:?}s", total_cfg_time + total_stack_time + total_heap_time + total_call_time + total_locals_time, total_cfg_time, total_stack_time, total_heap_time, total_call_time, total_locals_time, ); println!("Done!"); } <file_sep>use crate::{analyses, ir, lattices}; use analyses::AnalysisResult; use ir::types::{IRMap, Stmt}; use lattices::reachingdefslattice::LocIdx; use lattices::Lattice; use itertools::Itertools; mod call_checker; mod heap_checker; mod jump_resolver; pub mod locals_checker; mod stack_checker; /* Public API for checker submodule */ pub use self::call_checker::check_calls; pub use self::heap_checker::check_heap; pub use self::jump_resolver::resolve_jumps; pub use self::stack_checker::check_stack; pub trait Checker<State: Lattice + Clone> { fn check(&self, result: AnalysisResult<State>) -> bool; fn irmap(&self) -> &IRMap; fn aexec(&self, state: &mut State, ir_stmt: &Stmt, loc: &LocIdx); fn check_state_at_statements(&self, result: AnalysisResult<State>) -> bool { // for (block_addr, mut state) in result { // log::debug!( // "Checking block 0x{:x} with start state {:?}", // block_addr, // state // ); for block_addr in result.keys().sorted() { let mut state = result[block_addr].clone(); log::debug!( "Checking block 0x{:x} with start state {:?}", block_addr, state ); for (addr, ir_stmts) in self.irmap().get(&block_addr).unwrap() { for (idx, ir_stmt) in ir_stmts.iter().enumerate() { log::debug!( "Checking stmt at 0x{:x}: {:?} with start state {:?}", addr, ir_stmt, state ); let loc_idx = LocIdx { addr: *addr, idx: idx as u32, }; if !self.check_statement(&state, ir_stmt, &loc_idx) { return false; } self.aexec(&mut state, ir_stmt, &loc_idx); } } } true } fn check_statement(&self, state: &State, ir_stmt: &Stmt, loc_idx: &LocIdx) -> bool; } <file_sep>use crate::{analyses, ir, lattices}; use analyses::{AbstractAnalyzer, AnalysisResult, SwitchAnalyzer}; use ir::types::{IRMap, Stmt, Value}; use lattices::reachingdefslattice::LocIdx; use lattices::switchlattice::{SwitchLattice, SwitchValue, SwitchValueLattice}; use std::collections::HashMap; use yaxpeax_core::memory::repr::process::ModuleData; use yaxpeax_core::memory::MemoryRepr; fn load_target(program: &ModuleData, addr: u64) -> i64 { let b0 = program.read(addr).unwrap() as u32; let b1 = (program.read(addr + 1).unwrap() as u32) << 8; let b2 = (program.read(addr + 2).unwrap() as u32) << 16; let b3 = (program.read(addr + 3).unwrap() as u32) << 24; (b0 + b1 + b2 + b3) as i64 } fn extract_jmp_targets(program: &ModuleData, aval: &SwitchValueLattice) -> Vec<i64> { let mut targets: Vec<i64> = Vec::new(); match aval.v { Some(SwitchValue::JmpTarget(base, upper_bound)) => { for idx in 0..upper_bound { let addr = base + idx * 4; let target = load_target(program, addr.into()); let resolved_target = ((base as i32) + (target as i32)) as i64; targets.push(resolved_target); } } _ => panic!("Jump Targets Broken, target = {:?}", aval.v), } targets } // addr -> vec of targets pub fn resolve_jumps( program: &ModuleData, result: AnalysisResult<SwitchLattice>, irmap: &IRMap, analyzer: &SwitchAnalyzer, ) -> HashMap<u64, Vec<i64>> { let mut switch_targets: HashMap<u64, Vec<i64>> = HashMap::new(); for (block_addr, mut state) in result.clone() { for (addr, ir_stmts) in irmap.get(&block_addr).unwrap() { for (idx, ir_stmt) in ir_stmts.iter().enumerate() { analyzer.aexec( &mut state, ir_stmt, &LocIdx { addr: *addr, idx: idx as u32, }, ); } } } for (block_addr, mut state) in result { for (addr, ir_stmts) in irmap.get(&block_addr).unwrap() { for (idx, ir_stmt) in ir_stmts.iter().enumerate() { match ir_stmt { Stmt::Branch(_, Value::Reg(regnum, regsize)) => { let aval = state.regs.get_reg(*regnum, *regsize); let targets = extract_jmp_targets(program, &aval); switch_targets.insert(*addr, targets); } Stmt::Branch(_, Value::Mem(_, _)) => { panic!("Illegal Jump!"); } _ => (), } analyzer.aexec( &mut state, ir_stmt, &LocIdx { addr: *addr, idx: idx as u32, }, ); } } } switch_targets } <file_sep>use crate::{loaders, runner}; use byteorder::{BigEndian, LittleEndian, ReadBytesExt}; use elfkit::relocation::RelocationType; use elfkit::{symbol, types, DynamicContent, Elf, SectionContent}; use goblin::Object; use loaders::types::{VwFuncInfo, VwMetadata, VwModule}; use loaders::utils::*; use loaders::utils::{deconstruct_elf, get_symbol_addr}; use lucet_module; use std::collections::HashMap; use std::fs::File; use std::fs::OpenOptions; use std::io::Cursor; use std::io::{Read, Seek, SeekFrom}; use std::mem; use std::path::Path; use std::string::String; use yaxpeax_core::memory::repr::process::{ModuleData, Segment}; use yaxpeax_core::memory::repr::FileRepr; pub fn lucet_get_plt_funcs(binpath: &str) -> Vec<(u64, String)> { //Extract relocation symbols let mut in_file = OpenOptions::new().read(true).open(binpath).unwrap(); let mut elf = Elf::from_reader(&mut in_file).unwrap(); elf.load_all().unwrap(); // Parse relocs to get mapping from target to name let mut target_to_name = HashMap::new(); for section in &elf.sections { match section.content { SectionContent::Relocations(ref relocs) => { for reloc in relocs { elf.sections .get(section.header.link as usize) .and_then(|sec| sec.content.as_symbols()) .and_then(|symbols| symbols.get(reloc.sym as usize)) .and_then(|symbol| { if symbol.name.len() > 0 { target_to_name.insert(reloc.addr, symbol.name.clone()); // println!("{:x} {:} ", reloc.addr, symbol.name); Some(()) } else { None } }) .unwrap_or_else(|| { // print!("{: <20.20} ", reloc.sym); }); } } _ => (), } } // Parse PLT to get mapping from address to target let mut addr_to_target = HashMap::new(); let plt_section = elf.sections.iter().find(|sec| sec.name == ".plt"); // if plt_section.is_none(){ // return Vec::new(); // }; let plt_section = plt_section.unwrap(); let plt_start = plt_section.header.addr; if let SectionContent::Raw(buf) = &plt_section.content { let mut rdr = Cursor::new(buf); let mut idx: usize = 0; while idx < buf.len() { rdr.seek(SeekFrom::Current(2)).unwrap(); let offset = rdr.read_i32::<LittleEndian>().unwrap(); rdr.seek(SeekFrom::Current(10)).unwrap(); let addr = plt_start + (idx as u64); println!("{:x} {:x} {:x}", plt_start, idx, offset); let target = plt_start + (idx as u64) + (offset as u64) + 6; addr_to_target.insert(addr, target); idx += 16; } } else { panic!("No plt section?"); } // println!("===== Addr to Target ======="); // for (addr,target) in &addr_to_target{ // println!("{:x} {:x}", addr, target); // } // println!("===== Target to Name ======="); // for (target, name) in &target_to_name{ // println!("{:x} {:}", target, name); // } let mut plt_funcs: Vec<(u64, String)> = Vec::new(); for (addr, target) in &addr_to_target { if target_to_name.contains_key(target) { let name = target_to_name[target].clone(); plt_funcs.push((*addr, name)); } } // println!("plt_funcs: {:?}", plt_funcs); // unimplemented!(); plt_funcs } // pub fn load_lucet_program(binpath: &str) -> ModuleData { // let program = yaxpeax_core::memory::reader::load_from_path(Path::new(binpath)).unwrap(); // if let FileRepr::Executable(program) = program { // program // } else { // panic!("function:{} is not a valid path", binpath) // } // } // pub fn load_lucet_program(config: &runner::Config) -> VwModule { // let program = // yaxpeax_core::memory::reader::load_from_path(Path::new(&config.module_path)).unwrap(); // if let FileRepr::Executable(program) = program { // let metadata = load_lucet_metadata(&program); // VwModule { // program, // metadata, // format: config.executable_type, // arch: config.arch, // } // } else { // panic!("function:{} is not a valid path", config.module_path) // } // } pub fn load_lucet_metadata(program: &ModuleData) -> VwMetadata { let (_, sections, entrypoint, imports, exports, symbols) = deconstruct_elf(program); let guest_table_0 = get_symbol_addr(symbols, "guest_table_0").unwrap(); let lucet_tables = get_symbol_addr(symbols, "lucet_tables").unwrap(); let lucet_probestack = get_symbol_addr(symbols, "lucet_probestack").unwrap(); VwMetadata { guest_table_0: guest_table_0, lucet_tables: lucet_tables, lucet_probestack: lucet_probestack, } } pub fn load_lucet_program(config: &runner::Config) -> VwModule { let program = yaxpeax_core::memory::reader::load_from_path(Path::new(&config.module_path)).unwrap(); if let FileRepr::Executable(program) = program { let metadata = load_lucet_metadata(&program); VwModule { program, metadata, format: config.executable_type, arch: config.arch, } } else { panic!("function:{} is not a valid path", config.module_path) } } // func name is valid if: // 1. is not probestack pub fn is_valid_lucet_func_name(name: &String) -> bool { if name == "lucet_probestack" { return false; } true } pub fn load_lucet_module_data(program: &ModuleData) -> lucet_module::ModuleData { let (program_header, sections, entrypoint, imports, exports, symbols) = deconstruct_elf(program); let module_start: usize = get_symbol_addr(symbols, "lucet_module").unwrap() as usize; let module_size: usize = mem::size_of::<lucet_module::SerializedModule>(); let buffer = read_module_buffer(program, module_start, module_size).unwrap(); let mut rdr = Cursor::new(buffer); let module_data_ptr = rdr.read_u64::<LittleEndian>().unwrap(); let module_data_len = rdr.read_u64::<LittleEndian>().unwrap(); let module_data_buffer = read_module_buffer(program, module_data_ptr as usize, module_data_len as usize).unwrap(); lucet_module::ModuleData::deserialize(module_data_buffer) .expect("ModuleData deserialization failure") } fn segment_for(program: &ModuleData, addr: usize) -> Option<&Segment> { for segment in program.segments.iter() { if addr >= segment.start && addr < (segment.start + segment.data.len()) { return Some(segment); } } None } // Finds and returns the data corresponding [addr..addr+size] pub fn read_module_buffer(program: &ModuleData, addr: usize, size: usize) -> Option<&[u8]> { let segment = segment_for(program, addr)?; let read_start = addr - segment.start; let read_end = read_start + size; Some(&segment.data[read_start..read_end]) } pub fn get_lucet_func_signatures(program: &ModuleData) -> VwFuncInfo { let lucet_module_data = load_lucet_module_data(program); for signature in lucet_module_data.signatures() { println!("{:?}", signature); } let mut indexes = HashMap::new(); for func_info in lucet_module_data.function_info() { println!("{:?}", func_info); indexes.insert( func_info.name.unwrap().to_string(), func_info.signature.as_u32(), ); } // Vec::new() VwFuncInfo { signatures: lucet_module_data.signatures().to_vec(), indexes, } } <file_sep>use crate::analyses::{AbstractAnalyzer, AnalysisResult, HeapAnalyzer}; use crate::checkers::Checker; use crate::ir::types::{IRMap, MemArg, MemArgs, Stmt, ValSize, Value, X86Regs}; use crate::ir::utils::{is_mem_access, is_stack_access}; use crate::lattices::heaplattice::{HeapLattice, HeapValue}; use crate::lattices::reachingdefslattice::LocIdx; use crate::loaders::utils::is_libcall; use std::collections::HashMap; use HeapValue::*; use ValSize::*; use X86Regs::*; pub struct HeapChecker<'a> { irmap: &'a IRMap, analyzer: &'a HeapAnalyzer, name_addr_map: &'a HashMap<u64, String>, } pub fn check_heap( result: AnalysisResult<HeapLattice>, irmap: &IRMap, analyzer: &HeapAnalyzer, name_addr_map: &HashMap<u64, String>, ) -> bool { HeapChecker { irmap: irmap, analyzer: analyzer, name_addr_map: name_addr_map, } .check(result) } fn memarg_is_frame(memarg: &MemArg) -> bool { if let MemArg::Reg(Rbp, size) = memarg { assert_eq!(*size, Size64); true } else { false } } fn is_frame_access(v: &Value) -> bool { if let Value::Mem(_, memargs) = v { // Accept only operands of the form `[rbp + OFFSET]` where `OFFSET` is an integer. In // Cranelift-generated code from Wasm, there are never arrays or variable-length data in // the function frame, so there should never be a computed address (e.g., `[rbp + 4*eax + // OFFSET]`). match memargs { MemArgs::Mem1Arg(memarg) => memarg_is_frame(memarg), MemArgs::Mem2Args(memarg1, memarg2) => { memarg_is_frame(memarg1) && matches!(memarg2, MemArg::Imm(..)) } _ => false, } } else { false } } impl Checker<HeapLattice> for HeapChecker<'_> { fn check(&self, result: AnalysisResult<HeapLattice>) -> bool { self.check_state_at_statements(result) } fn irmap(&self) -> &IRMap { self.irmap } fn aexec(&self, state: &mut HeapLattice, ir_stmt: &Stmt, loc: &LocIdx) { self.analyzer.aexec(state, ir_stmt, loc) } fn check_statement(&self, state: &HeapLattice, ir_stmt: &Stmt, loc_idx: &LocIdx) -> bool { match ir_stmt { //1. Check that at each call rdi = HeapBase Stmt::Call(v) => match state.regs.get_reg(Rdi, Size64).v { Some(HeapBase) => (), _ => { () // removed for lucet integration // if let Value::Imm(_, _, dst) = v { // let target = (*dst + (loc_idx.addr as i64) + 5) as u64; // let name = self.name_addr_map.get(&target).unwrap(); // if !is_libcall(name) { // log::debug!("0x{:x}: Call failure", loc_idx.addr); // return false; // } // } else { // log::debug!("0x{:x}: Call failure", loc_idx.addr); // return false; // } } }, //2. Check that all load and store are safe Stmt::Unop(_, dst, src) => { if is_mem_access(dst) && !self.check_mem_access(state, dst, loc_idx) { return false; } //stack read: probestack <= stackgrowth + c < 8K if is_mem_access(src) && !self.check_mem_access(state, src, loc_idx) { return false; } } Stmt::Binop(_, dst, src1, src2) => { if is_mem_access(dst) && !self.check_mem_access(state, dst, loc_idx) { return false; } if is_mem_access(src1) && !self.check_mem_access(state, src1, loc_idx) { return false; } if is_mem_access(src2) && !self.check_mem_access(state, src2, loc_idx) { return false; } } Stmt::Clear(dst, srcs) => { if is_mem_access(dst) && !self.check_mem_access(state, dst, loc_idx) { return false; } for src in srcs { if is_mem_access(src) && !self.check_mem_access(state, src, loc_idx) { return false; } } } _ => (), } true } } impl HeapChecker<'_> { fn check_global_access(&self, state: &HeapLattice, access: &Value) -> bool { if let Value::Mem(_, memargs) = access { match memargs { MemArgs::Mem1Arg(MemArg::Reg(regnum, Size64)) => { if let Some(GlobalsBase) = state.regs.get_reg(*regnum, Size64).v { return true; } } MemArgs::Mem2Args( MemArg::Reg(regnum, Size64), MemArg::Imm(_, _, globals_offset), ) => { if let Some(GlobalsBase) = state.regs.get_reg(*regnum, Size64).v { return *globals_offset <= 4096; } } _ => return false, } } false } fn check_ripconst_access(&self, state: &HeapLattice, access: &Value) -> bool { if let Value::Mem(_, memargs) = access { match memargs { // `RIPConst` represents a trusted value laoded from .rodata or .data; any access involving // such a pointer is trusted. // // An offset from the base, even with a computed value, // is acceptable here: // // - If we are checking offline, in a mode where we have access // to symbols/relocations, we will specially recognize table // accesses and they will not reach here. // // - On the other hand, when we check online, as part of the // compilation and one function at a time without access to // relocations, we accept this approximation to the trusted // base: we trust any memory access based at such a // constant/global-variable-produced address. MemArgs::Mem1Arg(MemArg::Reg(regnum, Size64)) | MemArgs::Mem2Args(MemArg::Reg(regnum, Size64), _) | MemArgs::Mem3Args(MemArg::Reg(regnum, Size64), _, _) | MemArgs::MemScale(MemArg::Reg(regnum, Size64), _, _) => { if let Some(RIPConst) = state.regs.get_reg(*regnum, Size64).v { return true; } } _ => {} } } false } fn check_heap_access(&self, state: &HeapLattice, access: &Value) -> bool { if let Value::Mem(_, memargs) = access { match memargs { // if only arg is heapbase or heapaddr MemArgs::Mem1Arg(MemArg::Reg(regnum, Size64)) => { if let Some(HeapBase) = state.regs.get_reg(*regnum, Size64).v { return true; } if let Some(HeapAddr) = state.regs.get_reg(*regnum, Size64).v { return true; } } // if arg1 is heapbase and arg2 is bounded || // if arg1 is heapaddr and arg2 is constant offset MemArgs::Mem2Args(MemArg::Reg(regnum, Size64), memarg2) => { if let Some(HeapBase) = state.regs.get_reg(*regnum, Size64).v { match memarg2 { MemArg::Reg(regnum2, size2) => { if let Some(Bounded4GB) = state.regs.get_reg(*regnum2, *size2).v { return true; } } MemArg::Imm(_, _, v) => return *v >= -0x1000 && *v <= 0xffffffff, } } if let Some(HeapAddr) = state.regs.get_reg(*regnum, Size64).v { match memarg2 { MemArg::Imm(_, _, v) => return *v >= -0x1000 && *v <= 0xffffffff, _ => {} } } } // if arg1 is heapbase and arg2 and arg3 are bounded || // if arg1 is bounded and arg1 and arg3 are bounded MemArgs::Mem3Args(MemArg::Reg(regnum, Size64), memarg2, memarg3) | MemArgs::Mem3Args(memarg2, MemArg::Reg(regnum, Size64), memarg3) => { if let Some(HeapBase) = state.regs.get_reg(*regnum, Size64).v { match (memarg2, memarg3) { (MemArg::Reg(regnum2, size2), MemArg::Imm(_, _, v)) | (MemArg::Imm(_, _, v), MemArg::Reg(regnum2, size2)) => { if let Some(Bounded4GB) = state.regs.get_reg(*regnum2, *size2).v { return *v <= 0xffffffff; } } (MemArg::Reg(regnum2, size2), MemArg::Reg(regnum3, size3)) => { if let (Some(Bounded4GB), Some(Bounded4GB)) = ( state.regs.get_reg(*regnum2, *size2).v, state.regs.get_reg(*regnum3, *size3).v, ) { return true; } } _ => (), } } } _ => return false, } } false } fn check_metadata_access(&self, state: &HeapLattice, access: &Value) -> bool { if let Value::Mem(_size, memargs) = access { match memargs { //Case 1: mem[globals_base] MemArgs::Mem1Arg(MemArg::Reg(regnum, Size64)) => { if let Some(GlobalsBase) = state.regs.get_reg(*regnum, Size64).v { return true; } } //Case 2: mem[lucet_tables + 8] MemArgs::Mem2Args(MemArg::Reg(regnum, Size64), MemArg::Imm(_, _, 8)) => { if let Some(LucetTables) = state.regs.get_reg(*regnum, Size64).v { return true; } } MemArgs::Mem2Args(MemArg::Reg(regnum1, Size64), MemArg::Reg(regnum2, Size64)) => { if let Some(GuestTable0) = state.regs.get_reg(*regnum1, Size64).v { return true; } if let Some(GuestTable0) = state.regs.get_reg(*regnum2, Size64).v { return true; } } MemArgs::Mem3Args( MemArg::Reg(regnum1, Size64), MemArg::Reg(regnum2, Size64), MemArg::Imm(_, _, 8), ) => { match ( state.regs.get_reg(*regnum1, Size64).v, state.regs.get_reg(*regnum2, Size64).v, ) { (Some(GuestTable0), _) => return true, (_, Some(GuestTable0)) => return true, _ => (), } } _ => return false, } } false } fn check_jump_table_access(&self, _state: &HeapLattice, access: &Value) -> bool { if let Value::Mem(_size, memargs) = access { match memargs { MemArgs::MemScale(_, _, MemArg::Imm(_, _, 4)) => return true, _ => return false, } } false } fn check_mem_access(&self, state: &HeapLattice, access: &Value, loc_idx: &LocIdx) -> bool { // Case 1: its a stack access if is_stack_access(access) { return true; } // Case 2: it is a frame slot (RBP-based) access if is_frame_access(access) { return true; } // Case 3: it is an access based at a constant loaded from // program data. We trust the compiler knows what it's doing // in such a case. This could also be a globals or table // access if we are validating in-process without relocation // info. if self.check_ripconst_access(state, access) { return true; } // Case 4: its a heap access if self.check_heap_access(state, access) { return true; }; // Case 5: its a metadata access if self.check_metadata_access(state, access) { return true; }; // Case 6: its a globals access if self.check_global_access(state, access) { return true; }; // Case 7: Jump table access if self.check_jump_table_access(state, access) { return true; }; // Case 8: its unknown log::debug!("None of the memory accesses at 0x{:x}", loc_idx.addr); print_mem_access(state, access); return false; } } pub fn memarg_repr(state: &HeapLattice, memarg: &MemArg) -> String { match memarg { MemArg::Reg(regnum, size) => { format!("{:?}: {:?}", regnum, state.regs.get_reg(*regnum, *size).v) } MemArg::Imm(_, _, x) => format!("{:?}", x), } } pub fn print_mem_access(state: &HeapLattice, access: &Value) { if let Value::Mem(_, memargs) = access { match memargs { MemArgs::Mem1Arg(x) => log::debug!("mem[{:?}]", memarg_repr(state, x)), MemArgs::Mem2Args(x, y) => log::debug!( "mem[{:?} + {:?}]", memarg_repr(state, x), memarg_repr(state, y) ), MemArgs::Mem3Args(x, y, z) => log::debug!( "mem[{:?} + {:?} + {:?}]", memarg_repr(state, x), memarg_repr(state, y), memarg_repr(state, z) ), MemArgs::MemScale(x, y, z) => log::debug!( "mem[{:?} + {:?} * {:?}]", memarg_repr(state, x), memarg_repr(state, y), memarg_repr(state, z) ), } } } <file_sep>use crate::ir::types::Stmt; use crate::{analyses, ir, lattices, loaders}; use analyses::{AbstractAnalyzer, AnalysisResult}; use ir::types::{Binopcode, MemArg, MemArgs, Unopcode, ValSize, Value, X86Regs}; use ir::utils::{extract_stack_offset, is_stack_access}; use lattices::heaplattice::{HeapLattice, HeapValue, HeapValueLattice}; use lattices::reachingdefslattice::LocIdx; use lattices::{ConstLattice, VarState}; use loaders::types::VwMetadata; use std::default::Default; use HeapValue::*; use ValSize::*; use X86Regs::*; pub struct HeapAnalyzer { pub metadata: VwMetadata, } impl AbstractAnalyzer<HeapLattice> for HeapAnalyzer { fn init_state(&self) -> HeapLattice { let mut result: HeapLattice = Default::default(); result .regs .set_reg(Rdi, Size64, HeapValueLattice::new(HeapBase)); result } fn aexec(&self, in_state: &mut HeapLattice, ir_instr: &Stmt, loc_idx: &LocIdx) -> () { match ir_instr { Stmt::Clear(dst, _srcs) => { if let &Value::Reg(rd, Size32) | &Value::Reg(rd, Size16) | &Value::Reg(rd, Size8) = dst { in_state.regs.set_reg( rd, Size64, HeapValueLattice::new(Bounded4GB), ); } else { in_state.set_to_bot(dst) } }, Stmt::Unop(opcode, dst, src) => self.aexec_unop(in_state, opcode, &dst, &src, loc_idx), Stmt::Binop(opcode, dst, src1, src2) => { self.aexec_binop(in_state, opcode, dst, src1, src2, loc_idx); in_state.adjust_stack_offset(opcode, dst, src1, src2) } Stmt::Call(_) => { // TODO: this should only be for probestack // RDI is conserved on calls // let v = in_state.regs.get_reg(Rdi, Size64); in_state.on_call(); // in_state.regs.set_reg(Rdi, Size64, v); }, _ => (), } } fn aexec_unop( &self, in_state: &mut HeapLattice, opcode: &Unopcode, dst: &Value, src: &Value, _loc_idx: &LocIdx, ) -> () { // Any write to a 32-bit register will clear the upper 32 bits of the containing 64-bit // register. if let &Value::Reg(rd, Size32) = dst { in_state.regs.set_reg( rd, Size64, ConstLattice { v: Some(Bounded4GB), }, ); return; } match opcode { Unopcode::Mov => { let v = self.aeval_unop(in_state, src); in_state.set(dst, v); } Unopcode::Movsx => { in_state.set(dst, Default::default()); } } } fn aexec_binop( &self, in_state: &mut HeapLattice, opcode: &Binopcode, dst: &Value, src1: &Value, src2: &Value, _loc_idx: &LocIdx, ) { match opcode { Binopcode::Add => { if let ( &Value::Reg(rd, Size64), &Value::Reg(rs1, Size64), &Value::Reg(rs2, Size64), ) = (dst, src1, src2) { let rs1_val = in_state.regs.get_reg(rs1, Size64).v; let rs2_val = in_state.regs.get_reg(rs2, Size64).v; match (rs1_val, rs2_val) { (Some(HeapBase), Some(Bounded4GB)) | (Some(Bounded4GB), Some(HeapBase)) => { in_state .regs .set_reg(rd, Size64, ConstLattice { v: Some(HeapAddr) }); return; } _ => {} } } } _ => {} } // Any write to a 32-bit register will clear the upper 32 bits of the containing 64-bit // register. if let &Value::Reg(rd, Size32) = dst { in_state.regs.set_reg( rd, Size64, ConstLattice { v: Some(Bounded4GB), }, ); return; } in_state.set_to_bot(dst); } } pub fn is_globalbase_access(in_state: &HeapLattice, memargs: &MemArgs) -> bool { if let MemArgs::Mem2Args(arg1, _arg2) = memargs { if let MemArg::Reg(regnum, size) = arg1 { assert_eq!(size.into_bits(), 64); let base = in_state.regs.get_reg(*regnum, *size); if let Some(HeapBase) = base.v { return true; } } }; false } impl HeapAnalyzer { pub fn aeval_unop(&self, in_state: &HeapLattice, value: &Value) -> HeapValueLattice { match value { Value::Mem(memsize, memargs) => { if is_globalbase_access(in_state, memargs) { return HeapValueLattice::new(GlobalsBase); } if is_stack_access(value) { let offset = extract_stack_offset(memargs); let v = in_state.stack.get(offset, memsize.into_bytes()); return v; } } Value::Reg(regnum, size) => { if size.into_bits() <= 32 { return HeapValueLattice::new(Bounded4GB); } else { return in_state.regs.get_reg(*regnum, Size64); } } Value::Imm(_, _, immval) => { if (*immval as u64) == self.metadata.guest_table_0 { return HeapValueLattice::new(GuestTable0); } else if (*immval as u64) == self.metadata.lucet_tables { return HeapValueLattice::new(LucetTables); } else if (*immval >= 0) && (*immval < (1 << 32)) { return HeapValueLattice::new(Bounded4GB); } } Value::RIPConst => { return HeapValueLattice::new(RIPConst); } } Default::default() } } <file_sep>use crate::ir::types::X86Regs; use crate::lattices; use lattices::davlattice::DAV; use lattices::reachingdefslattice::LocIdx; use lattices::{Lattice, VariableState}; use std::cmp::Ordering; #[derive(Clone, PartialEq, Eq, PartialOrd, Debug)] pub enum CallCheckValue { GuestTableBase, LucetTablesBase, TableSize, TypeOf(X86Regs), //regnum PtrOffset(DAV), TypedPtrOffset(u32), FnPtr(u32), //type CheckedVal, CheckFlag(u32, X86Regs), TypeCheckFlag(X86Regs, u32), //addr, regnum, typeidx } use CallCheckValue::*; #[derive(PartialEq, Eq, Clone, Debug)] pub struct CallCheckValueLattice { pub v: Option<CallCheckValue>, } pub type CallCheckLattice = VariableState<CallCheckValueLattice>; impl Default for CallCheckValueLattice { fn default() -> Self { CallCheckValueLattice { v: None } } } impl CallCheckValueLattice { pub fn new(v: CallCheckValue) -> Self { CallCheckValueLattice { v: Some(v) } } } impl Lattice for CallCheckValueLattice { fn meet(&self, other: &Self, loc_idx: &LocIdx) -> Self { if self.v.clone() == other.v { CallCheckValueLattice { v: self.v.clone() } } else { match (self.v.clone(), other.v.clone()) { (Some(PtrOffset(x)), Some(PtrOffset(y))) => CallCheckValueLattice { v: Some(PtrOffset(x.meet(&y, loc_idx))), }, (_, _) => CallCheckValueLattice { v: None }, } } } } impl PartialOrd for CallCheckValueLattice { fn partial_cmp(&self, other: &CallCheckValueLattice) -> Option<Ordering> { match (self.v.clone(), other.v.clone()) { (None, None) => Some(Ordering::Equal), (None, _) => Some(Ordering::Less), (_, None) => Some(Ordering::Greater), (Some(x), Some(y)) => match (x.clone(), y.clone()) { (PtrOffset(x), PtrOffset(y)) => x.partial_cmp(&y), (_, _) => { if x == y { Some(Ordering::Equal) } else { None } } }, } } } #[test] fn call_lattice_test() { let x1 = CallCheckValueLattice { v: None }; let x2 = CallCheckValueLattice { v: Some(GuestTableBase), }; let x3 = CallCheckValueLattice { v: Some(PtrOffset(DAV::Unknown)), }; let x4 = CallCheckValueLattice { v: Some(PtrOffset(DAV::Unknown)), }; let x5 = CallCheckValueLattice { v: Some(PtrOffset(DAV::Checked)), }; assert_eq!(x1 == x2, false); assert_eq!(x2 == x3, false); assert_eq!(x3 == x4, true); assert_eq!(x4 == x5, false); assert_eq!(x1 != x2, true); assert_eq!(x2 != x3, true); assert_eq!(x3 != x4, false); assert_eq!(x4 != x5, true); assert_eq!(x1 > x2, false); assert_eq!(x2 > x3, false); assert_eq!(x3 > x4, false); assert_eq!(x4 > x5, false); assert_eq!(x1 < x2, true); assert_eq!(x2 < x3, false); assert_eq!(x3 < x4, false); assert_eq!(x4 < x5, true); assert_eq!( x1.meet(&x2, &LocIdx { addr: 0, idx: 0 }) == CallCheckValueLattice { v: None }, true ); assert_eq!( x2.meet(&x3, &LocIdx { addr: 0, idx: 0 }) == CallCheckValueLattice { v: None }, true ); assert_eq!( x3.meet(&x4, &LocIdx { addr: 0, idx: 0 }) == CallCheckValueLattice { v: Some(PtrOffset(DAV::Unknown)) }, true ); assert_eq!( x4.meet(&x5, &LocIdx { addr: 0, idx: 0 }) == CallCheckValueLattice { v: Some(PtrOffset(DAV::Unknown)) }, true ); } <file_sep>build_fuzzers: git clone https://github.com/PLSysSec/veriwasm_fuzzing.git cd veriwasm_fuzzing && make build compute_stats: if [ ! -d ./stats ]; then \ mkdir stats; \ fi cargo run --release -- -i veriwasm_public_data/firefox_libs/liboggwasm.so -o stats/liboggwasm.stats & cargo run --release -- -i veriwasm_public_data/firefox_libs/libgraphitewasm.so -o stats/libgraphitewasm.stats compute_stats_all: if [ ! -d ./stats ]; then \ mkdir stats; \ fi cargo run --release -- -i veriwasm_data/firefox_libs/liboggwasm.so -o stats/liboggwasm.stats & cargo run --release -- -i veriwasm_data/firefox_libs/libgraphitewasm.so -o stats/libgraphitewasm.stats & cargo run --release -- -i veriwasm_data/shootout/shootout.so -o stats/shootout.stats compute_stats_zerocost: mkdir -p ./zerocost_stats cargo build --release target/release/veriwasm -i veriwasm_public_data/zerocost_bins/graphiteogghunspell.so -o zerocost_stats/graphiteogghunspell target/release/veriwasm -i veriwasm_public_data/zerocost_bins/soundtouch.so -o zerocost_stats/soundtouch target/release/veriwasm -i veriwasm_public_data/zerocost_bins/libexpatwasm.so -o zerocost_stats/libexpatwasm target/release/veriwasm -i veriwasm_public_data/zerocost_spec_libraries/astar.so -o zerocost_stats/astar target/release/veriwasm -i veriwasm_public_data/zerocost_spec_libraries/bzip2.so -o zerocost_stats/bzip2 target/release/veriwasm -i veriwasm_public_data/zerocost_spec_libraries/gobmk.so -o zerocost_stats/gobmk target/release/veriwasm -i veriwasm_public_data/zerocost_spec_libraries/h264ref.so -o zerocost_stats/h264ref target/release/veriwasm -i veriwasm_public_data/zerocost_spec_libraries/lbm.so -o zerocost_stats/lbm target/release/veriwasm -i veriwasm_public_data/zerocost_spec_libraries/libquantum.so -o zerocost_stats/libquantum target/release/veriwasm -i veriwasm_public_data/zerocost_spec_libraries/mcf.so -o zerocost_stats/mcf target/release/veriwasm -i veriwasm_public_data/zerocost_spec_libraries/milc.so -o zerocost_stats/milc target/release/veriwasm -i veriwasm_public_data/zerocost_spec_libraries/namd.so -o zerocost_stats/namd target/release/veriwasm -i veriwasm_public_data/zerocost_spec_libraries/sjeng.so -o zerocost_stats/sjeng <file_sep>use crate::{analyses, ir, lattices, loaders}; use analyses::reaching_defs::ReachingDefnAnalyzer; use analyses::{AbstractAnalyzer, AnalysisResult}; use ir::types::{Binopcode, IRMap, MemArg, MemArgs, Unopcode, ValSize, Value, X86Regs}; use ir::utils::get_rsp_offset; use lattices::reachingdefslattice::{LocIdx, ReachLattice}; use lattices::switchlattice::{SwitchLattice, SwitchValue, SwitchValueLattice}; use lattices::{VarSlot, VarState}; use loaders::types::VwMetadata; use std::default::Default; use SwitchValue::{JmpOffset, JmpTarget, SwitchBase, UpperBound}; use ValSize::*; use X86Regs::*; pub struct SwitchAnalyzer { pub metadata: VwMetadata, pub reaching_defs: AnalysisResult<ReachLattice>, pub reaching_analyzer: ReachingDefnAnalyzer, } impl AbstractAnalyzer<SwitchLattice> for SwitchAnalyzer { fn aexec_unop( &self, in_state: &mut SwitchLattice, _opcode: &Unopcode, dst: &Value, src: &Value, _loc_idx: &LocIdx, ) -> () { in_state.set(dst, self.aeval_unop(in_state, src)) } fn aexec_binop( &self, in_state: &mut SwitchLattice, opcode: &Binopcode, dst: &Value, src1: &Value, src2: &Value, loc_idx: &LocIdx, ) -> () { if let Binopcode::Cmp = opcode { match (src1, src2) { (Value::Reg(regnum, _), Value::Imm(_, _, imm)) | (Value::Imm(_, _, imm), Value::Reg(regnum, _)) => { let reg_def = self .reaching_analyzer .fetch_def(&self.reaching_defs, loc_idx); let src_loc = reg_def.regs.get_reg(*regnum, Size64); in_state.regs.set_reg( Zf, Size64, SwitchValueLattice::new(SwitchValue::ZF(*imm as u32, *regnum, src_loc)), ); } _ => (), } } match opcode { Binopcode::Cmp => (), Binopcode::Test => { in_state.regs.set_reg(Zf, Size64, Default::default()); } _ => in_state.set(dst, self.aeval_binop(in_state, opcode, src1, src2)), } } fn process_branch( &self, irmap: &IRMap, in_state: &SwitchLattice, succ_addrs: &Vec<u64>, addr: &u64, ) -> Vec<(u64, SwitchLattice)> { if succ_addrs.len() == 2 { let mut not_branch_state = in_state.clone(); let mut branch_state = in_state.clone(); if let Some(SwitchValue::ZF(bound, regnum, checked_defs)) = &in_state.regs.get_reg(Zf, Size64).v { not_branch_state.regs.set_reg( *regnum, Size64, SwitchValueLattice { v: Some(UpperBound(*bound)), }, ); let defs_state = self.reaching_defs.get(addr).unwrap(); let ir_block = irmap.get(addr).unwrap(); let defs_state = self.reaching_analyzer.analyze_block(defs_state, ir_block); //propagate bound across registers with the same reaching def for idx in X86Regs::iter() { if idx != *regnum { let reg_def = defs_state.regs.get_reg(idx, Size64); if (!reg_def.is_empty()) && (&reg_def == checked_defs) { not_branch_state.regs.set_reg( idx, Size64, SwitchValueLattice { v: Some(UpperBound(*bound)), }, ); } } } //propagate bound across stack slots with the same upper bound for (stack_offset, stack_slot) in defs_state.stack.map.iter() { if !checked_defs.is_empty() && (&stack_slot.value == checked_defs) { let v = SwitchValueLattice { v: Some(UpperBound(*bound)), }; let vv = VarSlot { size: stack_slot.size, value: v, }; not_branch_state.stack.map.insert(*stack_offset, vv); } } } branch_state.regs.set_reg(Zf, Size64, Default::default()); not_branch_state .regs .set_reg(Zf, Size64, Default::default()); vec![ (succ_addrs[0].clone(), not_branch_state), (succ_addrs[1].clone(), branch_state), ] } else { succ_addrs .into_iter() .map(|addr| (addr.clone(), in_state.clone())) .collect() } } } impl SwitchAnalyzer { fn aeval_unop_mem( &self, in_state: &SwitchLattice, memargs: &MemArgs, memsize: &ValSize, ) -> SwitchValueLattice { if let Some(offset) = get_rsp_offset(memargs) { return in_state.stack.get(offset, memsize.into_bytes()); } if let MemArgs::MemScale( MemArg::Reg(regnum1, size1), MemArg::Reg(regnum2, size2), MemArg::Imm(_, _, immval), ) = memargs { if let (Some(SwitchBase(base)), Some(UpperBound(bound)), 4) = ( in_state.regs.get_reg(*regnum1, *size1).v, in_state.regs.get_reg(*regnum2, *size2).v, immval, ) { return SwitchValueLattice::new(JmpOffset(base, bound)); } } Default::default() } // 1. if unop is a constant, set as constant -- done // 2. if reg, return reg -- done // 3. if stack access, return stack access -- done // 4. x = mem[switch_base + offset * 4] pub fn aeval_unop(&self, in_state: &SwitchLattice, src: &Value) -> SwitchValueLattice { match src { Value::Mem(memsize, memargs) => self.aeval_unop_mem(in_state, memargs, memsize), Value::Reg(regnum, size) => in_state.regs.get_reg(*regnum, *size), Value::Imm(_, _, immval) => { if *immval == 0 { SwitchValueLattice::new(UpperBound(1)) } else { SwitchValueLattice::new(SwitchBase(*immval as u32)) } } Value::RIPConst => Default::default(), } } // 1. x = switch_base + offset pub fn aeval_binop( &self, in_state: &SwitchLattice, opcode: &Binopcode, src1: &Value, src2: &Value, ) -> SwitchValueLattice { if let Binopcode::Add = opcode { if let (Value::Reg(regnum1, size1), Value::Reg(regnum2, size2)) = (src1, src2) { match ( in_state.regs.get_reg(*regnum1, *size1).v, in_state.regs.get_reg(*regnum2, *size2).v, ) { (Some(SwitchBase(base)), Some(JmpOffset(_, offset))) | (Some(JmpOffset(_, offset)), Some(SwitchBase(base))) => { return SwitchValueLattice::new(JmpTarget(base, offset)) } _ => return Default::default(), }; } } Default::default() } } <file_sep>use clap::{App, Arg}; use loaders::types::{ExecutableType, VwArch}; use std::str::FromStr; use veriwasm::loaders; use veriwasm::runner::*; fn main() { let _ = env_logger::try_init(); let matches = App::new("VeriWasm") .version("0.1.0") .about("Validates safety of native Wasm code") .arg( Arg::with_name("module path") .short("i") .takes_value(true) .help("path to native Wasm module to validate") .required(true), ) .arg( Arg::with_name("jobs") .short("j") .long("jobs") .takes_value(true) .help("Number of parallel threads (default 1)"), ) .arg( Arg::with_name("stats output path") .short("o") .long("output") .takes_value(true) .help("Path to output stats file"), ) .arg( Arg::with_name("one function") .short("f") .long("func") .takes_value(true) .help("Single function to process (rather than whole module)"), ) .arg( Arg::with_name("executable type") .short("c") .long("format") .takes_value(true) .help("Format of the executable (lucet | wasmtime)"), ) .arg( Arg::with_name("architecture") .long("arch") .takes_value(true) .help("Architecture of the executable (x64 | aarch64)"), ) .arg(Arg::with_name("disable_stack_checks").long("disable_stack_checks")) .arg(Arg::with_name("disable_linear_mem_checks").long("disable_linear_mem_checks")) .arg(Arg::with_name("disable_call_checks").long("disable_call_checks")) .arg(Arg::with_name("enable_zero_cost_checks").long("enable_zero_cost_checks")) .get_matches(); let module_path = matches.value_of("module path").unwrap(); let num_jobs_opt = matches.value_of("jobs"); let output_path = matches.value_of("stats output path").unwrap_or(""); let num_jobs = num_jobs_opt .map(|s| s.parse::<u32>().unwrap_or(1)) .unwrap_or(1); let disable_stack_checks = matches.is_present("disable_stack_checks"); let disable_linear_mem_checks = matches.is_present("disable_linear_mem_checks"); let disable_call_checks = matches.is_present("disable_call_checks"); let enable_zero_cost_checks = matches.is_present("enable_zero_cost_checks"); let only_func = matches.value_of("one function").map(|s| s.to_owned()); let executable_type = ExecutableType::from_str(matches.value_of("executable type").unwrap_or("lucet")).unwrap(); let arch = VwArch::from_str(matches.value_of("architecture").unwrap_or("x64")).unwrap(); let has_output = if output_path == "" { false } else { true }; let active_passes = PassConfig { stack: !disable_stack_checks, linear_mem: !disable_linear_mem_checks, call: !disable_call_checks, zero_cost: enable_zero_cost_checks, }; let config = Config { module_path: module_path.to_string(), _num_jobs: num_jobs, output_path: output_path.to_string(), has_output: has_output, only_func, executable_type, active_passes, arch, }; run(config); } <file_sep>use std::collections::HashMap; use std::convert::TryFrom; #[derive(Debug, Clone)] pub enum ImmType { Signed, Unsigned, } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)] pub enum ValSize { Size1, Size8, Size16, Size32, Size64, Size128, Size256, Size512, } impl ValSize { pub fn try_from_bits(value: u32) -> Result<Self, String> { match value { 1 => Ok(ValSize::Size1), 8 => Ok(ValSize::Size8), 16 => Ok(ValSize::Size16), 32 => Ok(ValSize::Size32), 64 => Ok(ValSize::Size64), 128 => Ok(ValSize::Size128), 256 => Ok(ValSize::Size256), 512 => Ok(ValSize::Size512), _ => Err(format!("Not a valid bit length: {:?}", value)), } } pub fn into_bits(self) -> u32 { match self { ValSize::Size1 => 1, ValSize::Size8 => 8, ValSize::Size16 => 16, ValSize::Size32 => 32, ValSize::Size64 => 64, ValSize::Size128 => 128, ValSize::Size256 => 256, ValSize::Size512 => 512, } } pub fn try_from_bytes(value: u32) -> Result<Self, String> { match value { 1 => Ok(ValSize::Size8), 2 => Ok(ValSize::Size16), 4 => Ok(ValSize::Size32), 8 => Ok(ValSize::Size64), 16 => Ok(ValSize::Size128), 32 => Ok(ValSize::Size256), 64 => Ok(ValSize::Size512), _ => Err(format!("Not a valid byte length: {:?}", value)), } } pub fn into_bytes(self) -> u32 { match self { ValSize::Size1 => panic!("1 bit flag cannot be converted to bytes"), ValSize::Size8 => 1, ValSize::Size16 => 2, ValSize::Size32 => 4, ValSize::Size64 => 8, ValSize::Size128 => 16, ValSize::Size256 => 32, ValSize::Size512 => 64, } } pub fn fp_offset() -> u8 { u8::from(Zmm0) } } #[derive(Debug, Clone)] pub enum MemArgs { Mem1Arg(MemArg), // [arg] Mem2Args(MemArg, MemArg), // [arg1 + arg2] Mem3Args(MemArg, MemArg, MemArg), // [arg1 + arg2 + arg3] MemScale(MemArg, MemArg, MemArg), // [arg1 + arg2 * arg3] } #[derive(Debug, Clone)] pub enum MemArg { Reg(X86Regs, ValSize), // register mappings captured in `crate::lattices` Imm(ImmType, ValSize, i64), // signed, size, const } #[derive(Debug, Clone)] pub enum Value { Mem(ValSize, MemArgs), // mem[memargs] Reg(X86Regs, ValSize), Imm(ImmType, ValSize, i64), // signed, size, const RIPConst, } impl From<i64> for Value { fn from(num: i64) -> Self { Value::Imm(ImmType::Signed, ValSize::Size64, num) } } #[derive(Debug, Clone)] pub enum Stmt { Clear(Value, Vec<Value>), // clear v <- vs Unop(Unopcode, Value, Value), // v1 <- uop v2 Binop(Binopcode, Value, Value, Value), // v1 <- bop v2 v3 Undefined, // undefined Ret, // return Branch(yaxpeax_x86::long_mode::Opcode, Value), // br branch-type v Call(Value), // call v ProbeStack(u64), // probestack } #[derive(Debug, Clone)] pub enum Unopcode { Mov, Movsx, } #[derive(Debug, Clone)] pub enum Binopcode { Test, Rol, Cmp, Shl, And, Add, Sub, } pub type IRBlock = Vec<(u64, Vec<Stmt>)>; pub type IRMap = HashMap<u64, IRBlock>; #[derive(Clone, Debug)] pub enum VarIndex { Reg(X86Regs), Stack(i64), } #[derive(Debug, Clone)] pub struct FunType { pub args: Vec<(VarIndex, ValSize)>, pub ret: Option<(X86Regs, ValSize)>, } // TODO: this should not implement PartialOrd // TODO: add flags iter #[derive(PartialEq, PartialOrd, Clone, Eq, Debug, Copy, Hash)] pub enum X86Regs { Rax, Rcx, Rdx, Rbx, Rsp, Rbp, Rsi, Rdi, R8, R9, R10, R11, R12, R13, R14, R15, Zf, Cf, Pf, Sf, Of, Zmm0, Zmm1, Zmm2, Zmm3, Zmm4, Zmm5, Zmm6, Zmm7, Zmm8, Zmm9, Zmm10, Zmm11, Zmm12, Zmm13, Zmm14, Zmm15, } use self::X86Regs::*; impl X86Regs { pub fn is_flag(self) -> bool { match self { Zf | Cf | Pf | Sf | Of => true, _ => false, } } } pub struct X86RegsIterator { current_reg: Option<X86Regs>, } impl X86Regs { pub fn iter() -> X86RegsIterator { X86RegsIterator { current_reg: Some(Rax), } } } impl Iterator for X86RegsIterator { type Item = X86Regs; fn next(&mut self) -> Option<Self::Item> { match self.current_reg { None => None, Some(reg) => match reg { Rax => { self.current_reg = Some(Rcx); return Some(Rax); } Rcx => { self.current_reg = Some(Rdx); return Some(Rcx); } Rdx => { self.current_reg = Some(Rbx); return Some(Rdx); } Rbx => { self.current_reg = Some(Rsp); return Some(Rbx); } Rsp => { self.current_reg = Some(Rbp); return Some(Rsp); } Rbp => { self.current_reg = Some(Rsi); return Some(Rbp); } Rsi => { self.current_reg = Some(Rdi); return Some(Rsi); } Rdi => { self.current_reg = Some(R8); return Some(Rdi); } R8 => { self.current_reg = Some(R9); return Some(R8); } R9 => { self.current_reg = Some(R10); return Some(R9); } R10 => { self.current_reg = Some(R11); return Some(R10); } R11 => { self.current_reg = Some(R12); return Some(R11); } R12 => { self.current_reg = Some(R13); return Some(R12); } R13 => { self.current_reg = Some(R14); return Some(R13); } R14 => { self.current_reg = Some(R15); return Some(R14); } R15 => { self.current_reg = Some(Zf); return Some(R15); } Zf => { self.current_reg = Some(Cf); return Some(Zf); } Cf => { self.current_reg = Some(Pf); return Some(Cf); } Pf => { self.current_reg = Some(Sf); return Some(Pf); } Sf => { self.current_reg = Some(Of); return Some(Sf); } Of => { self.current_reg = Some(Zmm0); return Some(Of); } Zmm0 => { self.current_reg = Some(Zmm1); return Some(Zmm0); } Zmm1 => { self.current_reg = Some(Zmm2); return Some(Zmm1); } Zmm2 => { self.current_reg = Some(Zmm3); return Some(Zmm2); } Zmm3 => { self.current_reg = Some(Zmm4); return Some(Zmm3); } Zmm4 => { self.current_reg = Some(Zmm5); return Some(Zmm4); } Zmm5 => { self.current_reg = Some(Zmm6); return Some(Zmm5); } Zmm6 => { self.current_reg = Some(Zmm7); return Some(Zmm6); } Zmm7 => { self.current_reg = Some(Zmm8); return Some(Zmm7); } Zmm8 => { self.current_reg = Some(Zmm9); return Some(Zmm8); } Zmm9 => { self.current_reg = Some(Zmm10); return Some(Zmm9); } Zmm10 => { self.current_reg = Some(Zmm11); return Some(Zmm10); } Zmm11 => { self.current_reg = Some(Zmm12); return Some(Zmm11); } Zmm12 => { self.current_reg = Some(Zmm13); return Some(Zmm12); } Zmm13 => { self.current_reg = Some(Zmm14); return Some(Zmm13); } Zmm14 => { self.current_reg = Some(Zmm15); return Some(Zmm14); } Zmm15 => { self.current_reg = None; return Some(Zmm15); } }, } } } impl TryFrom<u8> for X86Regs { type Error = std::string::String; fn try_from(value: u8) -> Result<Self, Self::Error> { match value { 0 => Ok(Rax), 1 => Ok(Rcx), 2 => Ok(Rdx), 3 => Ok(Rbx), 4 => Ok(Rsp), 5 => Ok(Rbp), 6 => Ok(Rsi), 7 => Ok(Rdi), 8 => Ok(R8), 9 => Ok(R9), 10 => Ok(R10), 11 => Ok(R11), 12 => Ok(R12), 13 => Ok(R13), 14 => Ok(R14), 15 => Ok(R15), 16 => Ok(Zf), 17 => Ok(Cf), 18 => Ok(Pf), 19 => Ok(Sf), 20 => Ok(Of), 21 => Ok(Zmm0), 22 => Ok(Zmm1), 23 => Ok(Zmm2), 24 => Ok(Zmm3), 25 => Ok(Zmm4), 26 => Ok(Zmm5), 27 => Ok(Zmm6), 28 => Ok(Zmm7), 29 => Ok(Zmm8), 30 => Ok(Zmm9), 31 => Ok(Zmm10), 32 => Ok(Zmm11), 33 => Ok(Zmm12), 34 => Ok(Zmm13), 35 => Ok(Zmm14), 36 => Ok(Zmm15), _ => Err(format!("Unknown register: index = {:?}", value)), } } } impl From<X86Regs> for u8 { fn from(value: X86Regs) -> Self { value as u8 } } <file_sep>use crate::ir::types::*; use ValSize::*; use X86Regs::*; pub fn is_rsp(v: &Value) -> bool { match v { Value::Reg(Rsp, Size64) => return true, Value::Reg(Rsp, Size32) | Value::Reg(Rsp, Size16) | Value::Reg(Rsp, Size8) => { panic!("Illegal RSP access") } _ => return false, } } pub fn is_rbp(v: &Value) -> bool { match v { Value::Reg(Rbp, Size64) => return true, Value::Reg(Rbp, Size32) | Value::Reg(Rbp, Size16) | Value::Reg(Rbp, Size8) => { panic!("Illegal RBP access") } _ => return false, } } pub fn is_zf(v: &Value) -> bool { match v { Value::Reg(Zf, _) => return true, _ => return false, } } pub fn memarg_is_stack(memarg: &MemArg) -> bool { if let MemArg::Reg(Rsp, regsize) = memarg { if let Size64 = regsize { return true; } else { panic!("Non 64 bit version of rsp being used") }; } return false; } pub fn is_stack_access(v: &Value) -> bool { if let Value::Mem(_size, memargs) = v { match memargs { MemArgs::Mem1Arg(memarg) => return memarg_is_stack(memarg), MemArgs::Mem2Args(memarg1, memarg2) => { return memarg_is_stack(memarg1) || memarg_is_stack(memarg2) } MemArgs::Mem3Args(memarg1, memarg2, memarg3) => { return memarg_is_stack(memarg1) || memarg_is_stack(memarg2) || memarg_is_stack(memarg3) } MemArgs::MemScale(memarg1, memarg2, memarg3) => { return memarg_is_stack(memarg1) || memarg_is_stack(memarg2) || memarg_is_stack(memarg3) } } } false } pub fn memarg_is_bp(memarg: &MemArg) -> bool { if let MemArg::Reg(Rbp, regsize) = memarg { if let Size64 = regsize { return true; } else { panic!("Non 64 bit version of rbp being used") }; } return false; } pub fn is_bp_access(v: &Value) -> bool { if let Value::Mem(_size, memargs) = v { match memargs { MemArgs::Mem1Arg(memarg) => return memarg_is_bp(memarg), MemArgs::Mem2Args(memarg1, memarg2) => { return memarg_is_bp(memarg1) || memarg_is_bp(memarg2) } MemArgs::Mem3Args(memarg1, memarg2, memarg3) => { return memarg_is_bp(memarg1) || memarg_is_bp(memarg2) || memarg_is_bp(memarg3) } MemArgs::MemScale(memarg1, memarg2, memarg3) => { return memarg_is_bp(memarg1) || memarg_is_bp(memarg2) || memarg_is_bp(memarg3) } } } false } pub fn extract_stack_offset(memargs: &MemArgs) -> i64 { match memargs { MemArgs::Mem1Arg(_memarg) => 0, MemArgs::Mem2Args(_memarg1, memarg2) => get_imm_mem_offset(memarg2), MemArgs::Mem3Args(_memarg1, _memarg2, _memarg3) | MemArgs::MemScale(_memarg1, _memarg2, _memarg3) => panic!("extract_stack_offset failed"), } } pub fn is_mem_access(v: &Value) -> bool { if let Value::Mem(_, _) = v { true } else { false } } pub fn get_imm_offset(v: &Value) -> i64 { if let Value::Imm(_, _, v) = v { *v } else { panic!("get_imm_offset called on something that is not an imm offset") } } pub fn get_imm_mem_offset(v: &MemArg) -> i64 { if let MemArg::Imm(_, _, v) = v { *v } else { panic!("get_imm_offset called on something that is not an imm offset") } } pub fn has_indirect_calls(irmap: &IRMap) -> bool { for (_block_addr, ir_block) in irmap { for (_addr, ir_stmts) in ir_block { for (_idx, ir_stmt) in ir_stmts.iter().enumerate() { match ir_stmt { Stmt::Call(Value::Reg(_, _)) | Stmt::Call(Value::Mem(_, _)) => return true, _ => (), } } } } false } pub fn has_indirect_jumps(irmap: &IRMap) -> bool { for (_block_addr, ir_block) in irmap { for (_addr, ir_stmts) in ir_block { for (_idx, ir_stmt) in ir_stmts.iter().enumerate() { match ir_stmt { Stmt::Branch(_, Value::Reg(_, _)) | Stmt::Branch(_, Value::Mem(_, _)) => { return true } _ => (), } } } } false } pub fn get_rsp_offset(memargs: &MemArgs) -> Option<i64> { match memargs { MemArgs::Mem1Arg(arg) => { if let MemArg::Reg(regnum, _) = arg { if *regnum == Rsp { return Some(0); } } None } MemArgs::Mem2Args(arg1, arg2) => { if let MemArg::Reg(regnum, _) = arg1 { if *regnum == Rsp { if let MemArg::Imm(_, _, offset) = arg2 { return Some(*offset); } } } None } _ => None, } } pub fn valsize(num: u32) -> ValSize { ValSize::try_from_bits(num).unwrap() } pub fn mk_value_i64(num: i64) -> Value { Value::Imm(ImmType::Signed, Size64, num) } <file_sep>use core::str::FromStr; use lucet_module::Signature; use std::collections::HashMap; use yaxpeax_core::memory::repr::process::{ ELFExport, ELFImport, ELFSection, ELFSymbol, ModuleData, ModuleInfo, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum VwArch { X64, Aarch64, } impl FromStr for VwArch { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match &s.to_string().to_lowercase()[..] { "x86_64" => Ok(VwArch::X64), "x64" => Ok(VwArch::X64), "aarch64" => Ok(VwArch::Aarch64), _ => Err("Unknown architecture"), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExecutableType { Lucet, Wasmtime, } impl FromStr for ExecutableType { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match &s.to_string().to_lowercase()[..] { "lucet" => Ok(ExecutableType::Lucet), "wasmtime" => Ok(ExecutableType::Wasmtime), _ => Err("Unknown executable type"), } } } //TODO: remove public fields pub struct VwModule { pub program: ModuleData, pub metadata: VwMetadata, pub format: ExecutableType, pub arch: VwArch, } #[derive(Clone, Debug)] pub struct VwMetadata { pub guest_table_0: u64, pub lucet_tables: u64, pub lucet_probestack: u64, } #[derive(Clone, Debug)] pub struct VwFuncInfo { // Index -> Type pub signatures: Vec<Signature>, // Name -> Index pub indexes: HashMap<String, u32>, } <file_sep>use std::cmp::Ordering; use std::collections::HashMap; use std::convert::TryFrom; use crate::ir::types::{ValSize, X86Regs}; use crate::lattices::reachingdefslattice::LocIdx; use crate::lattices::{Lattice, VarSlot}; use X86Regs::*; #[derive(Default, PartialEq, Eq, Clone, Debug)] pub struct X86RegsLattice<T> { pub map: HashMap<X86Regs, VarSlot<T>>, } fn hashmap_le<T: PartialOrd>(s1: &X86RegsLattice<T>, s2: &X86RegsLattice<T>) -> bool { for (k1, v1) in s1.map.iter() { if !s2.map.contains_key(k1) { return false; } else { if s2.map.get(k1).unwrap() < v1 { return false; } else { } } } true } impl<T: PartialOrd> PartialOrd for X86RegsLattice<T> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { if hashmap_le(self, other) { Some(Ordering::Less) } else if hashmap_le(other, self) { Some(Ordering::Greater) } else if self == other { Some(Ordering::Equal) } else { None } } } impl<T: Lattice + Clone> X86RegsLattice<T> { pub fn get_reg(&self, index: X86Regs, size: ValSize) -> T { // if let ValSize::Size128 = size { // return Default::default(); // TODO: what is happening here // } // if let ValSize::Size256 = size { // return Default::default(); // TODO: what is happening here // } // if let ValSize::Size256 = size { // return Default::default(); // TODO: what is happening here // } if let Some(slot) = self.map.get(&index) { slot.value.clone() } else { Default::default() } } pub fn get_reg_index(&self, index: u8, size: ValSize) -> T { let reg_index = match X86Regs::try_from(index) { Err(err) => panic!("{}", err), Ok(reg) => reg, }; self.get_reg(reg_index, size) } pub fn set_reg(&mut self, index: X86Regs, size: ValSize, value: T) { // if let ValSize::Size128 = size { // return Default::default(); // TODO: what is happening here // } // if let ValSize::Size256 = size { // return Default::default(); // TODO: what is happening here // } // if let ValSize::Size256 = size { // return Default::default(); // TODO: what is happening here // } self.map.insert( index, VarSlot { size: size.into_bits(), value, }, ); } pub fn set_reg_index(&mut self, index: u8, size: ValSize, value: T) -> () { let reg_index = match X86Regs::try_from(index) { Err(err) => panic!("{}", err), Ok(reg) => reg, }; self.set_reg(reg_index, size, value) } pub fn clear_regs(&mut self) -> () { self.map.clear() } // TODO: should this do the inverse? pub fn clear_caller_save_regs(&mut self) { // x86-64 calling convention: rax, rcx, rdx, rsi, rdi, r8, r9, r10, r11 must be saved by // the caller (are clobbered by the callee), so their states become unknown after calls. // // TODO: get calling convention from program's target ABI; on Windows, rsi and rdi are // callee-save. The below is thus sound but conservative (and possibly // false-positive-producing) on Windows. self.map.remove(&Rax); self.map.remove(&Rcx); self.map.remove(&Rdx); self.map.remove(&Rsi); self.map.remove(&Rdi); self.map.remove(&R8); self.map.remove(&R9); self.map.remove(&R10); self.map.remove(&R11); self.map.remove(&Zf); self.map.remove(&Cf); self.map.remove(&Pf); self.map.remove(&Sf); self.map.remove(&Of); } pub fn show(&self) -> () { println!("State = "); println!("{:?}", self.map); } } impl<T: Lattice + Clone> Lattice for X86RegsLattice<T> { fn meet(&self, other: &Self, loc_idx: &LocIdx) -> Self { let mut newmap: HashMap<X86Regs, VarSlot<T>> = HashMap::new(); for (var_index, v1) in self.map.iter() { match other.map.get(var_index) { Some(v2) => { let new_v = v1.value.meet(&v2.value.clone(), loc_idx); let newslot = VarSlot { size: std::cmp::min(v1.size, v2.size), value: new_v, }; newmap.insert(*var_index, newslot); } None => (), // this means v2 = ⊥ so v1 ∧ v2 = ⊥ } } X86RegsLattice { map: newmap } } } // TODO: put this back // #[test] // fn regs_lattice_test() { // use crate::lattices::BooleanLattice; // let r1 = X86RegsLattice { // rax: BooleanLattice { v: false }, // rbx: BooleanLattice { v: false }, // rcx: BooleanLattice { v: false }, // rdx: BooleanLattice { v: false }, // rdi: BooleanLattice { v: false }, // rsi: BooleanLattice { v: false }, // rsp: BooleanLattice { v: false }, // rbp: BooleanLattice { v: false }, // r8: BooleanLattice { v: false }, // r9: BooleanLattice { v: false }, // r10: BooleanLattice { v: false }, // r11: BooleanLattice { v: false }, // r12: BooleanLattice { v: false }, // r13: BooleanLattice { v: false }, // r14: BooleanLattice { v: false }, // r15: BooleanLattice { v: false }, // zf: BooleanLattice { v: false }, // }; // let r2 = X86RegsLattice { // rax: BooleanLattice { v: true }, // rbx: BooleanLattice { v: false }, // rcx: BooleanLattice { v: false }, // rdx: BooleanLattice { v: false }, // rdi: BooleanLattice { v: false }, // rsi: BooleanLattice { v: false }, // rsp: BooleanLattice { v: false }, // rbp: BooleanLattice { v: false }, // r8: BooleanLattice { v: false }, // r9: BooleanLattice { v: false }, // r10: BooleanLattice { v: false }, // r11: BooleanLattice { v: false }, // r12: BooleanLattice { v: false }, // r13: BooleanLattice { v: false }, // r14: BooleanLattice { v: false }, // r15: BooleanLattice { v: false }, // zf: BooleanLattice { v: false }, // }; // let r3 = X86RegsLattice { // rax: BooleanLattice { v: false }, // rbx: BooleanLattice { v: true }, // rcx: BooleanLattice { v: false }, // rdx: BooleanLattice { v: false }, // rdi: BooleanLattice { v: false }, // rsi: BooleanLattice { v: false }, // rsp: BooleanLattice { v: false }, // rbp: BooleanLattice { v: false }, // r8: BooleanLattice { v: false }, // r9: BooleanLattice { v: false }, // r10: BooleanLattice { v: false }, // r11: BooleanLattice { v: false }, // r12: BooleanLattice { v: false }, // r13: BooleanLattice { v: false }, // r14: BooleanLattice { v: false }, // r15: BooleanLattice { v: false }, // zf: BooleanLattice { v: false }, // }; // assert_eq!(r2.rax > r2.rbx, true); // assert_eq!(r2.rax < r2.rbx, false); // assert_eq!(r2.rax.gt(&r2.rbx), true); // assert_eq!(r2.rbx == r2.rdi, true); // assert_eq!(r1 < r2, true); // assert_eq!(r1 <= r2, true); // assert_eq!(r2 < r3, false); // assert_eq!(r2 <= r3, false); // assert_eq!(r2.meet(&r3, &LocIdx { addr: 0, idx: 0 }) == r1, true); // assert_eq!(r1.meet(&r2, &LocIdx { addr: 0, idx: 0 }) == r1, true); // } <file_sep>use crate::{analyses, ir, lattices}; use analyses::AbstractAnalyzer; use ir::types::{Binopcode, Stmt, Unopcode}; use ir::utils::{get_imm_offset, is_rbp, is_rsp}; use lattices::reachingdefslattice::LocIdx; use lattices::stackgrowthlattice::StackGrowthLattice; pub struct StackAnalyzer {} impl AbstractAnalyzer<StackGrowthLattice> for StackAnalyzer { fn init_state(&self) -> StackGrowthLattice { StackGrowthLattice::new((0, 4096, 0)) } fn aexec(&self, in_state: &mut StackGrowthLattice, ir_instr: &Stmt, loc_idx: &LocIdx) -> () { match ir_instr { Stmt::Clear(dst, _) => { if is_rsp(dst) { *in_state = Default::default() } } Stmt::Unop(Unopcode::Mov, dst, src) if is_rsp(dst) && is_rbp(src) => { if let Some((_, probestack, rbp_stackgrowth)) = in_state.v { *in_state = StackGrowthLattice { v: Some((rbp_stackgrowth, probestack, rbp_stackgrowth)), }; } } Stmt::Unop(Unopcode::Mov, dst, src) if is_rbp(dst) && is_rsp(src) => { if let Some((stackgrowth, probestack, _)) = in_state.v { *in_state = StackGrowthLattice { v: Some((stackgrowth, probestack, stackgrowth)), }; } } Stmt::Unop(_, dst, _) => { if is_rsp(dst) { *in_state = Default::default() } } Stmt::Binop(Binopcode::Cmp, _, _, _) => (), Stmt::Binop(Binopcode::Test, _, _, _) => (), Stmt::Binop(opcode, dst, src1, src2) => { if is_rsp(dst) { if is_rsp(src1) { log::debug!( "Processing stack instruction: 0x{:x} {:?}", loc_idx.addr, ir_instr ); let offset = get_imm_offset(src2); if let Some((x, probestack, rbp)) = in_state.v { match opcode { Binopcode::Add => { *in_state = StackGrowthLattice { v: Some((x + offset, probestack, rbp)), } } Binopcode::Sub => { if (offset - x) > probestack + 4096 { panic!("Probestack violation") } else if (offset - x) > probestack { //if we touch next page after the space //we've probed, it cannot skip guard page *in_state = StackGrowthLattice { v: Some((x - offset, probestack + 4096, rbp)), }; return; } *in_state = StackGrowthLattice { v: Some((x - offset, probestack, rbp)), } } _ => panic!("Illegal RSP write"), } } else { *in_state = Default::default() } } else { *in_state = Default::default() } } } Stmt::ProbeStack(new_probestack) => { if let Some((x, _old_probestack, rbp)) = in_state.v { let probed = (((*new_probestack / 4096) + 1) * 4096) as i64; // Assumes page size of 4096 *in_state = StackGrowthLattice { v: Some((x - *new_probestack as i64, probed, rbp)), } } else { *in_state = Default::default() } } _ => (), } } } <file_sep>use crate::lattices::{ConstLattice, VariableState}; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum HeapValue { HeapBase, Bounded4GB, HeapAddr, LucetTables, GuestTable0, GlobalsBase, RIPConst, } pub type HeapValueLattice = ConstLattice<HeapValue>; pub type HeapLattice = VariableState<HeapValueLattice>; #[test] fn heap_lattice_test() { use crate::lattices::reachingdefslattice::LocIdx; use crate::lattices::Lattice; let x1 = HeapValueLattice { v: None }; let x2 = HeapValueLattice { v: Some(HeapValue::HeapBase), }; let x3 = HeapValueLattice { v: Some(HeapValue::HeapBase), }; let x4 = HeapValueLattice { v: Some(HeapValue::Bounded4GB), }; assert_eq!(x1 == x2, false); assert_eq!(x2 == x3, true); assert_eq!(x3 == x4, false); assert_eq!(x1 != x2, true); assert_eq!(x2 != x3, false); assert_eq!(x3 != x4, true); assert_eq!(x1 > x2, false); assert_eq!(x2 > x3, false); assert_eq!(x3 > x4, false); assert_eq!(x1 < x2, true); assert_eq!(x2 < x3, false); assert_eq!(x3 < x4, false); assert_eq!( x1.meet(&x2, &LocIdx { addr: 0, idx: 0 }) == HeapValueLattice { v: None }, true ); assert_eq!( x2.meet(&x3, &LocIdx { addr: 0, idx: 0 }) == HeapValueLattice { v: Some(HeapValue::HeapBase) }, true ); assert_eq!( x3.meet(&x4, &LocIdx { addr: 0, idx: 0 }) == HeapValueLattice { v: None }, true ); } <file_sep>use crate::lattices::reachingdefslattice::LocIdx; use crate::lattices::{Lattice, VarSlot}; use std::cmp::Ordering; use std::collections::HashMap; use std::default::Default; //Currently implemented with hashmap, could also use a vector for a dense map #[derive(Eq, Clone, Debug)] pub struct StackLattice<T> { pub offset: i64, pub map: HashMap<i64, VarSlot<T>>, } impl<T: std::fmt::Debug + Clone> std::fmt::Display for StackLattice<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut tmp: Vec<(&i64, &VarSlot<T>)> = self.map.iter().collect(); let sorted = tmp.as_mut_slice(); sorted.sort_by(|a, b| b.0.cmp(&a.0)); write!(f, "{}: {:?}", self.offset, sorted) } } impl<T: Lattice + Clone> StackLattice<T> { pub fn update(&mut self, offset: i64, value: T, size: u32) -> () { // println!("stack update: {:?} + {:?} = {:?} <- {:?} {:?}", self.offset, offset, self.offset + offset, value, size); //Check if 4 aligned if (offset & 3) != 0 { panic!("Unsafe: Attempt to store value on the stack on not 4-byte aligned address."); } if size > 8 { panic!("Store too large!"); } //remove overlapping entries //if write is size 8: remove next slot (offset + 4) if one exists if size == 8 { self.map.remove(&(self.offset + offset + 4)); } // if next slot back (offset-4) is size 8, remove it if let Some(x) = self.map.get(&(self.offset + offset - 4)) { if x.size == 8 { self.map.remove(&(self.offset + offset - 4)); } } //if value is default, just delete entry map.remove(offset) if value == Default::default() { self.map.remove(&(self.offset + offset)); } else { self.map .insert(self.offset + offset, VarSlot { size, value }); } } pub fn get(&self, offset: i64, size: u32) -> T { if !(size == 4 || size == 8) { panic!("Load wrong size! size = {:?}", size); } // TODO: is this correct? match self.map.get(&(self.offset + offset)) { Some(stack_slot) => { if stack_slot.size == size { stack_slot.value.clone() } else { Default::default() } } None => Default::default(), } } pub fn update_stack_offset(&mut self, adjustment: i64) -> () { if (adjustment & 3) != 0 { panic!("Unsafe: Attempt to make stack not 4-byte aligned."); } self.offset += adjustment; } } //check if StackLattice s1 is less than StackLattice s2 fn hashmap_le<T: PartialOrd>(s1: &StackLattice<T>, s2: &StackLattice<T>) -> bool { for (k1, v1) in s1.map.iter() { if !s2.map.contains_key(k1) { return false; } else { if s2.map.get(k1).unwrap() < v1 { return false; } else { } } } true } impl<T: PartialOrd> PartialOrd for StackLattice<T> { fn partial_cmp(&self, other: &StackLattice<T>) -> Option<Ordering> { if self.offset != other.offset { None } else { if hashmap_le(self, other) { Some(Ordering::Less) } else if hashmap_le(other, self) { Some(Ordering::Greater) } else if self == other { Some(Ordering::Equal) } else { None } } } } impl<T: PartialEq> PartialEq for StackLattice<T> { fn eq(&self, other: &StackLattice<T>) -> bool { (self.map == other.map) && (self.offset == other.offset) } } //assumes that stack offset is equal in both stack lattices impl<T: Lattice + Clone> Lattice for StackLattice<T> { fn meet(&self, other: &Self, loc_idx: &LocIdx) -> Self { let mut newmap: HashMap<i64, VarSlot<T>> = HashMap::new(); for (k, v1) in self.map.iter() { match other.map.get(k) { Some(v2) => { if v1.size == v2.size { let new_v = v1.value.meet(&v2.value.clone(), loc_idx); if new_v != Default::default() { let newslot = VarSlot { size: v1.size, value: new_v, }; newmap.insert(*k, newslot); } } } None => (), } } if self.offset != other.offset { panic!( "stack offsets misaligned 0x{:x?}: {:?} {:?}", loc_idx.addr, self.offset, other.offset ); } StackLattice { offset: self.offset, map: newmap, } } } impl<T: Default> Default for StackLattice<T> { fn default() -> Self { StackLattice { offset: 0, map: HashMap::new(), } } } #[test] fn stack_lattice_test_eq() { use crate::lattices::BooleanLattice; let mut x1: StackLattice<BooleanLattice> = Default::default(); let mut x2: StackLattice<BooleanLattice> = Default::default(); assert_eq!(x1 == x2, true); //check equality with adjusted stack x1.update_stack_offset(4); x2.update_stack_offset(4); assert_eq!(x1 == x2, true); //check inequality of different stack adjustments x1.update_stack_offset(4); x2.update_stack_offset(8); assert_eq!(x1 == x2, false); x1.update_stack_offset(4); assert_eq!(x1 == x2, true); let y1 = BooleanLattice { v: false }; let y2 = BooleanLattice { v: false }; let y3 = BooleanLattice { v: true }; //check equality with entries added x1.update(4, y1, 4); //adding a false does nothing assert_eq!(x1 == x2, true); x2.update(4, y2, 4); assert_eq!(x1 == x2, true); //check that different sizes break equality x1.update(20, y3, 4); x2.update(20, y3, 8); assert_eq!(x1 != x2, true); assert_eq!(x1.get(20, 4) == y3, true); // should be false if we access with wrong size assert_eq!(x1.get(20, 8) == y3, false); assert_eq!(x1.get(20, 8) == y1, true); //empty entry should return default assert_eq!(x1.get(64, 8) == y1, true); } #[test] fn stack_lattice_test_ord() { use crate::lattices::BooleanLattice; let mut x1: StackLattice<BooleanLattice> = Default::default(); let mut x2: StackLattice<BooleanLattice> = Default::default(); let y1 = BooleanLattice { v: true }; let y2 = BooleanLattice { v: true }; //check 1 entry vs 0 x1.update(4, y1, 4); assert_eq!(x1 == x2, false); assert_eq!(x1 > x2, true); assert_eq!(x1 < x2, false); //check 2 entry vs 1 x1.update(8, y2, 4); x2.update(4, y1, 4); assert_eq!(x1 == x2, false); assert_eq!(x1 > x2, true); assert_eq!(x1 < x2, false); //check meet of 1 entry vs 2 assert_eq!(x1.meet(&x2, &LocIdx { addr: 0, idx: 0 }) == x2, true); } #[test] fn stack_lattice_test_overlapping_entries() { use crate::lattices::BooleanLattice; let mut x1: StackLattice<BooleanLattice> = Default::default(); let mut x2: StackLattice<BooleanLattice> = Default::default(); let y1 = BooleanLattice { v: true }; let y2 = BooleanLattice { v: true }; let y3 = BooleanLattice { v: true }; //overlapping entries x1.update_stack_offset(16); x2.update_stack_offset(16); x1.update(0, y2, 8); x1.update(4, y1, 4); x2.update(4, y3, 4); print!("{:?} {:?}", x1, x2); assert_eq!(x1 == x2, true); } <file_sep>use crate::runner::Config; use crate::{loaders, runner}; use loaders::types::{VwFuncInfo, VwMetadata, VwModule}; use loaders::utils::deconstruct_elf; use loaders::utils::*; use std::fs; use wasmtime::*; use yaxpeax_core::goblin::Object; use yaxpeax_core::memory::repr::process::ModuleData; use yaxpeax_core::memory::repr::process::Segment; //yaxpeax doesnt load .o files correctly, so this code // manually adds memory regions corresponding to ELF sections // (yaxpeax does this by segments, but .o files may not have segments) fn fixup_object_file(program: &mut ModuleData, obj: &[u8]) { // let elf = program.module_info().unwrap(); let elf = match Object::parse(obj) { Ok(obj @ Object::Elf(_)) => match obj { Object::Elf(elf) => elf, _ => panic!(), }, _ => panic!(), }; for section in elf.section_headers.iter() { if section.sh_name == 0 { continue; } //Load data for section let mut section_data = vec![0; section.sh_size as usize]; for idx in 0..section.sh_size { section_data[idx as usize] = obj[(section.sh_offset + idx) as usize]; } //add as segment let new_section = Segment { start: section.sh_addr as usize, // virtual addr data: section_data, name: elf .shdr_strtab .get(section.sh_name) .unwrap() .unwrap() .to_string(), }; program.segments.push(new_section); } } fn load_wasmtime_metadata(program: &ModuleData) -> VwMetadata { let (_, sections, entrypoint, imports, exports, symbols) = deconstruct_elf(program); // unimplemented!(); // let guest_table_0 = get_symbol_addr(symbols, "guest_table_0").unwrap(); // let lucet_tables = get_symbol_addr(symbols, "lucet_tables").unwrap(); // let lucet_probestack = get_symbol_addr(symbols, "lucet_probestack").unwrap(); // println!( // "guest_table_0 = {:x} lucet_tables = {:x} probestack = {:x}", // guest_table_0, lucet_tables, lucet_probestack // ); VwMetadata { guest_table_0: 0, lucet_tables: 0, lucet_probestack: 0, } } pub fn load_wasmtime_program(config: &runner::Config) -> VwModule { let path = &config.module_path; let buffer = fs::read(path).expect("Something went wrong reading the file"); let store: Store<()> = Store::default(); // Deserialize wasmtime module let module = unsafe { Module::deserialize(store.engine(), buffer).unwrap() }; unimplemented!(); // let obj = module.obj(); // match ModuleData::load_from(&obj, path.to_string()) { // Some(mut program) => { // fixup_object_file(&mut program, &obj); // let metadata = load_wasmtime_metadata(&program); // VwModule { // program, // metadata, // format: config.executable_type, // arch: config.arch, // } // } //{ FileRepr::Executable(data) } // None => { // panic!("function:{} is not a valid path", path) // } // } } // We do not need to check handwritten trampoline functions pub fn is_valid_wasmtime_func_name(name: &String) -> bool { // true !name.starts_with("_trampoline") } pub fn get_wasmtime_func_signatures(program: &ModuleData) -> VwFuncInfo { unimplemented!(); } pub fn wasmtime_get_plt_funcs(binpath: &str) -> Vec<(u64, String)> { unimplemented!(); } <file_sep>use crate::lattices::{Lattice, VariableState}; use std::cmp::Ordering; use std::collections::BTreeSet; #[derive(PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Debug)] pub struct LocIdx { pub addr: u64, pub idx: u32, } #[derive(Eq, Clone, Debug)] pub struct ReachingDefnLattice { pub defs: BTreeSet<LocIdx>, } pub type ReachLattice = VariableState<ReachingDefnLattice>; impl ReachingDefnLattice { pub fn is_empty(&self) -> bool { self.defs.is_empty() } } impl PartialOrd for ReachingDefnLattice { fn partial_cmp(&self, other: &ReachingDefnLattice) -> Option<Ordering> { if &self.defs == &other.defs { return Some(Ordering::Equal); } else if self.defs.is_subset(&other.defs) { return Some(Ordering::Greater); } else if other.defs.is_subset(&self.defs) { return Some(Ordering::Less); } else { return None; } } } impl PartialEq for ReachingDefnLattice { fn eq(&self, other: &ReachingDefnLattice) -> bool { self.defs == other.defs } } impl Lattice for ReachingDefnLattice { fn meet(&self, other: &Self, _loc_idx: &LocIdx) -> Self { let newdefs: BTreeSet<LocIdx> = self.defs.union(&other.defs).cloned().collect(); ReachingDefnLattice { defs: newdefs } } } impl Default for ReachingDefnLattice { fn default() -> Self { ReachingDefnLattice { defs: BTreeSet::new(), } } } pub fn singleton(loc_idx: LocIdx) -> ReachingDefnLattice { let mut bset = BTreeSet::new(); bset.insert(loc_idx); ReachingDefnLattice { defs: bset } } pub fn loc(addr: u64, idx: u32) -> ReachingDefnLattice { singleton(LocIdx { addr: addr, idx: idx, }) } <file_sep>use crate::ir::types::X86Regs; use crate::lattices::reachingdefslattice::ReachingDefnLattice; use crate::lattices::{ConstLattice, VariableState}; #[derive(Clone, PartialEq, Eq, Debug)] pub enum SwitchValue { SwitchBase(u32), ZF(u32, X86Regs, ReachingDefnLattice), UpperBound(u32), JmpOffset(u32, u32), // base + bound JmpTarget(u32, u32), //base + bound } pub type SwitchValueLattice = ConstLattice<SwitchValue>; pub type SwitchLattice = VariableState<SwitchValueLattice>; #[test] fn switch_lattice_test() { use crate::lattices::reachingdefslattice::LocIdx; use crate::lattices::Lattice; let x1 = SwitchValueLattice { v: None }; let x2 = SwitchValueLattice { v: Some(SwitchValue::SwitchBase(1)), }; let x3 = SwitchValueLattice { v: Some(SwitchValue::SwitchBase(1)), }; let x4 = SwitchValueLattice { v: Some(SwitchValue::SwitchBase(2)), }; let x5 = SwitchValueLattice { v: Some(SwitchValue::UpperBound(1)), }; assert_eq!(x1 == x2, false); assert_eq!(x2 == x3, true); assert_eq!(x3 == x4, false); assert_eq!(x4 == x5, false); assert_eq!(x1 != x2, true); assert_eq!(x2 != x3, false); assert_eq!(x3 != x4, true); assert_eq!(x4 != x5, true); assert_eq!(x1 > x2, false); assert_eq!(x2 > x3, false); assert_eq!(x3 > x4, false); assert_eq!(x4 > x5, false); assert_eq!(x1 < x2, true); assert_eq!(x2 < x3, false); assert_eq!(x3 < x4, false); assert_eq!(x4 < x5, false); assert_eq!( x1.meet(&x2, &LocIdx { addr: 0, idx: 0 }) == SwitchValueLattice { v: None }, true ); assert_eq!( x2.meet(&x3, &LocIdx { addr: 0, idx: 0 }) == SwitchValueLattice { v: Some(SwitchValue::SwitchBase(1)) }, true ); assert_eq!( x3.meet(&x4, &LocIdx { addr: 0, idx: 0 }) == SwitchValueLattice { v: None }, true ); assert_eq!( x4.meet(&x5, &LocIdx { addr: 0, idx: 0 }) == SwitchValueLattice { v: None }, true ); } <file_sep>use crate::{analyses, ir, lattices, loaders}; use std::collections::HashMap; use std::collections::HashSet; use analyses::{AbstractAnalyzer, AnalysisResult, CallAnalyzer}; use ir::types::{Binopcode, FunType, IRMap, Stmt, ValSize, Value, VarIndex, X86Regs}; use ir::utils::mk_value_i64; use lattices::calllattice::CallCheckLattice; use lattices::localslattice::*; use lattices::mem_to_stack_offset; use lattices::reachingdefslattice::LocIdx; use lattices::{Lattice, VarState, VariableState}; use loaders::types::VwFuncInfo; use loaders::utils::to_system_v_ret_ty; use SlotVal::*; use ValSize::*; use X86Regs::*; pub struct LocalsAnalyzer<'a> { pub fun_type: FunType, pub symbol_table: &'a VwFuncInfo, pub name_addr_map: &'a HashMap<u64, String>, pub plt_bounds: (u64, u64), pub call_analysis: AnalysisResult<CallCheckLattice>, pub call_analyzer: CallAnalyzer, } impl<'a> LocalsAnalyzer<'a> { pub fn aeval_val(&self, state: &LocalsLattice, value: &Value, loc_idx: &LocIdx) -> SlotVal { match value { Value::Mem(memsize, memargs) => { if let Some(offset) = mem_to_stack_offset(memargs) { // println!("reading from stack 0x{:x?}: {:?} + {:?}\n\t{:?}", loc_idx.addr, state.stack.offset, offset, value); // println!("{}", state.stack); // println!("{:?}", self.fun_type); state.stack.get(offset, memsize.into_bytes()) } else { // println!("reading from mem 0x{:x?}: {:?}", loc_idx.addr, value); Init } } Value::Reg(_, _) => state.get(value).unwrap_or(Uninit), Value::Imm(_, _, _) => Init, Value::RIPConst => todo!(), } } // if all values are initialized then the value is initialized pub fn aeval_vals( &self, state: &LocalsLattice, values: &Vec<Value>, loc_idx: &LocIdx, ) -> SlotVal { values.iter().fold(Init, |acc, value| -> SlotVal { if (acc == Init) && (self.aeval_val(state, value, loc_idx) == Init) { Init } else { Uninit } }) } } impl<'a> AbstractAnalyzer<LocalsLattice> for LocalsAnalyzer<'a> { fn init_state(&self) -> LocalsLattice { let mut lattice: LocalsLattice = Default::default(); for arg in self.fun_type.args.iter() { match arg { (VarIndex::Stack(offset), size) => { lattice .stack .update(i64::from(*offset), Init, size.into_bytes()) } (VarIndex::Reg(reg_num), size) => lattice.regs.set_reg(*reg_num, *size, Init), } } // rbp, rbx, and r12-r15 are the callee-saved registers lattice.regs.set_reg(Rbp, Size64, UninitCalleeReg(Rbp)); lattice.regs.set_reg(Rbx, Size64, UninitCalleeReg(Rbx)); lattice.regs.set_reg(R12, Size64, UninitCalleeReg(R12)); lattice.regs.set_reg(R13, Size64, UninitCalleeReg(R13)); lattice.regs.set_reg(R14, Size64, UninitCalleeReg(R14)); lattice.regs.set_reg(R15, Size64, UninitCalleeReg(R15)); lattice } fn aexec(&self, in_state: &mut LocalsLattice, ir_instr: &Stmt, loc_idx: &LocIdx) -> () { let debug_addrs: HashSet<u64> = vec![].into_iter().collect(); if debug_addrs.contains(&loc_idx.addr) { println!("========================================"); println!("{}", in_state); println!("aexec debug 0x{:x?}: {:?}", loc_idx.addr, ir_instr); } match ir_instr { Stmt::Clear(dst, srcs) => in_state.set(dst, self.aeval_vals(in_state, srcs, loc_idx)), Stmt::Unop(_, dst, src) => in_state.set(dst, self.aeval_val(in_state, src, loc_idx)), Stmt::Binop(opcode, dst, src1, src2) => { let dst_val = self .aeval_val(in_state, src1, loc_idx) .meet(&self.aeval_val(in_state, src2, loc_idx), loc_idx); in_state.set(dst, dst_val); let prev_offset = in_state.stack.offset; in_state.adjust_stack_offset(opcode, dst, src1, src2); // if prev_offset != in_state.stack.offset { // println!("adjusting offset 0x{:x?}: {:?}\n\t{:?} -> {:?}", // loc_idx.addr, // ir_instr, // prev_offset, // in_state.stack.offset, // ); // } } // TODO: wasi calls (no requirements on initialization, always return in rax) // TODO: wasi calls are things in plt_bounds? Stmt::Call(Value::Imm(_, _, dst)) => { let target = (*dst + (loc_idx.addr as i64) + 5) as u64; let name = self.name_addr_map.get(&target); let signature = name .and_then(|name| self.symbol_table.indexes.get(name)) .and_then(|sig_index| self.symbol_table.signatures.get(*sig_index as usize)); in_state.on_call(); if let Some((ret_reg, reg_size)) = signature.and_then(|sig| to_system_v_ret_ty(sig)) { in_state.regs.set_reg(ret_reg, reg_size, Init); } } Stmt::Call(val @ Value::Reg(_, _)) => { let fn_ptr_type = self .call_analyzer .get_fn_ptr_type(&self.call_analysis, loc_idx, val) .and_then(|fn_ptr_index| { self.symbol_table.signatures.get(fn_ptr_index as usize) }); in_state.on_call(); if let Some((ret_reg, reg_size)) = fn_ptr_type.and_then(|sig| to_system_v_ret_ty(sig)) { in_state.regs.set_reg(ret_reg, reg_size, Init); } } Stmt::Branch(br_type, val) => { // println!("unhandled branch 0x{:x?}: {:?} {:?}", loc_idx.addr, br_type, val); } Stmt::ProbeStack(x) => { in_state.adjust_stack_offset( &Binopcode::Sub, &Value::Reg(Rsp, Size64), &Value::Reg(Rsp, Size64), &mk_value_i64(*x as i64), ); } stmt => { // println!("unhandled instruction 0x{:x?}: {:?}", loc_idx.addr, stmt); } } if debug_addrs.contains(&loc_idx.addr) { println!("{}", in_state); println!("========================================"); } } fn process_branch( &self, _irmap: &IRMap, in_state: &LocalsLattice, succ_addrs: &Vec<u64>, _addr: &u64, ) -> Vec<(u64, LocalsLattice)> { succ_addrs .into_iter() .map(|addr| (addr.clone(), in_state.clone())) .collect() } }
984559bb746aa04fd4d905182c9e6bbc106d84ca
[ "TOML", "Markdown", "Makefile", "Rust", "Python" ]
42
Rust
spector-in-london/veriwasm
1fcb1e68a5947705f0bafaa90a2b76d1d9d0c596
9dcb82a3e98615e2ac12e94ddf24d7b84d85ea2a
refs/heads/master
<repo_name>jkdwyer/CS21-1<file_sep>/ProperStack/src/ProperStackLifo.java /** * Class ProperStackLifo * - This is the second version, using correct node-based model. * * - contains StackNode variable for head of stack. * - contains constructor, stackEmpty, stackPush and stackPop methods. * * @author <NAME> * @version 1.0 09/03/2017 */ public class ProperStackLifo { private StackNode head; // Stack should always start empty. private int nodeCounter = 0; // no-args constructor. public ProperStackLifo() { System.out.println("in ProperStackLifo constructor"); } // end constructor. /** * method stackEmpty * @return boolean - true if nodeCounter is zero. */ public boolean stackEmpty() { System.out.println("in ProperStackLifo.stackEmpty()"); return (nodeCounter == 0); } // end stackEmpty. /** * method stackPush * @param node - takes StackNode to add to stack. */ public void stackPush(StackNode node) { System.out.println("in ProperStackLifo.stackPush()"); System.out.println("node.getPayload(): " + node.getPayload()); if (nodeCounter == 0) { // then this is the first node added to the stack. head = node; } else { // current head must become last ref in new head, // then incoming node must become new head. node.setLast(head); head = node; } // end if. nodeCounter++; System.out.println("nodeCounter: " + nodeCounter); } // end stackAppend. /** * method stackPop * @return StackNode - head of stack is removed & returned. */ public StackNode stackPop() { System.out.println("in ProperStackLifo.stackPop()"); System.out.println("head.getPayload(): " + head.getPayload()); StackNode currentHead = new StackNode(); currentHead = head; // new head needs to be last ref from current head; this loses // the connection between the current head and the stack. head = currentHead.getLast(); // return value is the node that was the previous head. System.out.println("payload from node removed and returned: " + currentHead.getPayload()); if (head != null) { System.out.println("payload from new head: " + head.getPayload()); } // end if. nodeCounter--; System.out.println("nodeCounter: " + nodeCounter); return currentHead; } // end stackPop. public int getNodeCounter() { return nodeCounter; } // end getNodeCounter. public StackNode getHead() { return head; } // end getHead. } // end class. <file_sep>/List/test/DoublyLinkedListTest.java import junit.framework.TestCase; public class DoublyLinkedListTest extends TestCase { private String after; private String before; private int position = 0; private LLNode listNode0; private LLNode listNode1; private LLNode listNode2; private LLNode listNode3; private LLNode listNode4; private LLNode listNode5; private LLNode listNode6; private LLNode listNode7; private LLNode listNode8; private LLNode listNode9; private DoublyLinkedList dlList; public void setUp() { after = "after"; before = "before"; listNode1 = new LLNode(); listNode2 = new LLNode("Tourmaline"); listNode3 = new LLNode("Jade"); listNode4 = new LLNode("Olivine"); listNode5 = new LLNode("Malachite"); listNode6 = new LLNode("Aquamarine"); listNode7 = new LLNode("Peridot"); listNode8 = new LLNode("Gaspeite"); listNode9 = new LLNode("Amazonite"); dlList = new DoublyLinkedList(); // for searches and gets only. dlList.insertNewHead(listNode1); // tail. dlList.insertNewHead(listNode2); dlList.insertNewHead(listNode3); dlList.insertNewHead(listNode4); dlList.insertNewHead(listNode5); // last inserted is head. } public void testPrintList() throws Exception { // Can verify that the call produces the expected string // but I've done that below in testCreatePrintList. } public void testCreatePrintList() throws Exception { // start fresh list per test. DoublyLinkedList dlList = new DoublyLinkedList(); dlList.insertNewHead(listNode1); // tail. dlList.insertNewHead(listNode2); dlList.insertNewHead(listNode3); dlList.insertNewHead(listNode4); dlList.insertNewHead(listNode5); // last inserted is head. StringBuffer actualList = new StringBuffer(); actualList.append("\n"); actualList.append("ct: 1 - payload: Malachite"); actualList.append("\n"); actualList.append("ct: 2 - payload: Olivine"); actualList.append("\n"); actualList.append("ct: 3 - payload: Jade"); actualList.append("\n"); actualList.append("ct: 4 - payload: Tourmaline"); actualList.append("\n"); actualList.append("ct: 5 - payload: Emerald"); actualList.append("\n"); actualList.append("\n"); StringBuffer returnedList = dlList.createPrintList(); assertTrue(returnedList.toString().equals(actualList.toString())); } public void testInsertNodeListEmpty() throws Exception { // needs to begin with an empty list. DoublyLinkedList dlList2 = new DoublyLinkedList(); dlList2.insertNode(listNode9, listNode1, after); assertEquals(dlList2.getHead(), listNode9); assertEquals(dlList2.getTail(), listNode9); assertEquals(dlList2.getNodeCounter(), 1); } public void testInsertNodeBeforeHead() throws Exception { // start fresh list per test. DoublyLinkedList dlList = new DoublyLinkedList(); dlList.insertNewHead(listNode1); // tail. dlList.insertNewHead(listNode2); dlList.insertNewHead(listNode3); dlList.insertNewHead(listNode4); dlList.insertNewHead(listNode5); // last inserted is head. // insert L8 Gaspeite before L5 Malachite (head) assertEquals(dlList.getHead(), listNode5); dlList.insertNode(listNode8, listNode5, before); // new head; next and last changes for L8, L5. assertEquals(dlList.getHead(), listNode8); assertNull(listNode8.getLast()); assertEquals(listNode8.getNext(), listNode5); assertEquals(listNode5.getLast(), listNode8); } public void testInsertNodeBeforeNotHead() throws Exception { // start fresh list per test. DoublyLinkedList dlList = new DoublyLinkedList(); dlList.insertNewHead(listNode1); // tail. dlList.insertNewHead(listNode2); dlList.insertNewHead(listNode3); dlList.insertNewHead(listNode4); dlList.insertNewHead(listNode5); // last inserted is head. // insert L6 Aquamarine before L2 Tourmaline dlList.insertNode(listNode6, listNode2, before); // next and last changes for L2, L6, L3. assertEquals(listNode2.getLast(), listNode6); assertEquals(listNode6.getNext(), listNode2); assertEquals(listNode6.getLast(), listNode3); assertEquals(listNode3.getNext(), listNode6); } public void testInsertNodeAfterTail() throws Exception { // start fresh list per test. DoublyLinkedList dlList = new DoublyLinkedList(); dlList.insertNewHead(listNode1); // tail. dlList.insertNewHead(listNode2); dlList.insertNewHead(listNode3); dlList.insertNewHead(listNode4); dlList.insertNewHead(listNode5); // last inserted is head. // insert L9 Amazonite after L1 Emerald (tail) assertEquals(dlList.getTail(), listNode1); dlList.insertNode(listNode9, listNode1, after); assertEquals(dlList.getTail(), listNode9); assertNull(listNode9.getNext()); assertEquals(listNode9.getLast(), listNode1); assertEquals(listNode1.getNext(), listNode9); } public void testInsertNodeAfterNotTail() throws Exception { // start fresh list per test. DoublyLinkedList dlList = new DoublyLinkedList(); dlList.insertNewHead(listNode1); // tail. dlList.insertNewHead(listNode2); dlList.insertNewHead(listNode3); dlList.insertNewHead(listNode4); dlList.insertNewHead(listNode5); // last inserted is head. // insert L7 Peridot after L2 Tourmaline dlList.insertNode(listNode7, listNode2, after); // next and last changes for L2, L7, L1. assertEquals(listNode2.getNext(), listNode7); assertEquals(listNode7.getLast(), listNode2); assertEquals(listNode7.getNext(), listNode1); assertEquals(listNode1.getLast(), listNode7); } public void testInsertNewHead() throws Exception { // start fresh list. DoublyLinkedList dlList3 = new DoublyLinkedList(); dlList3.insertNewHead(listNode1); // tail. assertEquals(dlList3.getHead(), listNode1); assertEquals(dlList3.getTail(), listNode1); dlList3.insertNewHead(listNode2); assertEquals(dlList3.getHead(), listNode2); assertEquals(dlList3.getTail(), listNode1); dlList3.insertNewHead(listNode3); dlList3.insertNewHead(listNode4); dlList3.insertNewHead(listNode5); // last inserted is head. assertEquals(dlList3.getHead(), listNode5); assertEquals(dlList3.getTail(), listNode1); } public void testDeleteNodeListEmpty() throws Exception { // needs to begin with an empty list. DoublyLinkedList dlList2 = new DoublyLinkedList(); dlList2.deleteNode(listNode1); } public void testDeleteNodeHead() throws Exception { // start fresh list per test. DoublyLinkedList dlList = new DoublyLinkedList(); dlList.insertNewHead(listNode1); // tail. dlList.insertNewHead(listNode2); dlList.insertNewHead(listNode3); dlList.insertNewHead(listNode4); dlList.insertNewHead(listNode5); dlList.insertNewHead(listNode8); // last inserted is head. // delete L8 Gaspeite (head) assertEquals(dlList.getHead(), listNode8); dlList.deleteNode(listNode8); assertEquals(dlList.getHead(), listNode5); assertNull(listNode5.getLast()); } public void testDeleteNodeTail() throws Exception { // start fresh list per test. DoublyLinkedList dlList = new DoublyLinkedList(); dlList.insertNewHead(listNode9); // tail. dlList.insertNewHead(listNode1); dlList.insertNewHead(listNode2); dlList.insertNewHead(listNode3); dlList.insertNewHead(listNode4); dlList.insertNewHead(listNode5); // last inserted is head. // delete L9 Amazonite (tail) assertEquals(dlList.getTail(), listNode9); dlList.deleteNode(listNode9); assertEquals(dlList.getTail(), listNode1); assertNull(listNode1.getNext()); } public void testDeleteNode() throws Exception { // start fresh list per test. DoublyLinkedList dlList = new DoublyLinkedList(); dlList.insertNewHead(listNode1); // tail. dlList.insertNewHead(listNode2); dlList.insertNewHead(listNode3); dlList.insertNewHead(listNode4); dlList.insertNewHead(listNode5); // last inserted is head. // delete L3 Jade (between L4 Olivine and L2 Tourmaline) assertEquals(listNode4.getNext(), listNode3); assertEquals(listNode2.getLast(), listNode3); dlList.deleteNode(listNode3); assertEquals(listNode4.getNext(), listNode2); assertEquals(listNode2.getLast(), listNode4); } public void testSearchByNode() throws Exception { // uses private dlList initialized with 5 values. position = dlList.searchByNode(listNode5); assertEquals(position, 1); position = dlList.searchByNode(listNode4); assertEquals(position, 2); position = dlList.searchByNode(listNode3); assertEquals(position, 3); position = dlList.searchByNode(listNode2); assertEquals(position, 4); position = dlList.searchByNode(listNode1); assertEquals(position, 5); } public void testSearchByPosition() throws Exception { // uses private dlList initialized with 5 values. listNode0 = dlList.searchByPosition(1); assertEquals(listNode0, listNode5); listNode0 = dlList.searchByPosition(2); assertEquals(listNode0, listNode4); listNode0 = dlList.searchByPosition(3); assertEquals(listNode0, listNode3); listNode0 = dlList.searchByPosition(4); assertEquals(listNode0, listNode2); listNode0 = dlList.searchByPosition(5); assertEquals(listNode0, listNode1); listNode0 = dlList.searchByPosition(6); assertNull(listNode0); } public void testGetHead() throws Exception { // uses private dlList initialized with 5 values. assertEquals(dlList.getHead(), listNode5); } public void testGetTail() throws Exception { // uses private dlList initialized with 5 values. assertEquals(dlList.getTail(), listNode1); } public void testGetNodeCounter() throws Exception { // uses private dlList initialized with 5 values. assertEquals(dlList.getNodeCounter(), 5); } public void testListEmptyTrue() throws Exception { // needs to begin with an empty list. DoublyLinkedList dlList2 = new DoublyLinkedList(); assertEquals(dlList2.listEmpty(), true); } public void testListEmptyFalse() throws Exception { // uses private dlList initialized with 5 values. assertEquals(dlList.listEmpty(), false); } }<file_sep>/Queue/src/QueueFifo.java import java.util.ArrayList; /** * Class QueueFifo * - queue is first-in, first-out. * - contains QueueNode references to head and tail of queue. * - contains two constructors. * - contains enqueue and dequeue methods. * * @author <NAME> * @version 1.0 09/02/2017 */ public class QueueFifo { private QueueNode head; private QueueNode tail; // queue should always start empty. private int nodeCounter = 0; // no-args constructor 1. public QueueFifo() { System.out.println("in QueueFifo constructor - 1"); } // end no-args constructor. // constructor 2 takes a QueueNode object. public QueueFifo(QueueNode node) { System.out.println("in QueueFifo constructor - 2"); System.out.println("node.getPayload(): " + node.getPayload()); enqueue(node); } // end constructor 2. /** * method enqueue * - takes a QueueNode, adds a new node to existing queue. * * @param node - the node being added to the queue */ public void enqueue(QueueNode node) { System.out.println("in QueueFifo.enqueue"); System.out.println("node.getPayload(): " + node.getPayload()); if (nodeCounter == 0) { head = node; tail = node; } else { // change existing tail's last to incoming node. tail.setLast(node); // replace old value of tail with incoming node. tail = node; } // end if. nodeCounter++; // debug. System.out.println("after enqueue changes:"); System.out.println("head.getPayload(): " + head.getPayload()); System.out.println("tail.getPayload(): " + tail.getPayload()); System.out.println("nodeCounter: " + nodeCounter); } // end enqueue. /** * method dequeue() * - removes and returns the head object from the queue. * - if the current head object is the last in the queue, then * dequeue also sets the boolean queueEmpty value to true. * * @return QueueNode */ public QueueNode dequeue(){ System.out.println("in QueueFifo.dequeue"); System.out.println("head.getPayload(): " + head.getPayload()); System.out.println("tail.getPayload(): " + tail.getPayload()); System.out.println("removing head.getPayload(): " + head.getPayload()); /* re-set new head to the object referenced by the current head. the instance that is the current head is still out there, but the reference to it in the queue will be gone. the tail of the queue (where new nodes are inserted) is untouched by the dequeue process. */ head = head.getLast(); nodeCounter--; // debug. System.out.println("after dequeue changes:"); System.out.println("head.getPayload(): " + head.getPayload()); System.out.println("tail.getPayload(): " + tail.getPayload()); System.out.println("nodeCounter: " + nodeCounter); return head; } // end dequeue. /** * method queueEmpty() * - returns true when queue is empty. * @return boolean */ public boolean queueEmpty() { return (nodeCounter == 0); } // end queueEmpty. /** * method getHead() * - returns current reference to head of queue. * @return QueueNode */ public QueueNode getHead() { return head; } /** * method getTail() * - returns current reference to tail (entry-point) of queue. * @return QueueNode */ public QueueNode getTail() { return tail; } /** * method getNodeCounter() * - returns current value of nodeCounter. * @return int */ public int getNodeCounter() { return nodeCounter; } } // end class <file_sep>/List/src/MakeListApp.java import java.util.*; /** * Class MakeList for LinkedList assignment. * * @author <NAME> * @version 1.1 09/20/2017 * */ public class MakeListApp { /** * Main method. * Instantiate nodes, lists and stacks. * Primarily for testing. */ public static void main(String[] args){ // System.out.println("in MakeListApp.main"); String after = "after"; String before = "before"; int position = 0; LLNode listNode0; LLNode listNode1 = new LLNode(); LLNode listNode2 = new LLNode("Tourmaline"); LLNode listNode3 = new LLNode(args[0]); LLNode listNode5 = new LLNode(); listNode5.setPayload("Malachite"); System.out.println("Type in the value 'Olivine' on the next line:"); Scanner sc = new Scanner(System.in); String gem = sc.next(); LLNode listNode4; listNode4 = new LLNode(gem); // Need to type an input (Olivine) for listNode4 in output pane; // then the program will complete and show an exit code. DoublyLinkedList dlList = new DoublyLinkedList(); dlList.insertNewHead(listNode1); dlList.insertNewHead(listNode2); dlList.insertNewHead(listNode3); dlList.insertNewHead(listNode4); dlList.insertNewHead(listNode5); dlList.printList(); LLNode listNode6; listNode6 = new LLNode("Aquamarine"); System.out.println("insert L6 Aquamarine before L2 Tourmaline"); dlList.insertNode(listNode6, listNode2, before); dlList.printList(); LLNode listNode7; listNode7 = new LLNode("Peridot"); System.out.println("insert L7 Peridot after L2 Tourmaline"); dlList.insertNode(listNode7, listNode2, after); dlList.printList(); LLNode listNode8; listNode8 = new LLNode("Gaspeite"); System.out.println("insert L8 Gaspeite before L5 Malachite (head)"); dlList.insertNode(listNode8, listNode5, before); dlList.printList(); LLNode listNode9; listNode9 = new LLNode("Amazonite"); System.out.println("insert L9 Amazonite after L1 Emerald (tail)"); dlList.insertNode(listNode9, listNode1, after); dlList.printList(); System.out.println("delete L9 Amazonite (tail)"); dlList.deleteNode(listNode9); dlList.printList(); System.out.println("delete L8 Gaspeite (head)"); dlList.deleteNode(listNode8); dlList.printList(); System.out.println("delete L7 Peridot (between L2 Tourmaline and L1 Emerald)"); dlList.deleteNode(listNode7); dlList.printList(); System.out.println("nodeCounter: " + dlList.getNodeCounter()); DoublyLinkedList dlList2 = new DoublyLinkedList(); try { // No exception generated, code silently skips request. dlList2.deleteNode(listNode1); } catch (Exception e) { System.out.println("deleting node from empty list"); e.printStackTrace(); } // end try. // test empty list section of insertNode(). dlList2.insertNode(listNode9, listNode1, after); // modified to createPrintList() to state "List is empty" and it is. int count = dlList2.getNodeCounter(); System.out.println("count: " + count); dlList2.printList(); // sc.close(); } // end method main. } // end class MakeListApp. <file_sep>/ProperStack/src/MakeProperStackApp.java public class MakeProperStackApp { public static void main(String args[]) { System.out.println("in MakeProperStackApp.main"); // test StackNode constructor and setPayload methods. StackNode node01 = new StackNode(); node01.setPayload(120); StackNode node02 = new StackNode(); node02.setPayload(44); StackNode node03 = new StackNode(); node03.setPayload(53); StackNode node04 = new StackNode(); node04.setPayload(6); // test ProperStackLifo constructor. ProperStackLifo firstStack = new ProperStackLifo(); // test stackEmpty method when stack is empty. if (firstStack.stackEmpty()) { System.out.println("stack is empty"); } else { System.out.println("stack is NOT empty"); } // end if. // test stackPush, stackPop methods. firstStack.stackPush(node01); firstStack.stackPush(node02); firstStack.stackPush(node03); firstStack.stackPush(node04); firstStack.stackPop(); // test stackEmpty method when stack is NOT empty. if (firstStack.stackEmpty()) { System.out.println("stack is empty"); } else { System.out.println("stack is NOT empty"); } // end if. } // end main. } // end class <file_sep>/List/src/DoublyLinkedList.java /** * class DoublyLinkedList * - contains references to LLNode objects at head and tail of List. * * @author <NAME> * @version 1.1 09/20/2017 */ public class DoublyLinkedList { private LLNode head; private LLNode tail; private int nodeCounter = 0; // no-args constructor. public DoublyLinkedList() { } // end constructor. /** * method printList * - prints entire contents of current list, one line per element. */ public void printList() { StringBuffer list = createPrintList(); System.out.println(list); } // end printList. /** * method createPrintList * - creates and returns a StringBuffer object containing the print string: * the entire contents of current list, one line per element. * @return printString StringBuffer */ public StringBuffer createPrintList() { StringBuffer printString = new StringBuffer(); int ct = 1; LLNode node; printString.append("\n"); if (!listEmpty()) { while (ct <= nodeCounter) { node = searchByPosition(ct); printString.append("ct: " + ct + " - payload: " + node.getPayload()); printString.append("\n"); ct++; } // end while. } else { printString.append("List is empty"); } // end if/else. printString.append("\n"); return printString; } // end printList. /** * method insertNode * - accepts new LLNode, neighbor LLNode, and before/after value. * - adds the new node before or after the neighbor as specified. * @param node LLNode * @param neighbor LLNode * @param ba String */ public void insertNode(LLNode node, LLNode neighbor, String ba) { LLNode neighborLast; LLNode neighborNext; if (nodeCounter == 0) { // list was empty, new node becomes head and tail. head = node; tail = node; } else { if (ba == "before") { if (neighbor != head) { node.setNext(neighbor); neighborLast = neighbor.getLast(); node.setLast(neighborLast); neighborLast.setNext(node); neighbor.setLast(node); } else { // there is no before-partner when neighbor is head. node.setNext(neighbor); neighbor.setLast(node); // node is new head. head = node; } // end if. } else { // after. if (neighbor != tail) { node.setLast(neighbor); neighborNext = neighbor.getNext(); node.setNext(neighborNext); neighbor.setNext(node); neighborNext.setLast(node); } else { // there is no after-partner when neighbor is tail. node.setLast(neighbor); neighbor.setNext(node); // node is new tail. tail = node; } // end if. } // end before or after. } // end if. nodeCounter++; } // end insertNode. /** * method insertNewHead() * - accepts a node and adds it to the head (entry-point) * of the List. * - ignore this method and code one per WKK description. * @param node LLNode */ public void insertNewHead (LLNode node) { if (nodeCounter == 0) { head = node; tail = node; } else { // set incoming node next-ref to existing head. node.setNext(head); // set existing head last-ref to incoming node. head.setLast(node); // set head to incoming node. // tail is not affected by insert. head = node; } // end if. nodeCounter++; } // end insertNewHead. /** * method deleteNode() * - accepts a node, does a search to locate it in list, * and then deletes it by position. * @param node * @return */ public void deleteNode(LLNode node) { LLNode neighbor; LLNode beforeNode; LLNode afterNode; if (!listEmpty()) { if (node == head) { neighbor = node.getNext(); // this removes ref to current head. neighbor.setLast(null); // neighbor becomes the new head. head = neighbor; } else if (node == tail) { neighbor = node.getLast(); // this removes ref to current tail. neighbor.setNext(null); // neighbor becomes the new tail. tail = neighbor; } else { beforeNode = node.getLast(); afterNode = node.getNext(); // this removes node from the list. beforeNode.setNext(afterNode); afterNode.setLast(beforeNode); } // end conditions. // reduce the node count in the list. nodeCounter--; } // end list not empty. } // end deleteNode. /** * method searchByNode() * - accepts LLNode * - then does a search to locate that value in the list * and return a int position value. * - will return a -1 when the list is empty, or when * the node is not found in the list. * @param node LLNode * @return position int */ public int searchByNode(LLNode node) { int position = -1; // initialize to a non-position value. int compareCounter = 1; LLNode compareNode = head; boolean match = false; if (!listEmpty()) { while ((compareNode != tail) && (!match)){ if (compareNode == node) { match = true; position = compareCounter; } else { LLNode next = compareNode.getNext(); compareNode = next; compareCounter++; } // end if/else. } // end while. if (!match) { if (tail == node) { position = compareCounter; } // end if. } // end if. } // end if. return position; } // end searchByNode. /** * method searchByPosition * - accepts an int value for position * - returns the node at that position in the list, as long * as position value is LTE the nodeCounter value * @param pos int * @return LLNode node */ public LLNode searchByPosition(int pos) { LLNode node = null; int counter = 1; boolean match = false; if (pos <= nodeCounter) { // then I can return a node. node = head; while ((counter <= nodeCounter) && (!match)) { if (pos == counter) { match = true; } else { LLNode next = node.getNext(); node = next; counter++; } // end if/else. } // end while. } // end if. // if pos exceeds nodeCounter then returned node is null. return node; } // end searchByPosition. /** * method getHead() * @return LLNode */ public LLNode getHead() { return head; } // end getHead. /** * method getTail() * @return LLNode */ public LLNode getTail() { return tail; } // end getTail. /** * method getNodeCounter() * @return int */ public int getNodeCounter() { return nodeCounter; } // end getNodeCounter. public boolean listEmpty() { return (nodeCounter == 0); } // end listEmpty. } // end DoublyLinkedList class <file_sep>/Queue/src/MakeQueueApp.java /** * Class MakeQueueApp * - instantiates QueueNode objects and adds them to a QueueFifo object * using QueueFifo methods. * - test calls QueueFifo methods as unit testing. * * @author <NAME> * @version 1.0 09/02/2017 */ public class MakeQueueApp { public static void main(String args[]){ System.out.println("in MakeQueueApp.main"); // test no-args QueueNode constructor. QueueNode node01 = new QueueNode(); node01.setPayload(168); // test data QueueNode constructor and setData methods. QueueNode node02 = new QueueNode(5); QueueNode node03 = new QueueNode(70); QueueNode node04 = new QueueNode(54); // test no-args QueueFifo constructor, enqueue and dequeue methods. QueueFifo firstQueue = new QueueFifo(); // test queueEmpty method when empty. if (firstQueue.queueEmpty()) { System.out.println("queue is empty"); } else { System.out.println("queue is NOT empty"); } // end if. firstQueue.enqueue(node01); firstQueue.enqueue(node02); firstQueue.enqueue(node03); firstQueue.enqueue(node04); firstQueue.dequeue(); // test node QueueFifo constructor. QueueFifo nextQueue = new QueueFifo(node01); // test queueEmpty method when NOT empty. if (nextQueue.queueEmpty()) { System.out.println("queue is empty"); } else { System.out.println("queue is NOT empty"); } // end if. } // end main } // end class <file_sep>/ProperStack/test/StackNodeTest.java import junit.framework.TestCase; public class StackNodeTest extends TestCase { public void testSetPayload() throws Exception { StackNode n = new StackNode(); n.setPayload(42); assertEquals(n.getPayload(), 42); } public void testGetPayload() throws Exception { StackNode n = new StackNode(); n.setPayload(42); assertEquals(n.getPayload(), 42); } public void testSetLast() throws Exception { StackNode n = new StackNode(); StackNode n2 = new StackNode(); n.setLast(n2); assertEquals(n.getLast(), n2); } public void testGetLast() throws Exception { StackNode n = new StackNode(); StackNode n2 = new StackNode(); n.setLast(n2); assertEquals(n.getLast(), n2); } }<file_sep>/Queue/src/QueueNode.java /** * Class QueueNode * - contains an int as the payload (which could be any data type.) * - contains a QueueNode object that only references its predecessor. * - contains get/set methods for the two variables. * * @author <NAME> * @version 1.0 09/02/2017 */ public class QueueNode { private int payload; private QueueNode last; // constructor1 - no args. public QueueNode() { System.out.println("in QueueNode no-args constructor"); }; // constructor2 - single int arg. public QueueNode(int data) { System.out.println("in QueueNode int arg constructor"); payload = data; } // end constructor2. /** * method setPayload sets private int value for node. * @param data - the integer value */ public void setPayload(int data){ System.out.println("in QueueNode.setPayload"); payload = data; } // end setPayload. /** * method getPayload returns private int value for node. * @return int */ public int getPayload() { return payload; } // end get Payload. /** * method setLast sets private int value for node. * @param node - the node being acted upon. */ public void setLast(QueueNode node){ System.out.println("in QueueNode.setLast"); last = node; } // end set last. /** * method getLast returns private int value for node. * @return QueueNode */ public QueueNode getLast() { return last; } // end get last. } // end class. <file_sep>/LDList/src/MakeDoubleListApp.java import java.util.*; import java.io.*; import java.text.*; /** * MakeDoubleListApp class * - main method tests functionality * - static read and write methods * * @author <NAME> 09/25/2017. * @version 1.0 */ public class MakeDoubleListApp { public static void main(String[] args) { System.out.println("in MakeDoubleListApp"); Double dbl = 0.0; int wct = 0; int nct = 0; String after = "after"; String before = "before"; LLDoubleNode dNode; Double dPayload = 0.0; Scanner fileIn; File dblFile; FileReader frInput; BufferedReader bufInput; File outputFile; FileWriter fwOutput; BufferedWriter bufOutput; PrintWriter dblOut; // Block 1 - test output of call: LinkedDoublesList doubleList = new LinkedDoublesList(); doubleList = readDoublesFromConsole(); doubleList.printList(); // Second block OK: make a list from doubles in text file. /* try { // dblFile = new File("/Users/jandwyer/Documents/work/CS21-1/LDList/src/dblFile.txt"); dblFile = new File("fileOfDoubles.txt"); if (dblFile.exists()) { System.out.println("Name: " + dblFile.getName()); System.out.println("Readable: " + dblFile.canRead()); } // end if file exists. frInput = new FileReader(dblFile); bufInput = new BufferedReader(frInput); fileIn = new Scanner(bufInput); // read double values from input text file into list. while (fileIn.hasNextDouble()) { LLDoubleNode nextNode = new LLDoubleNode(); LLDoubleNode otherNode = new LLDoubleNode(); dbl = fileIn.nextDouble(); nextNode.setPayload(dbl); if (wct == 0) { dblList.insertNode(nextNode, otherNode, after); } else { otherNode = dblList.getHead(); dblList.insertNode(nextNode, otherNode, before); } wct++; } dblList.printList(); } catch (Exception e){ System.out.println("Error encountered in read"); e.printStackTrace(); } // end try */ // Block 2 - test output of call: LinkedDoublesList dblList = new LinkedDoublesList(); dblList = readDoublesFromFile("fileOfDoubles.txt"); dblList.printList(); // Third block: format to 3 dec places, then write to text file. /* try { outputFile = new File("DblsToThreeDec.txt"); fwOutput = new FileWriter(outputFile, true); bufOutput = new BufferedWriter(fwOutput); dblOut = new PrintWriter(bufOutput); NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(3); nf.setMinimumFractionDigits(3); String strPayload; // loop over dblList and add each payload to output file. nct = dblList.getNodeCounter(); dNode = dblList.getHead(); for (int j = 0; j < nct; j++) { dPayload = dNode.getPayload(); strPayload = nf.format(dPayload); // System.out.println(strPayload); dblOut.println(strPayload); dNode = dNode.getNext(); } // end for loop dblOut.close(); } catch (Exception e){ System.out.println("\nError encountered in write"); e.printStackTrace(); } // end try */ // Block 3 - test output of call: String filename = "listOfDoubles.txt"; writeDoublesToFile(dblList, filename); // need to check the contents of the created file to verify. } // end main. /** * readDoublesFromConsole() static method * - make a list object from doubles entered at console. * @return doubleList LinkedDoublesList */ public static LinkedDoublesList readDoublesFromConsole() { System.out.println("in readDoublesFromConsole()"); System.out.println("\nPlease type in a list of double values, " + "one per line,\n and then finish by typing Command-D: "); LinkedDoublesList doubleList = new LinkedDoublesList(); Scanner processDoubles = new Scanner(System.in); int wct = 0; while (processDoubles.hasNextDouble()) { // these have to be new, each loop. LLDoubleNode newNode = new LLDoubleNode(); LLDoubleNode otherNode = new LLDoubleNode(); double ndbl = processDoubles.nextDouble(); if (wct == 0) { newNode.setPayload(ndbl); doubleList.insertNode(newNode, otherNode, "after"); } else { newNode.setPayload(ndbl); // each next hNode becomes new head otherNode = doubleList.getHead(); doubleList.insertNode(newNode, otherNode, "before"); } wct++; } // end while. processDoubles.close(); return doubleList; } // end readDoublesFromConsole /** * readDoublesFromFile() static method * - make a list of doubles from an input file * @param filename - a String containing the file name * and the path to that file if needed. * @return newLDList LinkedDoublesList */ public static LinkedDoublesList readDoublesFromFile(String filename) { System.out.println("in readDoublesFromFile() - filename: " + filename); LinkedDoublesList dblList = new LinkedDoublesList(); Double dbl = 0.0; int wct = 0; String after = "after"; String before = "before"; Scanner fileIn; File dblFile; FileReader frInput; BufferedReader bufInput; try { dblFile = new File(filename); if (dblFile.exists()) { // TODO: remove this output. System.out.println("Name: " + dblFile.getName()); System.out.println("Readable: " + dblFile.canRead()); } // end if file exists. frInput = new FileReader(dblFile); bufInput = new BufferedReader(frInput); fileIn = new Scanner(bufInput); // read double values from input text file into list. while (fileIn.hasNextDouble()) { LLDoubleNode nextNode = new LLDoubleNode(); LLDoubleNode otherNode = new LLDoubleNode(); dbl = fileIn.nextDouble(); nextNode.setPayload(dbl); if (wct == 0) { dblList.insertNode(nextNode, otherNode, after); } else { otherNode = dblList.getHead(); dblList.insertNode(nextNode, otherNode, before); } wct++; } } catch (Exception e){ System.out.println("Error encountered in read"); e.printStackTrace(); } // end try return dblList; } // end readDoublesFromFile /** * writeDoublesToFile() static method * - Format doubles to 3 dec places, then write to text file, * one per line. * @param ldl - LinkedDoublesList * @return dblOut - reference to a PrintWriter object. */ public static void writeDoublesToFile(LinkedDoublesList ldl, String fileName) { System.out.println("in writeDoublesToFile() - fileName: " + fileName); int nct = 0; LLDoubleNode dNode; Double dPayload = 0.0; File outputFile; FileWriter fwOutput; BufferedWriter bufOutput; PrintWriter dblOut; try { outputFile = new File(fileName); fwOutput = new FileWriter(outputFile, true); bufOutput = new BufferedWriter(fwOutput); dblOut = new PrintWriter(bufOutput); NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(3); nf.setMinimumFractionDigits(3); String strPayload; // loop over dblList and add each payload to output file. nct = ldl.getNodeCounter(); dNode = ldl.getHead(); for (int j = 0; j < nct; j++) { dPayload = dNode.getPayload(); strPayload = nf.format(dPayload); // TODO - remove this output. // System.out.println(strPayload); dblOut.println(strPayload); dNode = dNode.getNext(); } // end for loop dblOut.close(); } catch (Exception e){ System.out.println("\nError encountered in write"); e.printStackTrace(); } // end try // Can't return the PrintWriter object, it's closed. } // end writeDoublesToFile } // end MakeDoubleListApp class
f0d09b05cbc4b426833d507ba51c54657aaf11c8
[ "Java" ]
10
Java
jkdwyer/CS21-1
2abf2036383b81368abe1a4bbd16c6a75f6b4697
668c7ea385909c1e8302fec30b4928892fd3bd32
refs/heads/master
<file_sep>select * from comments where taskid = $1;<file_sep>import React, {Component} from 'react'; import { View, StyleSheet, ImageBackground } from "react-native"; import { Container, Content, Header, ListIcon, } from 'native-base'; export default class SideBar extends Component{ render(){ return( <View> </View> ) } }<file_sep>import React, { Component } from 'react' import DatePicker from 'react-native-datepicker' export default class TaskDatePicker extends Component { constructor(props){ super(props) this.state = {} } render(){ return ( <DatePicker style={{width: 200}} date={this.state.date} mode="datetime" placeholder="Due Date" format="YYYY-MM-DD" minDate="2017-05-01" maxDate="2021-06-01" confirmBtnText="Confirm" cancelBtnText="Cancel" confirmBtnText="Confirm" borderColor='transparent' customStyles={{ dateInput:{borderWidth: 0}}} onDateChange={(date) => {this.setState({date: date})}} /> ) } }<file_sep>module.exports={ addCheckItem: function(req, res){ const taskid = Number(req.params.taskid) console.log(typeof taskid); let item = [ taskid, req.body.content ]; req.app.get('db').addCheckItem(item).then(() => { req.app.get('db').getChecklist([taskid]).then(resp => { res.status(200).send(resp); }); }); }, addComment: function(req, res){ console.log('add comment endpoint hit') const taskid = Number(req.params.taskid); let comment = [ taskid, req.body.userid, req.body.content ]; req.app.get('db').addComment(comment).then(() => { req.app.get('db').getComments([taskid]).then(resp => { res.status(200).send(resp); }); }); }, editTask: function(req, res){ const taskid = Number(req.params.taskid); let task = [ taskid, req.body.taskname, req.body.duedate, req.body.starttime, req.body.description, req.body.completed, req.body.color, req.body.isrecurring, req.body.duration ]; req.app.get('db').updateTask(task).then(resp => { res.status(200).send(resp); }); }, addTask: function(req, res){ let task = [ req.body.taskname, req.body.duedate, req.body.starttime, req.body.description, req.body.completed, req.body.color, req.body.isrecurring, req.body.duration, req.body.userid ]; req.app.get('db').addTask(task).then(resp => { res.status(200).send(resp); }); } }<file_sep>import React from 'react'; import { StyleSheet, Text, View, Button, Alert, StatusBar, Image, AsyncStorage } from 'react-native'; import { Container, Content } from 'native-base'; import axios from 'axios'; import FooterMenu from './components/Footer/FooterMenu'; import Unscheduled from './components/Unscheduled/Unscheduled'; import TaskDetails from './components/TaskDetails/TaskDetails'; import CalendarScreen from './components/CalendarScreen/CalendarScreen'; import Ongoing from './components/Ongoing/Ongoing'; import SplashScreen from 'react-native-splash-screen'; import LoginScreen from './components/LoginScreen/LoginScreen' import LoadingIndicator from './components/ActivityIndicator/ActivityIndicator' import { auth0, AUTH0_DOMAIN } from './components/Logics/auth0' const PubIpAdress = '192.168.3.176' export default class App extends React.Component { constructor(props) { super(props); this.state = { user: null, userToken: null, showTasks: false, showCalendar: false, showTaskDetails: false, showOngoing: false, selectedDay: '', selectedTask: {}, isLoaded: false, hasToken: false, } this.showMenuItem = this.showMenuItem.bind(this); this.onDayPress = this.onDayPress.bind(this); this.onTaskPress = this.onTaskPress.bind(this); this.loginWindow = this.loginWindow.bind(this); } async componentDidMount() { SplashScreen.hide(); let checkToken = await AsyncStorage.getItem('token').then(res =>{ return res; }).catch(err => console.log(err)); if (checkToken !== null) { console.log('CheckToken data: ', checkToken) this.setState({ hasToken: true, userToken: checkToken }) } } showMenuItem(name) { this.setState({ [name]: !this.state[name] }); } onDayPress(day) { this.setState({ selectedDay: day.dateString }); this.showMenuItem('showCalendar'); } onTaskPress(task, listName) { this.setState({ selectedTask: task }); this.showMenuItem('showTaskDetails'); this.showMenuItem(listName); } loginWindow() { auth0 .webAuth .authorize({ scope: 'openid profile email', useBrowser: true, responseType: 'id_token' }) .then(credentials => { axios.post(`http://${PubIpAdress}:4040/api/auth`, { token: credentials.idToken }).then(res => { AsyncStorage.setItem('token', JSON.stringify(res.data), () => { AsyncStorage.getItem('token', (err, result) => { this.setState({ userToken: result, hasToken: true }) }) }) }).catch(err => console.log(err)); }).catch(err => console.log(err)); } render() { // if (!this.state.isLoaded && !this.state.user) { // return ( // <LoadingIndicator /> // ) // } console.log('state.user: ', this.state.user) console.log('state.hasToken: ', this.state.hasToken) console.log('state.userToken: ', this.state.userToken) if (this.state.userToken && this.state.hasToken) { return ( <Container> <Content> <TaskDetails selectedTask={this.state.selectedTask} /> <CalendarScreen onDayPress={this.onDayPress} visible={this.state.showCalendar} showMenuItem={this.showMenuItem} /> <Unscheduled visible={this.state.showTasks} showMenuItem={this.showMenuItem} onTaskPress={this.onTaskPress} /> <Ongoing visible={this.state.showOngoing} showMenuItem={this.showMenuItem} onTaskPress={this.onTaskPress} /> </Content> <FooterMenu showMenuItem={this.showMenuItem} /> </Container> ) } else { return ( <View style={styles.container}> <StatusBar backgroundColor="#4f6d7a" barStyle="light-content" /> <LoginScreen login={this.loginWindow} /> </View> ) } } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#4f6d7a', alignItems: 'center', justifyContent: 'center', }, text: { color: '#f5fcff', fontSize: 20 } });<file_sep>module.exports = { verifyToken: function(req, res, next){ jwt.verify(req.body.token, AUTH0_CLIENT_SECRET, (err, decoded) => { let db = app.get('db'); if (err){ console.log('Authorization failed', err); next(err); } let { given_name, family_name, email, sub } = decoded; db.checkForUser([sub]).then((resp) => { let user = resp[0]; let id = ''; if (!user){ db.createUser([given_name, family_name, email, sub]).then(resp => { id = resp[0].userid; let token = jwt.sign({ id }, JWT_SECRET, { expiresIn: '7d'}) res.status(200).send(token); }); } else { id = user.id; let token = jwt.sign({ id }, JWT_SECRET, { expiresIn: '7d'}) res.status(200).send(token); } }) }) } }<file_sep>insert into task (taskname, duedate, starttime, description, completed, color, isrecurring, duration, userid) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) returning *;<file_sep>import React, { Component } from 'react'; import { StyleSheet } from 'react-native'; import { Container, Header, Content, Footer, FooterTab, Button, Icon, Text } from 'native-base'; export default class FooterMenu extends Component{ render(){ return( <Footer> <FooterTab> <Button vertical> <Icon name="add" /> </Button> <Button vertical > <Icon name="calendar" onPress={() => this.props.showMenuItem('showCalendar')} /> <Text>Calendar</Text> </Button> <Button vertical onPress={() => this.props.showMenuItem('showTasks')}> <Icon name="clipboard" /> <Text>Tasks</Text> </Button> <Button vertical onPress={() => this.props.showMenuItem('showOngoing')} > <Icon name="paper" /> <Text>WIP</Text> </Button> <Button vertical onPress={() => this.props.showMenuItem('showMenu')}> <Icon name="navigate" /> <Text>Menu</Text> </Button> </FooterTab> </Footer> ) } } <file_sep>select * from task where userid = $1 and starttime is not null and completed = false;<file_sep>select * from task where userid = $1 and starttime is null;
b1f72cbe64fe0838e1892b09628a6909160b3981
[ "JavaScript", "SQL" ]
10
SQL
jordanshort/Final-Group-Project
7e1ed969296ee5a8afdd60e36d69900c91cb52b4
c04ceb713e2e87d517d4d7290881d1029ee7f305
refs/heads/master
<file_sep># Instructions https://argoproj.github.io/docs/argo/demo.html # Minikube Requires Minikube 1.10 or greater. * `minikube start` * `kubectl create namespace argo` * `sudo curl -sSL -o /usr/local/bin/argo https://github.com/argoproj/argo/releases/download/v2.2.1/argo-linux-amd64` * `sudo chmod +x /usr/local/bin/argo` * `kubectl apply -n argo -f https://raw.githubusercontent.com/argoproj/argo/stable/manifests/install.yaml` * `kubectl create rolebinding default-admin --clusterrole=admin --serviceaccount=default:default` * `kubectl -n argo port-forward deployment/argo-server 2746:2746` * go to `http://127.0.0.1:2746/workflows` # Livy * `sudo su -c 'echo -e "$(cat /etc/resolv.conf | grep nameserver | cut -d\ -f2)\tminikube.host" >> /etc/hosts'` * `docker run -p 8998:8998 -e SPARK_MASTER="local[*]" -e DEPLOY_MODE=client davlum/livy:0.7.0-spark2.4.4` * `docker build . -t phillyfan1138/livysubmit:v3` * `docker push phillyfan1138/livysubmit:v3` * `docker run --network="host" -e LOCAL=true phillyfan1138/livysubmit:v3` # Use livy in argo * `argo submit --watch ./basic_task.yaml`<file_sep>import json, pprint, requests, textwrap, time, os if os.getenv("LOCAL") is not None: host = "localhost" else: host = "172.17.0.1" # or whatever is in your /etc/hosts when you `minikube ssh` print("livy host is ", host) host = f"http://{host}:8998" data = {"kind": "spark"} headers = {"Content-Type": "application/json"} r = requests.post(host + "/sessions", data=json.dumps(data), headers=headers) result = r.json() session_url = host + r.headers["location"] statements_url = session_url + "/statements" # {u'state': u'starting', u'id': 0, u'kind': u'spark'} print(result) while result["state"] == "starting": r = requests.get(session_url, headers=headers) result = r.json() print(result) time.sleep(1) print(result) data = {"code": open("spark_test.scala", "r").read()} r = requests.post(statements_url, data=json.dumps(data), headers=headers) pprint.pprint(r.json()) result = r.json() statement_url = host + r.headers["location"] while result["state"] != "available": r = requests.get(statement_url, headers=headers) result = r.json() print(result) time.sleep(1) # statement_url = host + r.headers["location"] r = requests.get(statement_url, headers=headers) pprint.pprint(r.json()) requests.delete(session_url, headers=headers) # {u'id': 1, # u'output': {u'data': {u'text/plain': u'Pi is roughly 3.14004\nNUM_SAMPLES: Int = 100000\ncount: Int = 78501'}, # u'execution_count': 1, # u'status': u'ok'}, # u'state': u'available'} <file_sep>FROM python:alpine3.6 ADD livytest.py livytest.py ADD spark_test.scala spark_test.scala RUN pip install requests
0749514913e1ce2d11dbcc4edc75dd6bc133e201
[ "Markdown", "Python", "Dockerfile" ]
3
Markdown
danielhstahl/argo_example
af954e9d92462aafcb85acba3e8e8e0ae59f5474
207db108396c49e8c46af3cb918a044091d17498
refs/heads/master
<file_sep>using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(ProjetoLuisFE.Startup))] namespace ProjetoLuisFE { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using ProjetoLuisFE.Models; namespace ProjetoLuisFE.Controllers { public class ReservasController : Controller { private Contexto db = new Contexto(); // GET: Reservas public ActionResult Index() { List<Reserva> ListaReservas = db.Reserva.ToList(); foreach (var item in ListaReservas) { if (item.Funcionario_Id != 0) { item.Nome = db.Funcionarios.Where(x => x.FuncionarioId == item.Funcionario_Id).ToList().FirstOrDefault().Nome; item.Usuario = db.Funcionarios.Where(x => x.FuncionarioId == item.Funcionario_Id).ToList().FirstOrDefault().Usuario; item.Setor = db.Funcionarios.Where(x => x.FuncionarioId == item.Funcionario_Id).ToList().FirstOrDefault().Setor; } if (item.Equipamento_Id != 0) { item.EquipamentoNome = db.Equipamento.Where(x => x.EquipamentoId == item.Equipamento_Id).ToList().FirstOrDefault().EquipamentoNome; } } return View(ListaReservas); } // GET: Reservas/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Reserva reserva = db.Reserva.Find(id); if (reserva == null) { return HttpNotFound(); } else { reserva.Nome = db.Funcionarios.Where(x => x.FuncionarioId == reserva.Funcionario_Id).ToList().FirstOrDefault().Nome; reserva.Usuario = db.Funcionarios.Where(x => x.FuncionarioId == reserva.Funcionario_Id).ToList().FirstOrDefault().Usuario; reserva.Setor = db.Funcionarios.Where(x => x.FuncionarioId == reserva.Funcionario_Id).ToList().FirstOrDefault().Setor; reserva.EquipamentoNome = db.Equipamento.Where(x => x.EquipamentoId == reserva.Equipamento_Id).ToList().FirstOrDefault().EquipamentoNome; } return View(reserva); } // GET: Reservas/Create public ActionResult Create() { ViewBag.Funcionarios = db.Funcionarios.ToList().OrderBy(x => x.FuncionarioId); ViewBag.Equipamentos = db.Equipamento.ToList().OrderBy(x => x.EquipamentoId); return View(); } // POST: Reservas/Create // Para proteger-se contra ataques de excesso de postagem, ative as propriedades específicas às quais deseja se associar. // Para obter mais detalhes, confira https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ReservaId,Funcionario_Id,Equipamento_Id")] Reserva reserva) { if (ModelState.IsValid) { db.Reserva.Add(reserva); db.SaveChanges(); return RedirectToAction("Index"); } return View(reserva); } // GET: Reservas/Edit/5 public ActionResult Edit(int? id) { ViewBag.Funcionarios = db.Funcionarios.ToList().OrderBy(x => x.FuncionarioId); ViewBag.Equipamentos = db.Equipamento.ToList().OrderBy(x => x.EquipamentoId); if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Reserva reserva = db.Reserva.Find(id); if (reserva == null) { return HttpNotFound(); } else { reserva.Nome = db.Funcionarios.Where(x => x.FuncionarioId == reserva.Funcionario_Id).ToList().FirstOrDefault().Nome; reserva.Usuario = db.Funcionarios.Where(x => x.FuncionarioId == reserva.Funcionario_Id).ToList().FirstOrDefault().Usuario; reserva.Setor = db.Funcionarios.Where(x => x.FuncionarioId == reserva.Funcionario_Id).ToList().FirstOrDefault().Setor; reserva.EquipamentoNome = db.Equipamento.Where(x => x.EquipamentoId == reserva.Equipamento_Id).ToList().FirstOrDefault().EquipamentoNome; } return View(reserva); } // POST: Reservas/Edit/5 // Para proteger-se contra ataques de excesso de postagem, ative as propriedades específicas às quais deseja se associar. // Para obter mais detalhes, confira https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ReservaId,FuncionarioId,EquipamentoId")] Reserva reserva) { if (ModelState.IsValid) { db.Entry(reserva).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(reserva); } // GET: Reservas/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Reserva reserva = db.Reserva.Find(id); if (reserva == null) { return HttpNotFound(); } else { reserva.Nome = db.Funcionarios.Where(x => x.FuncionarioId == reserva.Funcionario_Id).ToList().FirstOrDefault().Nome; reserva.Usuario = db.Funcionarios.Where(x => x.FuncionarioId == reserva.Funcionario_Id).ToList().FirstOrDefault().Usuario; reserva.Setor = db.Funcionarios.Where(x => x.FuncionarioId == reserva.Funcionario_Id).ToList().FirstOrDefault().Setor; reserva.EquipamentoNome = db.Equipamento.Where(x => x.EquipamentoId == reserva.Equipamento_Id).ToList().FirstOrDefault().EquipamentoNome; } return View(reserva); } // POST: Reservas/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Reserva reserva = db.Reserva.Find(id); db.Reserva.Remove(reserva); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ProjetoLuisFE.Models { public class Reserva { public int ReservaId { get; set; } public int Funcionario_Id { get; set; } public int Equipamento_Id { get; set; } public virtual string Nome { get; set; } public virtual string Usuario { get; set; } public virtual string Setor { get; set; } public virtual string EquipamentoNome { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ProjetoLuisFE.Models { public class Funcionarios { [Key] public int FuncionarioId { get; set; } public string Nome { get; set; } public string Usuario { get; set; } public string Setor { get; set; } public bool Ativo { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace ProjetoLuisFE.Models { public class Contexto : DbContext { public DbSet<Funcionarios> Funcionarios { get; set; } public DbSet<Equipamento> Equipamento { get; set; } public DbSet<Reserva> Reserva { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ProjetoLuisFE.Models { public class Equipamento { [Key] public int EquipamentoId { get; set; } public string EquipamentoNome { get; set; } public string Serie { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using ProjetoLuisFE.Models; namespace ProjetoLuisFE.Controllers { public class EquipamentoesController : Controller { private Contexto db = new Contexto(); // GET: Equipamentoes public ActionResult Index() { return View(db.Equipamento.ToList()); } // GET: Equipamentoes/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Equipamento equipamento = db.Equipamento.Find(id); if (equipamento == null) { return HttpNotFound(); } return View(equipamento); } // GET: Equipamentoes/Create public ActionResult Create() { return View(); } // POST: Equipamentoes/Create // Para proteger-se contra ataques de excesso de postagem, ative as propriedades específicas às quais deseja se associar. // Para obter mais detalhes, confira https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "EquipamentoId,EquipamentoNome,Serie")] Equipamento equipamento) { if (ModelState.IsValid) { db.Equipamento.Add(equipamento); db.SaveChanges(); return RedirectToAction("Index"); } return View(equipamento); } // GET: Equipamentoes/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Equipamento equipamento = db.Equipamento.Find(id); if (equipamento == null) { return HttpNotFound(); } return View(equipamento); } // POST: Equipamentoes/Edit/5 // Para proteger-se contra ataques de excesso de postagem, ative as propriedades específicas às quais deseja se associar. // Para obter mais detalhes, confira https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "EquipamentoId,EquipamentoNome,Serie")] Equipamento equipamento) { if (ModelState.IsValid) { db.Entry(equipamento).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(equipamento); } // GET: Equipamentoes/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Equipamento equipamento = db.Equipamento.Find(id); if (equipamento == null) { return HttpNotFound(); } return View(equipamento); } // POST: Equipamentoes/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Equipamento equipamento = db.Equipamento.Find(id); db.Equipamento.Remove(equipamento); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
08c9555d66d1301e3ffe0fd3f43e12a83f7aa4fb
[ "C#" ]
7
C#
luisfelix-93/projetoEquipamento
19db0edf475de427c6491dca352cefccae9fee3b
c8c2ff4769f37ab908ed10406dfa5e28be894214
refs/heads/master
<file_sep>#ifndef ERIZO_SRC_ERIZO_DTLS_CONFIG_H_ #define ERIZO_SRC_ERIZO_DTLS_CONFIG_H_ typedef unsigned char UInt8; typedef unsigned short UInt16; // NOLINT(runtime/int) typedef unsigned int UInt32; // NOLINT(runtime/int) typedef unsigned long long UInt64; // NOLINT(runtime/int) #endif // ERIZO_SRC_ERIZO_DTLS_CONFIG_H_ <file_sep>/*global require, describe, it, beforeEach, afterEach*/ 'use strict'; var mocks = require('../utils'); var request = require('supertest'); var express = require('express'); var sinon = require('sinon'); var bodyParser = require('body-parser'); var kArbitraryRoom = {'_id': '1', name: '', options: {p2p: true, data: ''}}; var kArbitraryService = {'_id': '1', rooms: [kArbitraryRoom]}; var kArbtiraryUser = {name: '1'}; describe('Users Resource', function() { var app, usersResource, serviceRegistryMock, nuveAuthenticatorMock, setServiceStub, cloudHandlerMock; beforeEach(function() { mocks.start(mocks.licodeConfig); cloudHandlerMock = mocks.start(mocks.cloudHandler); serviceRegistryMock = mocks.start(mocks.serviceRegistry); nuveAuthenticatorMock = mocks.start(mocks.nuveAuthenticator); setServiceStub = sinon.stub(); usersResource = require('../../resource/usersResource'); app = express(); app.use(bodyParser.json()); app.all('*', function(req, res, next) { req.service = setServiceStub(); next(); }); app.get('/rooms/:room/users', usersResource.getList); }); afterEach(function() { mocks.stop(mocks.licodeConfig); mocks.stop(cloudHandlerMock); mocks.stop(serviceRegistryMock); mocks.stop(nuveAuthenticatorMock); mocks.deleteRequireCache(); mocks.reset(); }); describe('Get List', function() { it('should fail if service is not present', function(done) { serviceRegistryMock.getRoomForService.callsArgWith(2, kArbitraryRoom); request(app) .get('/rooms/1/users') .expect(404, 'Service not found') .end(function(err) { if (err) throw err; done(); }); }); it('should fail if room is not found', function(done) { serviceRegistryMock.getRoomForService.callsArgWith(2, undefined); setServiceStub.returns(kArbitraryService); request(app) .get('/rooms/1/users') .expect(404, 'Room does not exist') .end(function(err) { if (err) throw err; done(); }); }); it('should fail if CloudHandler does not respond', function(done) { serviceRegistryMock.getRoomForService.callsArgWith(2, kArbitraryRoom); setServiceStub.returns(kArbitraryService); cloudHandlerMock.getUsersInRoom.callsArgWith(1, 'error'); request(app) .get('/rooms/1/users') .expect(401, 'CloudHandler does not respond') .end(function(err) { if (err) throw err; done(); }); }); it('should succeed if user exists', function(done) { serviceRegistryMock.getRoomForService.callsArgWith(2, kArbitraryRoom); setServiceStub.returns(kArbitraryService); cloudHandlerMock.getUsersInRoom.callsArgWith(1, [kArbtiraryUser]); request(app) .get('/rooms/1/users') .expect(200, JSON.stringify([kArbtiraryUser])) .end(function(err) { if (err) throw err; done(); }); }); }); }); <file_sep>#ifndef ERIZO_SRC_ERIZO_THREAD_WORKER_H_ #define ERIZO_SRC_ERIZO_THREAD_WORKER_H_ #include <boost/asio.hpp> #include <boost/thread.hpp> #include <chrono> // NOLINT #include <memory> #include <vector> #include "thread/Scheduler.h" namespace erizo { class Worker : public std::enable_shared_from_this<Worker> { public: typedef std::unique_ptr<boost::asio::io_service::work> asio_worker; typedef std::function<void()> Task; explicit Worker(std::weak_ptr<Scheduler> scheduler); ~Worker(); void task(Task f); void start(); void close(); int scheduleFromNow(Task f, std::chrono::milliseconds delta_ms); void unschedule(int uuid); private: std::function<void()> safeTask(std::function<void(std::shared_ptr<Worker>)> f); bool isCancelled(int uuid); private: std::weak_ptr<Scheduler> scheduler_; boost::asio::io_service service_; asio_worker service_worker_; boost::thread_group group_; std::atomic<bool> closed_; int next_scheduled_ = 0; std::vector<int> cancelled_; mutable std::mutex cancel_mutex_; }; } // namespace erizo #endif // ERIZO_SRC_ERIZO_THREAD_WORKER_H_ <file_sep>/*global require, exports, setInterval, clearInterval*/ 'use strict'; var addon = require('./../../erizoAPI/build/Release/addon'); var logger = require('./../common/logger').logger; var amqper = require('./../common/amqper'); // Logger var log = logger.getLogger('ErizoJSController'); exports.ErizoJSController = function (threadPool) { var that = {}, // {id: {subsId1: wrtc1, subsId2: wrtc2}} subscribers = {}, // {id: {muxer: OneToManyProcessor, wrtc: WebRtcConnection} publishers = {}, // {id: ExternalOutput} externalOutputs = {}, SLIDESHOW_TIME = 1000, PLIS_TO_RECOVER = 3, initWebRtcConnection, closeWebRtcConnection, getSdp, getRoap, CONN_INITIAL = 101, // CONN_STARTED = 102, CONN_GATHERED = 103, CONN_READY = 104, CONN_FINISHED = 105, CONN_CANDIDATE = 201, CONN_SDP = 202, CONN_FAILED = 500, WARN_NOT_FOUND = 404, WARN_CONFLICT = 409, WARN_PRECOND_FAILED = 412, WARN_BAD_CONNECTION = 502; /* * Given a WebRtcConnection waits for the state CANDIDATES_GATHERED for set remote SDP. */ initWebRtcConnection = function (wrtc, callback, idPub, idSub, options) { log.debug('message: Init WebRtcConnection, id: ' + wrtc.wrtcId + ', ' + logger.objectToLog(options)); if (options.metadata) { wrtc.setMetadata(JSON.stringify(options.metadata)); wrtc.metadata = options.metadata; } if (wrtc.minVideoBW) { var monitorMinVideoBw = {}; if (wrtc.scheme) { try{ monitorMinVideoBw = require('./adapt_schemes/' + wrtc.scheme) .MonitorSubscriber(log); } catch (e) { log.warn('message: could not find custom adapt scheme, ' + 'code: ' + WARN_PRECOND_FAILED + ', ' + 'id:' + wrtc.wrtcId + ', ' + 'scheme: ' + wrtc.scheme + ', ' + logger.objectToLog(options.metadata)); monitorMinVideoBw = require('./adapt_schemes/notify').MonitorSubscriber(log); } } else { monitorMinVideoBw = require('./adapt_schemes/notify').MonitorSubscriber(log); } monitorMinVideoBw(wrtc, callback, idPub, idSub, options, that); } if (GLOBAL.config.erizoController.report.rtcp_stats) { // jshint ignore:line log.debug('message: RTCP Stat collection is active'); wrtc.getStats(function (newStats) { var timeStamp = new Date(); amqper.broadcast('stats', {pub: idPub, subs: idSub, stats: JSON.parse(newStats), timestamp:timeStamp.getTime()}); }); } wrtc.init(function (newStatus, mess) { log.info('message: WebRtcConnection status update, ' + 'id: ' + wrtc.wrtcId + ', status: ' + newStatus + ', ' + logger.objectToLog(options.metadata)); if (GLOBAL.config.erizoController.report.connection_events) { //jshint ignore:line var timeStamp = new Date(); amqper.broadcast('event', {pub: idPub, subs: idSub, type: 'connection_status', status: newStatus, timestamp:timeStamp.getTime()}); } switch(newStatus) { case CONN_INITIAL: callback('callback', {type: 'started'}); break; case CONN_SDP: case CONN_GATHERED: mess = mess.replace(that.privateRegexp, that.publicIP); if (options.createOffer) callback('callback', {type: 'offer', sdp: mess}); else callback('callback', {type: 'answer', sdp: mess}); break; case CONN_CANDIDATE: mess = mess.replace(that.privateRegexp, that.publicIP); callback('callback', {type: 'candidate', candidate: mess}); break; case CONN_FAILED: log.warn('message: failed the ICE process, ' + 'code: ' + WARN_BAD_CONNECTION + ', id: ' + wrtc.wrtcId); callback('callback', {type: 'failed', sdp: mess}); break; case CONN_READY: log.debug('message: connection ready, ' + 'id: ' + wrtc.wrtcId + ', ' + 'status: ' + newStatus); // If I'm a subscriber and I'm bowser, I ask for a PLI if (idSub && options.browser === 'bowser') { publishers[idPub].wrtc.generatePLIPacket(); } if (options.slideShowMode === true) { that.setSlideShow(true, idSub, idPub); } callback('callback', {type: 'ready'}); break; } }); if (options.createOffer === true) { log.debug('message: create offer requested, id:', wrtc.wrtcId); var audioEnabled = true; var videoEnabled = true; var bundle = true; wrtc.createOffer(audioEnabled, videoEnabled, bundle); } callback('callback', {type: 'initializing'}); }; closeWebRtcConnection = function (wrtc) { var associatedMetadata = wrtc.metadata || {}; wrtc.close(); log.info('message: WebRtcConnection status update, ' + 'id: ' + wrtc.wrtcId + ', status: ' + CONN_FINISHED + ', ' + logger.objectToLog(associatedMetadata)); }; /* * Gets SDP from roap message. */ getSdp = function (roap) { var reg1 = new RegExp(/^.*sdp\":\"(.*)\",.*$/), sdp = roap.match(reg1)[1], reg2 = new RegExp(/\\r\\n/g); sdp = sdp.replace(reg2, '\n'); return sdp; }; /* * Gets roap message from SDP. */ getRoap = function (sdp, offerRoap) { var reg1 = new RegExp(/\n/g), offererSessionId = offerRoap.match(/("offererSessionId":)(.+?)(,)/)[0], answererSessionId = '106', answer = ('\n{\n \"messageType\":\"ANSWER\",\n'); sdp = sdp.replace(reg1, '\\r\\n'); //var reg2 = new RegExp(/^.*offererSessionId\":(...).*$/); //var offererSessionId = offerRoap.match(reg2)[1]; answer += ' \"sdp\":\"' + sdp + '\",\n'; //answer += ' \"offererSessionId\":' + offererSessionId + ',\n'; answer += ' ' + offererSessionId + '\n'; answer += ' \"answererSessionId\":' + answererSessionId + ',\n \"seq\" : 1\n}\n'; return answer; }; that.addExternalInput = function (from, url, callback) { if (publishers[from] === undefined) { var eiId = from + '_' + url; log.info('message: Adding ExternalInput, id: ' + eiId); var muxer = new addon.OneToManyProcessor(), ei = new addon.ExternalInput(url); ei.wrtcId = eiId; publishers[from] = {muxer: muxer}; subscribers[from] = {}; ei.setAudioReceiver(muxer); ei.setVideoReceiver(muxer); muxer.setExternalPublisher(ei); var answer = ei.init(); if (answer >= 0) { callback('callback', 'success'); } else { callback('callback', answer); } } else { log.warn('message: Publisher already set, code: ' + WARN_CONFLICT + ', id: ' + from); } }; that.addExternalOutput = function (to, url) { if (publishers[to] !== undefined) { var eoId = url + '_' + to; log.info('message: Adding ExternalOutput, id: ' + eoId); var externalOutput = new addon.ExternalOutput(url); externalOutput.wrtcId = eoId; externalOutput.init(); publishers[to].muxer.addExternalOutput(externalOutput, url); externalOutputs[url] = externalOutput; } }; that.removeExternalOutput = function (to, url) { if (externalOutputs[url] !== undefined && publishers[to] !== undefined) { log.info('message: Stopping ExternalOutput, id: ' + externalOutputs[url].wrtcId); publishers[to].muxer.removeSubscriber(url); delete externalOutputs[url]; } }; that.processSignaling = function (streamId, peerId, msg) { log.info('message: Process Signaling message, ' + 'streamId: ' + streamId + ', peerId: ' + peerId); if (publishers[streamId] !== undefined) { if (subscribers[streamId][peerId]) { if (msg.type === 'offer') { subscribers[streamId][peerId].setRemoteSdp(msg.sdp); } else if (msg.type === 'candidate') { subscribers[streamId][peerId].addRemoteCandidate(msg.candidate.sdpMid, msg.candidate.sdpMLineIndex, msg.candidate.candidate); } else if (msg.type === 'updatestream') { if(msg.sdp) subscribers[streamId][peerId].setRemoteSdp(msg.sdp); if (msg.config) { if (msg.config.slideShowMode !== undefined) { that.setSlideShow(msg.config.slideShowMode, peerId, streamId); } } } } else { if (msg.type === 'offer') { publishers[streamId].wrtc.setRemoteSdp(msg.sdp); } else if (msg.type === 'candidate') { publishers[streamId].wrtc.addRemoteCandidate(msg.candidate.sdpMid, msg.candidate.sdpMLineIndex, msg.candidate.candidate); } else if (msg.type === 'updatestream') { if (msg.sdp) { publishers[streamId].wrtc.setRemoteSdp(msg.sdp); } if (msg.config) { if (msg.config.minVideoBW) { log.debug('message: updating minVideoBW for publisher, ' + 'id: ' + publishers[streamId].wrtcId + ', ' + 'minVideoBW: ' + msg.config.minVideoBW); publishers[streamId].minVideoBW = msg.config.minVideoBW; for (var sub in subscribers[streamId]) { var theConn = subscribers[streamId][sub]; theConn.minVideoBW = msg.config.minVideoBW * 1000; // bps theConn.lowerThres = Math.floor(theConn.minVideoBW*(1-0.2)); theConn.upperThres = Math.ceil(theConn.minVideoBW*(1+0.1)); } } } } } } }; /* * Adds a publisher to the room. This creates a new OneToManyProcessor * and a new WebRtcConnection. This WebRtcConnection will be the publisher * of the OneToManyProcessor. */ that.addPublisher = function (from, options, callback) { var muxer; var wrtc; if (publishers[from] === undefined) { log.info('message: Adding publisher, ' + 'streamId: ' + from + ', ' + logger.objectToLog(options) + ', ' + logger.objectToLog(options.metadata)); var wrtcId = from; muxer = new addon.OneToManyProcessor(); wrtc = new addon.WebRtcConnection(threadPool, wrtcId, GLOBAL.config.erizo.stunserver, GLOBAL.config.erizo.stunport, GLOBAL.config.erizo.minport, GLOBAL.config.erizo.maxport, false, JSON.stringify(GLOBAL.mediaConfig), GLOBAL.config.erizo.turnserver, GLOBAL.config.erizo.turnport, GLOBAL.config.erizo.turnusername, GLOBAL.config.erizo.turnpass); wrtc.wrtcId = wrtcId; publishers[from] = {muxer: muxer, wrtc: wrtc, minVideoBW: options.minVideoBW, scheme: options.scheme}; subscribers[from] = {}; wrtc.setAudioReceiver(muxer); wrtc.setVideoReceiver(muxer); muxer.setPublisher(wrtc); initWebRtcConnection(wrtc, callback, from, undefined, options); } else { if (Object.keys(subscribers[from]).length === 0) { log.warn('message: publisher already set but no subscribers will republish, ' + 'code: ' + WARN_CONFLICT + ', streamId: ' + from + ', ' + logger.objectToLog(options.metadata)); wrtc = new addon.WebRtcConnection(threadPool, from, GLOBAL.config.erizo.stunserver, GLOBAL.config.erizo.stunport, GLOBAL.config.erizo.minport, GLOBAL.config.erizo.maxport, false, JSON.stringify(GLOBAL.mediaConfig), GLOBAL.config.erizo.turnserver, GLOBAL.config.erizo.turnport, GLOBAL.config.erizo.turnusername, GLOBAL.config.erizo.turnpass); muxer = publishers[from].muxer; publishers[from].wrtc = wrtc; wrtc.setAudioReceiver(muxer); wrtc.setVideoReceiver(muxer); muxer.setPublisher(wrtc); initWebRtcConnection(wrtc, callback, from, undefined, options); }else{ log.warn('message: publisher already set has subscribers will ignore, ' + 'code: ' + WARN_CONFLICT + ', streamId: ' + from); } } }; /* * Adds a subscriber to the room. This creates a new WebRtcConnection. * This WebRtcConnection will be added to the subscribers list of the * OneToManyProcessor. */ that.addSubscriber = function (from, to, options, callback) { if (publishers[to] === undefined) { log.warn('message: addSubscriber to unknown publisher, ' + 'code: ' + WARN_NOT_FOUND + ', streamId: ' + to + ', clientId: ' + from + ', ' + logger.objectToLog(options.metadata)); //We may need to notify the clients return; } if (subscribers[to][from] !== undefined) { log.warn('message: Duplicated subscription will resubscribe, ' + 'code: ' + WARN_CONFLICT + ', streamId: ' + to + ', clientId: ' + from+ ', ' + logger.objectToLog(options.metadata)); that.removeSubscriber(from,to); } var wrtcId = from + '_' + to; log.info('message: Adding subscriber, id: ' + wrtcId + ', ' + logger.objectToLog(options)+ ', ' + logger.objectToLog(options.metadata)); var wrtc = new addon.WebRtcConnection(threadPool, wrtcId, GLOBAL.config.erizo.stunserver, GLOBAL.config.erizo.stunport, GLOBAL.config.erizo.minport, GLOBAL.config.erizo.maxport, false, JSON.stringify(GLOBAL.mediaConfig), GLOBAL.config.erizo.turnserver, GLOBAL.config.erizo.turnport, GLOBAL.config.erizo.turnusername, GLOBAL.config.erizo.turnpass); wrtc.wrtcId = wrtcId; subscribers[to][from] = wrtc; publishers[to].muxer.addSubscriber(wrtc, from); wrtc.minVideoBW = publishers[to].minVideoBW; log.debug('message: Setting scheme from publisher to subscriber, ' + 'id: ' + wrtcId + ', scheme: ' + publishers[to].scheme+ ', ' + logger.objectToLog(options.metadata)); wrtc.scheme = publishers[to].scheme; initWebRtcConnection(wrtc, callback, to, from, options); }; /* * Removes a publisher from the room. This also deletes the associated OneToManyProcessor. */ that.removePublisher = function (from) { if (subscribers[from] !== undefined && publishers[from] !== undefined) { log.info('message: Removing publisher, id: ' + from); if(publishers[from].periodicPlis!==undefined) { log.debug('message: clearing periodic PLIs for publisher, id: ' + from); clearInterval (publishers[from].periodicPlis); } for (var key in subscribers[from]) { if (subscribers[from].hasOwnProperty(key)) { log.info('message: Removing subscriber, id: ' + subscribers[from][key].wrtcId); closeWebRtcConnection(subscribers[from][key]); } } closeWebRtcConnection(publishers[from].wrtc); publishers[from].muxer.close(function(message) { log.info('message: muxer closed succesfully, ' + 'id: ' + from + ', ' + logger.objectToLog(message)); delete subscribers[from]; delete publishers[from]; var count = 0; for (var k in publishers) { if (publishers.hasOwnProperty(k)) { ++count; } } log.debug('message: remaining publishers, publisherCount: ' + count); if (count === 0) { log.info('message: Removed all publishers. Killing process.'); process.exit(0); } }); } else { log.warn('message: removePublisher that does not exist, ' + 'code: ' + WARN_NOT_FOUND + ', id: ' + from); } }; /* * Removes a subscriber from the room. * This also removes it from the associated OneToManyProcessor. */ that.removeSubscriber = function (from, to) { if (subscribers[to] && subscribers[to][from]) { log.info('message: removing subscriber, id: ' + subscribers[to][from].wrtcId); closeWebRtcConnection(subscribers[to][from]); publishers[to].muxer.removeSubscriber(from); delete subscribers[to][from]; } if (publishers[to] && publishers[to].wrtc.periodicPlis !== undefined) { for (var i in subscribers[to]) { if(subscribers[to][i].slideShowMode === true) { return; } } log.debug('message: clearing Pli interval as no more ' + 'slideshows subscribers are present'); clearInterval(publishers[to].wrtc.periodicPlis); publishers[to].wrtc.periodicPlis = undefined; } }; /* * Removes all the subscribers related with a client. */ that.removeSubscriptions = function (from) { log.info('message: removing subscriptions, peerId:', from); for (var to in subscribers) { if (subscribers.hasOwnProperty(to)) { if (subscribers[to][from]) { log.debug('message: removing subscription, ' + 'id:', subscribers[to][from].wrtcId); closeWebRtcConnection(subscribers[to][from]); publishers[to].muxer.removeSubscriber(from); delete subscribers[to][from]; } } } }; /* * Enables/Disables slideshow mode for a subscriber */ that.setSlideShow = function (slideShowMode, from, to) { var wrtcPub; var theWrtc = subscribers[to][from]; if (!theWrtc) { log.warn('message: wrtc not found for updating slideshow, ' + 'code: ' + WARN_NOT_FOUND + ', id: ' + from + '_' + to); return; } log.debug('message: setting SlideShow, id: ' + theWrtc.wrtcId + ', slideShowMode: ' + slideShowMode); if (slideShowMode === true) { theWrtc.setSlideShowMode(true); theWrtc.slideShowMode = true; wrtcPub = publishers[to].wrtc; if (wrtcPub.periodicPlis === undefined) { wrtcPub.periodicPlis = setInterval(function () { if(wrtcPub) wrtcPub.generatePLIPacket(); }, SLIDESHOW_TIME); } } else { wrtcPub = publishers[to].wrtc; for (var pliIndex = 0; pliIndex < PLIS_TO_RECOVER; pliIndex++) { wrtcPub.generatePLIPacket(); } theWrtc.setSlideShowMode(false); theWrtc.slideShowMode = false; if (publishers[to].wrtc.periodicPlis !== undefined) { for (var i in subscribers[to]) { if (subscribers[to][i].slideShowMode === true) { return; } } log.debug('message: clearing PLI interval for publisher slideShow, ' + 'id: ' + publishers[to].wrtc.wrtcId); clearInterval(publishers[to].wrtc.periodicPlis); publishers[to].wrtc.periodicPlis = undefined; } } }; return that; }; <file_sep>#!/bin/bash ./../erizo/utils/cpplint.py --filter=-legal/copyright,-build/include --linelength=120 *.cc *.h <file_sep>#include <gmock/gmock.h> #include <gtest/gtest.h> #include <thread/Scheduler.h> #include <rtp/RtpRetransmissionHandler.h> #include <rtp/RtpHeaders.h> #include <MediaDefinitions.h> #include <WebRtcConnection.h> #include <vector> static constexpr uint16_t kVideoSsrc = 1; static constexpr uint16_t kAudioSsrc = 2; static constexpr uint16_t kArbitrarySeqNumber = 12; static constexpr uint16_t kFirstSequenceNumber = 0; static constexpr uint16_t kLastSequenceNumber = 65535; using ::testing::_; using ::testing::IsNull; using ::testing::Args; using ::testing::Return; using erizo::dataPacket; using erizo::packetType; using erizo::AUDIO_PACKET; using erizo::VIDEO_PACKET; using erizo::IceConfig; using erizo::RtpMap; using erizo::RtpRetransmissionHandler; using erizo::WebRtcConnection; using erizo::Pipeline; using erizo::InboundHandler; using erizo::OutboundHandler; using erizo::Worker; class MockWebRtcConnection: public WebRtcConnection { public: MockWebRtcConnection(std::shared_ptr<Worker> worker, const IceConfig &ice_config, const std::vector<RtpMap> rtp_mappings) : WebRtcConnection(worker, "", ice_config, rtp_mappings, nullptr) {} virtual ~MockWebRtcConnection() { } }; class Reader : public InboundHandler { public: MOCK_METHOD2(read, void(Context*, std::shared_ptr<dataPacket>)); }; class Writer : public OutboundHandler { public: MOCK_METHOD2(write, void(Context*, std::shared_ptr<dataPacket>)); }; class RtpRetransmissionHandlerTest : public ::testing::Test { public: RtpRetransmissionHandlerTest() : ice_config() {} protected: virtual void SetUp() { scheduler = std::make_shared<Scheduler>(1); worker = std::make_shared<Worker>(scheduler); connection = std::make_shared<MockWebRtcConnection>(worker, ice_config, rtp_maps); connection->setVideoSinkSSRC(kVideoSsrc); connection->setAudioSinkSSRC(kAudioSsrc); pipeline = Pipeline::create(); rtx_handler = std::make_shared<RtpRetransmissionHandler>(connection.get()); reader = std::make_shared<Reader>(); writer = std::make_shared<Writer>(); pipeline->addBack(writer); pipeline->addBack(rtx_handler); pipeline->addBack(reader); pipeline->finalize(); } virtual void TearDown() { } std::shared_ptr<dataPacket> createDataPacket(uint16_t seq_number, packetType type) { erizo::RtpHeader *header = new erizo::RtpHeader(); header->setSeqNumber(seq_number); if (type == AUDIO_PACKET) { header->setSSRC(kAudioSsrc); } else { header->setSSRC(kVideoSsrc); } return std::make_shared<dataPacket>(0, reinterpret_cast<char*>(header), sizeof(erizo::RtpHeader), type, 0); } std::shared_ptr<dataPacket> createNack(uint16_t seq_number, packetType type, int additional_packets = 0) { erizo::RtcpHeader *nack = new erizo::RtcpHeader(); nack->setPacketType(RTCP_RTP_Feedback_PT); nack->setBlockCount(1); uint source_ssrc = type == VIDEO_PACKET ? connection->getVideoSinkSSRC() : connection->getAudioSinkSSRC(); uint ssrc = type == VIDEO_PACKET ? connection->getVideoSourceSSRC() : connection->getAudioSourceSSRC(); nack->setSSRC(ssrc); nack->setSourceSSRC(source_ssrc); nack->setNackPid(seq_number); nack->setNackBlp(additional_packets); nack->setLength(3); char *buf = reinterpret_cast<char*>(nack); int len = (nack->getLength() + 1) * 4; return std::make_shared<dataPacket>(0, buf, len, type, 0); } IceConfig ice_config; std::vector<RtpMap> rtp_maps; std::shared_ptr<MockWebRtcConnection> connection; Pipeline::Ptr pipeline; std::shared_ptr<Reader> reader; std::shared_ptr<Writer> writer; std::shared_ptr<RtpRetransmissionHandler> rtx_handler; std::shared_ptr<Worker> worker; std::shared_ptr<Scheduler> scheduler; }; MATCHER_P(HasSequenceNumber, seq_num, "") { return (reinterpret_cast<erizo::RtpHeader*>(std::get<0>(arg)->data))->getSeqNumber() == seq_num; } TEST_F(RtpRetransmissionHandlerTest, basicBehaviourShouldReadPackets) { auto packet = createDataPacket(kArbitrarySeqNumber, VIDEO_PACKET); EXPECT_CALL(*reader.get(), read(_, _)).With(Args<1>(HasSequenceNumber(kArbitrarySeqNumber))).Times(1); pipeline->read(packet); } TEST_F(RtpRetransmissionHandlerTest, basicBehaviourShouldWritePackets) { auto packet = createDataPacket(kArbitrarySeqNumber, VIDEO_PACKET); EXPECT_CALL(*writer.get(), write(_, _)).With(Args<1>(HasSequenceNumber(kArbitrarySeqNumber))).Times(1); pipeline->write(packet); } TEST_F(RtpRetransmissionHandlerTest, shouldRetransmitPackets_whenReceivingNacksWithGoodSeqNum) { auto rtp_packet = createDataPacket(kArbitrarySeqNumber, VIDEO_PACKET); auto nack_packet = createNack(kArbitrarySeqNumber, VIDEO_PACKET); EXPECT_CALL(*writer.get(), write(_, _)).With(Args<1>(HasSequenceNumber(kArbitrarySeqNumber))).Times(2); pipeline->write(rtp_packet); EXPECT_CALL(*reader.get(), read(_, _)).Times(0); pipeline->read(nack_packet); } TEST_F(RtpRetransmissionHandlerTest, shouldNotRetransmitPackets_whenReceivingNacksWithBadSeqNum) { auto rtp_packet = createDataPacket(kArbitrarySeqNumber, VIDEO_PACKET); auto nack_packet = createNack(kArbitrarySeqNumber + 1, VIDEO_PACKET); EXPECT_CALL(*writer.get(), write(_, _)).With(Args<1>(HasSequenceNumber(kArbitrarySeqNumber))).Times(1); EXPECT_CALL(*writer.get(), write(_, _)).With(Args<1>(HasSequenceNumber(kArbitrarySeqNumber + 1))).Times(0); pipeline->write(rtp_packet); EXPECT_CALL(*reader.get(), read(_, _)).Times(1); pipeline->read(nack_packet); } TEST_F(RtpRetransmissionHandlerTest, shouldNotRetransmitPackets_whenReceivingNacksFromDifferentType) { auto rtp_packet = createDataPacket(kArbitrarySeqNumber, VIDEO_PACKET); auto nack_packet = createNack(kArbitrarySeqNumber, AUDIO_PACKET); EXPECT_CALL(*writer.get(), write(_, _)).With(Args<1>(HasSequenceNumber(kArbitrarySeqNumber))).Times(1); pipeline->write(rtp_packet); EXPECT_CALL(*reader.get(), read(_, _)).Times(1); pipeline->read(nack_packet); } TEST_F(RtpRetransmissionHandlerTest, shouldRetransmitPackets_whenReceivingWithSeqNumBeforeGeneralRollover) { auto nack_packet = createNack(kFirstSequenceNumber, VIDEO_PACKET); EXPECT_CALL(*writer.get(), write(_, _)).With(Args<1>(HasSequenceNumber(kLastSequenceNumber))).Times(1); EXPECT_CALL(*writer.get(), write(_, _)).With(Args<1>(HasSequenceNumber(kFirstSequenceNumber))).Times(2); pipeline->write(createDataPacket(kLastSequenceNumber, VIDEO_PACKET)); pipeline->write(createDataPacket(kFirstSequenceNumber, VIDEO_PACKET)); EXPECT_CALL(*reader.get(), read(_, _)).Times(0); pipeline->read(nack_packet); } TEST_F(RtpRetransmissionHandlerTest, shouldRetransmitPackets_whenReceivingWithSeqNumBeforeBufferRollover) { auto nack_packet = createNack(kRetransmissionsBufferSize - 1, VIDEO_PACKET); EXPECT_CALL(*writer.get(), write(_, _)).With(Args<1>(HasSequenceNumber(kRetransmissionsBufferSize))).Times(1); EXPECT_CALL(*writer.get(), write(_, _)).With(Args<1>(HasSequenceNumber(kRetransmissionsBufferSize - 1))).Times(2); pipeline->write(createDataPacket(kRetransmissionsBufferSize - 1, VIDEO_PACKET)); pipeline->write(createDataPacket(kRetransmissionsBufferSize, VIDEO_PACKET)); EXPECT_CALL(*reader.get(), read(_, _)).Times(0); pipeline->read(nack_packet); } TEST_F(RtpRetransmissionHandlerTest, shouldRetransmitPackets_whenReceivingNackWithMultipleSeqNums) { auto nack_packet = createNack(kArbitrarySeqNumber, VIDEO_PACKET, 1); EXPECT_CALL(*writer.get(), write(_, _)).With(Args<1>(HasSequenceNumber(kArbitrarySeqNumber))).Times(2); EXPECT_CALL(*writer.get(), write(_, _)).With(Args<1>(HasSequenceNumber(kArbitrarySeqNumber + 1))).Times(2); pipeline->write(createDataPacket(kArbitrarySeqNumber, VIDEO_PACKET)); pipeline->write(createDataPacket(kArbitrarySeqNumber + 1, VIDEO_PACKET)); EXPECT_CALL(*reader.get(), read(_, _)).Times(0); pipeline->read(nack_packet); } <file_sep>#include "dtls/DtlsTimer.h" #include <sys/time.h> #include <iostream> #ifdef HAVE_CONFIG_H #include "./config.h" #endif using dtls::TestTimerContext; using dtls::DtlsTimer; using dtls::DtlsTimerContext; DtlsTimer::DtlsTimer(unsigned int seq) { mValid = true; } DtlsTimer::~DtlsTimer() {} void DtlsTimer::fire() { if (mValid) { expired(); } else { // memory mangement is overly tricky and possibly wrong...deleted by target // if valid is the contract. weak pointers would help. // delete this; } } void DtlsTimerContext::fire(DtlsTimer *timer) { timer->fire(); } long long getTimeMS() { // NOLINT struct timeval start; gettimeofday(&start, NULL); long timeMs = ((start.tv_sec) * 1000 + start.tv_usec / 1000.0); // NOLINT return timeMs; } TestTimerContext::~TestTimerContext() { if (mTimer) delete mTimer; mTimer = 0; } void TestTimerContext::addTimer(DtlsTimer *timer, unsigned int lifetime) { delete mTimer; mTimer = timer; long timeMs = getTimeMS(); // NOLINT mExpiryTime = timeMs + lifetime; } long long TestTimerContext::getRemainingTime() { // NOLINT long long timeMs = getTimeMS(); // NOLINT if (mTimer) { if (mExpiryTime < timeMs) return(0); return(mExpiryTime - timeMs); } else { #if defined(WIN32) && !defined(__GNUC__) return 18446744073709551615ui64; #else return 18446744073709551615ULL; #endif } } void TestTimerContext::updateTimer() { long long timeMs = getTimeMS(); // NOLINT if (mTimer) { if (mExpiryTime < timeMs) { DtlsTimer *tmpTimer = mTimer; mTimer = 0; fire(tmpTimer); } } } /* ==================================================================== Copyright (c) 2007-2008, <NAME> and <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. None of the contributors names 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. ==================================================================== */ <file_sep>#include "thread/Worker.h" #include <boost/asio.hpp> #include <boost/thread.hpp> #include <memory> using erizo::Worker; Worker::Worker(std::weak_ptr<Scheduler> scheduler) : scheduler_{scheduler}, service_{}, service_worker_{new asio_worker::element_type(service_)}, closed_{false} { } Worker::~Worker() { } void Worker::task(Task f) { service_.post(f); } void Worker::start() { auto this_ptr = shared_from_this(); auto worker = [this_ptr] { if (!this_ptr->closed_) { return this_ptr->service_.run(); } return size_t(0); }; group_.add_thread(new boost::thread(worker)); } void Worker::close() { closed_ = true; service_worker_.reset(); group_.join_all(); service_.stop(); } int Worker::scheduleFromNow(Task f, std::chrono::milliseconds delta_ms) { int uuid = next_scheduled_++; if (auto scheduler = scheduler_.lock()) { scheduler->scheduleFromNow(safeTask([f, uuid](std::shared_ptr<Worker> this_ptr) { this_ptr->task(this_ptr->safeTask([f, uuid](std::shared_ptr<Worker> this_ptr) { std::unique_lock<std::mutex> lock(this_ptr->cancel_mutex_); if (this_ptr->isCancelled(uuid)) { return; } f(); })); }), delta_ms); } return uuid; } void Worker::unschedule(int uuid) { if (uuid < 0) { return; } std::unique_lock<std::mutex> lock(cancel_mutex_); cancelled_.push_back(uuid); } bool Worker::isCancelled(int uuid) { if (std::find(cancelled_.begin(), cancelled_.end(), uuid) != cancelled_.end()) { cancelled_.erase(std::remove(cancelled_.begin(), cancelled_.end(), uuid), cancelled_.end()); return true; } return false; } std::function<void()> Worker::safeTask(std::function<void(std::shared_ptr<Worker>)> f) { std::weak_ptr<Worker> weak_this = shared_from_this(); return [f, weak_this] { if (auto this_ptr = weak_this.lock()) { f(this_ptr); } }; }
cfe2d8292770267d09824bf0bbbe4cb8b5c92978
[ "JavaScript", "C", "C++", "Shell" ]
8
C
KayvanMazaheri/licode
aa299bb986ea2517dd0efcee267f6a20dad2fb8e
fdddccb76d828cda6d02d265cd6bb1cc49885b49
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { MockDataService } from './mock-data.service'; @Component({ selector: 'app-mock-data', templateUrl: './mock-data.component.html', styleUrls: ['./mock-data.component.css'] }) export class MockDataComponent implements OnInit { constructor(private mockDataService: MockDataService) { } ngOnInit(): void { // this.mockDataService.init(); // this.mockDataService.fakeField(); console.log(this.mockDataService.fieldOwnData()); } } <file_sep>import { Injectable } from '@angular/core'; import { mocker } from 'mocker-data-generator'; @Injectable({ providedIn: 'root' }) export class MockDataService { constructor() { } public init(): void { const user = { firstName: { faker: 'name.firstName' }, lastName: { faker: 'name.lastName' }, country: { faker: 'address.country' }, createdAt: { faker: 'date.past' }, username: { function(): void { return ( this.object.lastName.substring(0, 5) + this.object.firstName.substring(0, 3) + Math.floor(Math.random() * 10) ); } } }; const group = { description: { faker: 'lorem.paragraph' }, users: [ { function(): void { return this.faker.random.arrayElement(this.db.user).username; }, length: 10, fixedLength: false } ] }; const conditionalField = { type: { values: ['HOUSE', 'CAR', 'MOTORBIKE'] }, 'object.type=="HOUSE",location': { faker: 'address.city' }, 'object.type=="CAR"||object.type=="MOTORBIKE",speed': { faker: 'random.number' } }; // Using traditional callback Style mocker() .schema('user', user, 2) .schema('group', group, 2) .schema('conditionalField', conditionalField, 2) .build((error, data) => { if (error) { throw error; } console.log('1', data); // This returns an object // { // user:[array of users], // group: [array of groups], // conditionalField: [array of conditionalFields] // } }); // Using promises mocker() .schema('user', user, 2) .schema('group', group, 2) .schema('conditionalField', conditionalField, 2) .build() .then( data => { console.log('2', data); // This returns an object // { // user:[array of users], // group: [array of groups], // conditionalField: [array of conditionalFields] // } }, err => console.error(err) ); // Synchronously // This returns an object // { // user:[array of users], // group: [array of groups], // conditionalField: [array of conditionalFields] // } const dataLog = mocker() .schema('user', user, 2) .schema('group', group, 2) .schema('conditionalField', conditionalField, 2) .buildSync(); console.log('3', dataLog); } public fakeField(): void { const cultivation = { id: { incrementalId: 1 }, name: { faker: 'name.jobTitle' }, }; const field = { id: { incrementalId: 1 }, name: { faker: 'name.title' }, cultivations: [ { faker: 'random.arrayElement(db.cultivation)', // Array config length: 10, fixedLength: false, } ] }; mocker() .schema('field', field, 2) .schema('cultivation', cultivation, 20) .build((error, data) => { if (error) { throw error; } console.log('1', data); }); } public fieldOwnData(): any { const field = { id: 1, name: 'Field 1', cultivations: [] }; for (let index = 0; index < 4; index++) { field.cultivations.push({ id: index + 1, name: `Cultivation ${index + 1}`, phases: [] }); for (let index2 = 0; index2 < 10; index2++) { const randStart = Math.ceil(Math.random() * 10); const randEnd = Math.ceil(Math.random() * 5); const mockStart = new Date(); mockStart.setDate(mockStart.getDate() - randStart); const mockEnd = new Date(mockStart); mockEnd.setDate(mockEnd.getDate() + randEnd); const ranColor = `#${Math.random().toString(16).substr(-6)}`; field.cultivations[index].phases.push({ id: (index2 + 1) + (index * 10), name: `Activity ${(index2 + 1) + (index * 10)}`, color: ranColor, startDate: mockStart, completionDate: mockEnd, }); } } return field; } }
dcf6891f6794ac4856ecc6b08460b892b6bbfbaf
[ "TypeScript" ]
2
TypeScript
LeonScot/abstract-and-generic
f3602280333b8730fca3ea97e02ff1eefc94f546
be5a91d1ad0a3a3de5d28fa0058d9e35138f902c
refs/heads/master
<file_sep>package com.tinyplan.exam.dao; import com.tinyplan.exam.entity.po.User; import java.util.List; public interface TestMapper { List<User> getUser(); } <file_sep>package com.tinyplan.exam.common.constant; public class TokenConstant { // key分隔符 public static final String TOKEN_KEY_SEPARATOR = ":"; // 默认有效时间 public static final int TOKEN_DEFAULT_EXPIRE = 3600; } <file_sep>package com.tinyplan.exam.common.config; import com.tinyplan.exam.common.properties.RedisProperties; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisPassword; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.sql.Connection; /** * Redis 配置 */ @Configuration public class RedisConfig { @Autowired private RedisProperties redisProperties; /** * 连接池参数 * * @return */ @Bean public GenericObjectPoolConfig<Connection> poolConfig() { GenericObjectPoolConfig<Connection> poolConfig = new GenericObjectPoolConfig<>(); poolConfig.setMaxIdle(redisProperties.getMaxIdle()); // genericObjectPoolConfig.setMaxTotal(maxTotal); // genericObjectPoolConfig.setMinIdle(minIdle); poolConfig.setMaxWaitMillis(redisProperties.getMaxWait()); //在borrow一个实例时,是否提前进行validate操作;如果为true,则得到的实例均是可用的 poolConfig.setTestOnBorrow(redisProperties.getTestOnBorrow()); // 在空闲时检查有效性, 默认false // genericObjectPoolConfig.setTestWhileIdle(isTestWhileIdle); return poolConfig; } /** * 连接池代理配置 * * @param poolConfig 连接池参数 * @return */ @Bean public LettuceClientConfiguration lettuceClientConfiguration(GenericObjectPoolConfig<Connection> poolConfig){ return LettucePoolingClientConfiguration.builder() .poolConfig(poolConfig) .build(); } /** * Redis 单机配置 * * @return */ @Bean public RedisStandaloneConfiguration standaloneConfiguration(){ RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(); configuration.setHostName(redisProperties.getHost()); configuration.setPort(redisProperties.getPort()); configuration.setPassword(RedisPassword.of(redisProperties.getPassword())); configuration.setDatabase(redisProperties.getDbIndex()); return configuration; } /** * 连接工厂 * * @param configuration 单机配置 * @param poolConfig 连接池配置 * @return */ @Bean public LettuceConnectionFactory lettuceConnectionFactory(RedisStandaloneConfiguration configuration, LettuceClientConfiguration poolConfig){ LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration, poolConfig); //校验连接是否有效 factory.setValidateConnection(true); factory.afterPropertiesSet(); return factory; } @Bean public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory factory){ return new StringRedisTemplate(factory); } @Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory){ RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); redisTemplate.setEnableTransactionSupport(true); return redisTemplate; } } <file_sep>import cn.hutool.core.date.LocalDateTimeUtil; import org.junit.Test; public class HutoolTest { @Test public void Test(){ System.out.println(LocalDateTimeUtil.format(LocalDateTimeUtil.now(), "yyyy-MM-dd HH:mm:ss")); } } <file_sep>jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ems?useUnicode=true&characterEncoding=UTF-8&&useSSL=false jdbc.username=root jdbc.password=<PASSWORD> jdbc.maxTotal=30 jdbc.maxIdle=10 jdbc.initialSize=5<file_sep>package com.tinyplan.exam.controller; import com.tinyplan.exam.common.annotation.SysLog; import com.tinyplan.exam.common.entity.ApiResult; import com.tinyplan.exam.common.entity.BusinessException; import com.tinyplan.exam.common.entity.ResultStatus; import com.tinyplan.exam.dao.TestMapper; import com.tinyplan.exam.entity.po.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.http.HttpRequest; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.List; @RequestMapping("/login") @RestController public class LoginController { private final TestMapper testMapper; private final StringRedisTemplate stringRedisTemplate; @Autowired public LoginController(TestMapper testMapper, StringRedisTemplate stringRedisTemplate) { this.testMapper = testMapper; this.stringRedisTemplate = stringRedisTemplate; } @GetMapping("/test") @SysLog(module = "测试模块", method = "test()") public ApiResult<List<User>> test() { // stringRedisTemplate.opsForValue().set("status", "15132121"); // stringRedisTemplate.delete("mike"); return new ApiResult<>(ResultStatus.RES_SUCCESS, testMapper.getUser()); } @GetMapping("/tokenTest") public ApiResult<String> tokenTest(HttpServletRequest request) { String token = request.getHeader("Authorization"); if (token == null || "".equals(token)) { token = request.getHeader("x-token"); if (token == null || "".equals(token)) { throw new BusinessException(ResultStatus.RES_ILLEGAL_TOKEN); } else { return new ApiResult<>(ResultStatus.RES_SUCCESS, token); } } else { return new ApiResult<>(ResultStatus.RES_SUCCESS, token); } } } <file_sep>package com.tinyplan.exam.common.properties; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** * JDBC 数据源配置参数 */ @Component @PropertySource("classpath:config/db.properties") public class DBProperties { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Value("${jdbc.maxTotal}") private Integer maxTotal; @Value("${jdbc.maxIdle}") private Integer maxIdle; @Value("${jdbc.initialSize}") private Integer initialSize; public String getDriver() { return driver; } public String getUrl() { return url; } public String getUsername() { return username; } public String getPassword() { return <PASSWORD>; } public Integer getMaxTotal() { return maxTotal; } public Integer getMaxIdle() { return maxIdle; } public Integer getInitialSize() { return initialSize; } }
28813899365f64dcd4cebfd4ff50c6fa671de948
[ "Java", "INI" ]
7
Java
tinyplan/HEMS
d9e6844ea7a1827404314c5a8fe80cc5ee636e2b
2a501ddd664ae8d23d2d7237672c02f6cb3b4dfb
refs/heads/master
<file_sep>import { Component, Input, OnInit } from '@angular/core'; import { ViewController, NavParams } from 'ionic-angular'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { ServicioPersonas } from '../../servicios/servicio.persona'; import { ServicioLocal } from '../../servicios/servicio.local'; import { ServicioRutinas } from '../../servicios/servicio.rutina'; import { Entrenador } from '../../Modelo/entrenador'; import { Cliente } from '../../Modelo/cliente'; import { Gimnasio } from '../../Modelo/gimnasio'; import { Rutina } from '../../Modelo/rutina'; import { AlertController } from 'ionic-angular'; @Component({ selector: 'ver-ejercicio', templateUrl: 'verEjercicio.html' }) export class VerEjercicio implements OnInit { constructor(public viewCtrl: ViewController, private servicioPersonas: ServicioPersonas, private cliente: Cliente, private entrenador: Entrenador, private gimnasio: Gimnasio, public formBuilder: FormBuilder, private servicioLocal: ServicioLocal, private alertCtrl: AlertController, private servicioRutinas: ServicioRutinas, public navParams: NavParams) { } ejercicio; ejercicioAMostrar; series; ngOnInit(): void { var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); this.ejercicio = this.navParams.get('ejercicioSeleccionado'); this.series = []; this.ejercicioAMostrar = JSON.parse(JSON.stringify(this.ejercicio)); for (let i = 0; i < this.ejercicio.series; i++) { if (i === 0) { var serie = { numeroDeSerie: i + 1, repeticiones: this.ejercicioAMostrar.repeticiones, peso: this.ejercicioAMostrar.peso } } else { var serie = { numeroDeSerie: i + 1, repeticiones: this.ejercicioAMostrar.repeticiones += this.ejercicio.cambioRepeticiones, peso: this.ejercicioAMostrar.peso += this.ejercicio.cambioPeso } } this.series.push(serie); } } cerrarModal(): void { this.viewCtrl.dismiss(); } }<file_sep>import { Persona } from './persona'; import { Rutina } from './rutina'; import { Gimnasio } from './gimnasio'; export class Cliente extends Persona { solicitoDieta: boolean; solicitoRutina: boolean; gimnasio: Gimnasio; emailDelEntrenador: string; listaDeRutinas: Rutina []; }<file_sep>import { Component, Input, OnInit } from '@angular/core'; import { ViewController } from 'ionic-angular'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { ServicioEjercicios } from '../../servicios/servicio.ejercicio'; import { ServicioPersonas } from '../../servicios/servicio.persona'; import { ServicioLocal } from '../../servicios/servicio.local'; import { Entrenador } from '../../Modelo/entrenador'; import { Cliente } from '../../Modelo/cliente'; import { Ejercicio } from '../../Modelo/ejercicio'; import { Gimnasio } from '../../Modelo/gimnasio'; import { Alertas } from '../../componentes/alertas/alertas'; @Component({ selector: 'crear-ejercicio', templateUrl: 'crearEjercicio.html' }) export class CrearEjercicio { miForm: FormGroup; infoEjercicio: {nombre: string, series: number, repeticiones: number, peso: number, esCombinado: string, descarga: string, cambioPeso: number, cambioRepeticiones: number, descripcion: string } = { nombre: '', series: 1, repeticiones: 0, peso: 0, esCombinado: null, descarga: '', cambioPeso: 0, cambioRepeticiones: 0, descripcion: ''}; constructor(public viewCtrl: ViewController, private servicioPersonas: ServicioPersonas, private cliente: Cliente, private entrenador: Entrenador, private gimnasio: Gimnasio, public formBuilder: FormBuilder, private servicioLocal: ServicioLocal, private ejercicio: Ejercicio, private servicioEjercicios: ServicioEjercicios, private alerta: Alertas) { this.miForm = this.formBuilder.group({ 'nombre': ['', [Validators.required]], 'series': ['',], 'repeticiones': ['', [Validators.required, this.repeticionesValidator.bind(this)]], 'peso': ['',], 'descarga': ['', [Validators.required]], 'cambioRepeticiones': ['',], 'cambioPeso': ['',], 'esCombinado': ['', [Validators.required]], 'descripcion': ['', [Validators.required]] }); } repeticionesValidator(control: FormControl): {[s: string]: boolean} { if (control.value == 0 || control.value == null) { return {invalidRepeticiones: true}; } } cerrarModal(): void { this.viewCtrl.dismiss(); } isValid(field: string) { let formField = this.miForm.get(field); return formField.valid || formField.pristine; } onSubmit() { var ejercicio = new Ejercicio; var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); ejercicio.emailDelCreador = usuarioRegistrado.email; ejercicio.nombre = this.infoEjercicio.nombre; ejercicio.repeticiones = this.infoEjercicio.repeticiones; ejercicio.series = this.infoEjercicio.series; ejercicio.peso = this.infoEjercicio.peso; ejercicio.descarga = this.infoEjercicio.descarga; ejercicio.cambioRepeticiones = (this.infoEjercicio.descarga === 'noCambio' || this.infoEjercicio.descarga === 'cambioPeso') ? 0 : this.infoEjercicio.cambioRepeticiones; ejercicio.cambioPeso = (this.infoEjercicio.descarga === 'noCambio' || this.infoEjercicio.descarga === 'cambioRepeticiones') ? 0 : this.infoEjercicio.cambioPeso; ejercicio.esCombinado = (this.infoEjercicio.esCombinado == 'true') ? true : false; ejercicio.descripcion = this.infoEjercicio.descripcion; this.servicioEjercicios.setEjercicio(ejercicio); this.alerta.mostrarToast('Se le ha creado el ejercicio con éxito', 'top', 2500); this.viewCtrl.dismiss(); } }<file_sep>import { Component , OnInit} from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { ServicioPersonas } from '../../app/servicios/servicio.persona'; import { ServicioLocal } from '../../app/servicios/servicio.local'; import { Cliente } from '../../app/Modelo/cliente'; import { Entrenador } from '../../app/Modelo/entrenador'; import { Gimnasio } from '../../app/Modelo/gimnasio'; import { Alertas } from '../../app/componentes/alertas/alertas'; import { Page1 } from '../../pages/page1/page1'; import { CrearAsignarRutina} from '../../pages/crearAsignarRutina/crearAsignarRutina'; import { AsignarCliente } from '../../app/componentes/asignarCliente/asignarCliente'; @Component({ selector: 'main-entrenador', templateUrl: 'mainEntrenador.html' }) export class MainEntrenador implements OnInit { constructor(public navCtrl: NavController, private servicioPersonas: ServicioPersonas, private cliente: Cliente, private alertas: Alertas, private entrenador: Entrenador, private servicioLocal: ServicioLocal) {} infoDeEntrenador = this.servicioLocal.getUsuarioRegistrado(); clientesQuePidieronRutina; mostrarClientes; ngOnInit(): void { var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); this.servicioPersonas.getTodosLosClientes().then((clientes) => { this.clientesQuePidieronRutina = clientes.filter(cliente =>{ return cliente.emailDelEntrenador === usuarioRegistrado.email; }); this.clientesQuePidieronRutina = this.clientesQuePidieronRutina.filter(cliente =>{ return cliente.solicitoRutina === true; }); this.mostrarClientes = (this.clientesQuePidieronRutina.length > 0); }); } salir(): void { this.servicioLocal.limpiarUsuario(); this.servicioPersonas.logOut(); setTimeout(() => { this.navCtrl.push(Page1) }, 100); } crearAsignarRutina(): void { this.navCtrl.push(CrearAsignarRutina); } seguirClientes(): void { this.navCtrl.push(AsignarCliente); } } <file_sep>export class ComidasDiarias { desyuno: String; mediaMañana: String; almuerzo: String; merienda: String; cena: String; }<file_sep>import { Component , OnInit} from '@angular/core'; import { NavController } from 'ionic-angular'; import { ServicioPersonas } from '../../app/servicios/servicio.persona'; import { ServicioLocal } from '../../app/servicios/servicio.local'; import { Page1 } from '../../pages/page1/page1'; import { RutinasDeCliente } from '../../pages/rutinasDeCliente/rutinasDeCliente'; import { Alertas } from '../../app/componentes/alertas/alertas'; @Component({ selector: 'main-cliente', templateUrl: 'mainCliente.html' }) export class MainCliente implements OnInit { constructor(public navCtrl: NavController, private servicioPersonas: ServicioPersonas, private servicioLocal: ServicioLocal, private alertas: Alertas) {} infoDeCliente = this.servicioLocal.getUsuarioRegistrado(); ngOnInit(): void { } salir(): void { this.servicioLocal.limpiarUsuario(); this.servicioPersonas.logOut(); setTimeout(() => { this.navCtrl.push(Page1) }, 100); } verRutinas(): void { this.navCtrl.push(RutinasDeCliente); } pedirRutina(): void { this.servicioPersonas.usuarioPideRutina(); this.alertas.mostrarToast('Usted ha solicitado una rutina a su entrenador con éxito.', 'top', 2000); } } <file_sep>import { Storage } from '@ionic/storage'; import { Injectable } from '@angular/core'; import { Cliente } from '../Modelo/cliente'; import { Entrenador } from '../Modelo/entrenador'; import { Ejercicio } from '../Modelo/ejercicio'; import { Rutina } from '../Modelo/rutina'; import { ServicioLocal } from './servicio.local'; import { ServicioPersonas } from './servicio.persona'; @Injectable() export class ServicioRutinas { constructor(private storage: Storage, private ejercicio: Ejercicio, private servicioLocal: ServicioLocal, private servicioPersonas: ServicioPersonas) { } entrenador = this.servicioLocal.getUsuarioRegistrado(); setRutina(rutina: Rutina): void { var arrayRutinas = []; this.storage.get('rutinas').then((rutinas) => { if (rutinas == null) { arrayRutinas.push(rutina); } else { arrayRutinas = rutinas; arrayRutinas.push(rutina); } this.storage.set('rutinas', arrayRutinas); }) this.cargarRutinaAlEntrenador(rutina); this.servicioPersonas.actualizarUsuario(); } getTodasLasRutinas(): any { return this.storage.get('rutinas'); } eliminarTodasLasRutinas(): any { return this.storage.remove('rutinas'); } cargarRutinaAlEntrenador(rutina: Rutina): void { var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); var listaDeRutinas = []; if (usuarioRegistrado.hasOwnProperty('listaDeRutinas')) { usuarioRegistrado.listaDeRutinas.push(rutina); } else { usuarioRegistrado.listaDeRutinas = []; usuarioRegistrado.listaDeRutinas.push(rutina); } this.servicioLocal.setUsuarioRegistrado(usuarioRegistrado); } }<file_sep>export class ServicioLocal { usuarioRegistrado: Object; constructor() { this.usuarioRegistrado = null; } setUsuarioRegistrado(usuario) { this.usuarioRegistrado = usuario; } getUsuarioRegistrado() { return this.usuarioRegistrado; } limpiarUsuario() { this.usuarioRegistrado = null; } }<file_sep>import { Component , OnInit} from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { ServicioPersonas } from '../../app/servicios/servicio.persona'; import { ServicioLocal } from '../../app/servicios/servicio.local'; import { Alertas } from '../../app/componentes/alertas/alertas'; import { Rutina } from '../../app/modelo/rutina'; import { Page1 } from '../../pages/page1/page1'; import { VerRutina } from '../../app/componentes/verRutina/verRutina'; @Component({ selector: 'rutinas-de-cliente', templateUrl: 'rutinasDeCliente.html' }) export class RutinasDeCliente implements OnInit { constructor(public navCtrl: NavController, private servicioPersonas: ServicioPersonas, private alertas: Alertas, private servicioLocal: ServicioLocal) {} listaDeRutinas; ngOnInit(): void { var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); this.listaDeRutinas = usuarioRegistrado.listaDeRutinas; } abrirRutina(rutina: Rutina): void { console.log(rutina); this.navCtrl.push(VerRutina, {rutinaSeleccionada: rutina}); } salir(): void { this.servicioLocal.limpiarUsuario(); this.servicioPersonas.logOut(); setTimeout(() => { this.navCtrl.push(Page1) }, 100); } } <file_sep>import { Entrenador } from './entrenador'; export class Ejercicio { emailDelCreador: String; nombre: String; repeticiones: number; series:number; peso: number; descarga: String; cambioPeso: number; //cero para ningun cambio en peso cambioRepeticiones: number; //cero para ningun cambio en repeticiones esCombinado: boolean; ilustracion: ImageData; descripcion: String; ejercicioConActualizaciones: boolean; ejercicioCompletado: boolean; seriesHechas: number; repeticionesHechas: number; pesoConElQueSeHizo: number; }<file_sep>import { ComidasDiarias } from './comidasDiarias'; export class Dieta { emailDelCreador: String; nombre: String; objetivo: String; dieta: ComidasDiarias []; //rever esto }<file_sep>import { Component, Input, OnInit } from '@angular/core'; import { ViewController, NavController } from 'ionic-angular'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { ServicioEjercicios } from '../../servicios/servicio.ejercicio'; import { ServicioPersonas } from '../../servicios/servicio.persona'; import { ServicioLocal } from '../../servicios/servicio.local'; import { ServicioRutinas } from '../../servicios/servicio.rutina'; import { Entrenador } from '../../Modelo/entrenador'; import { Cliente } from '../../Modelo/cliente'; import { Ejercicio } from '../../Modelo/ejercicio'; import { Gimnasio } from '../../Modelo/gimnasio'; import { Rutina } from '../../Modelo/rutina'; import { RutinaDiaria } from '../../Modelo/rutinaDiaria'; import { AsignarRutina } from '../../componentes/asignarRutina/asignarRutina'; import { Alertas } from '../alertas/alertas'; @Component({ selector: 'crear-rutina', templateUrl: 'crearRutina.html' }) export class CrearRutina implements OnInit { miForm: FormGroup; infoRutina: {numeroDeDias: string; titulo: String; descripcion: String; } = { numeroDeDias: null, titulo: null, descripcion: null}; todosLosEjercicios; todosLosEjerciciosDelEntrenador; ejerciciosDeLaRutina; nombreDeLaRutina; descripcionDeLaRutina; ejerciciosUsuario; ejerciciosTodos; rutinaActual; arrayDeDias; pasoUnoCompleto; constructor(public viewCtrl: ViewController, private servicioPersonas: ServicioPersonas, private cliente: Cliente, private entrenador: Entrenador, private gimnasio: Gimnasio, public formBuilder: FormBuilder, private servicioLocal: ServicioLocal, private ejercicio: Ejercicio, private servicioEjercicios: ServicioEjercicios, private alerta: Alertas, private servicioRutinas: ServicioRutinas, private navCtrl: NavController) { } ngOnInit(): void { this.cargarEjercicios(); this.ejerciciosUsuario = true; this.ejerciciosTodos = false; this.rutinaActual = []; this.pasoUnoCompleto = false; } seleccionoDias(): void { this.arrayDeDias = new Array(parseInt(this.infoRutina.numeroDeDias)); for(let i = 0; i < this.arrayDeDias.length; i++) { this.arrayDeDias[i] = { titulo: null, descripcion: null, ejerciciosDelEntrenador: this.todosLosEjerciciosDelEntrenador, ejerciciosDeTodos: this.todosLosEjercicios, ejerciciosDeLaRutina: new Array() }; } } cambioElNombreDe(index) { this.arrayDeDias[index].titulo = this.infoRutina.titulo; } cambioLaDescripcionDe(index) { this.arrayDeDias[index].descripcion = this.infoRutina.descripcion; } cambiarLista(): void { if (this.ejerciciosUsuario === true) { this.ejerciciosUsuario = false; this.ejerciciosTodos = true; } else { this.ejerciciosUsuario = true; this.ejerciciosTodos = false; } } agregarEjercicio(ejercicio, indexDia): void { if (this.ejerciciosUsuario === true) { this.arrayDeDias[indexDia].ejerciciosDelEntrenador = this.arrayDeDias[indexDia].ejerciciosDelEntrenador.filter(ejer =>{ return ejer.nombre !== ejercicio.nombre }) } else { this.arrayDeDias[indexDia].ejerciciosDeTodos = this.arrayDeDias[indexDia].ejerciciosDeTodos.filter(ejer =>{ return ejer.nombre !== ejercicio.nombre }) } this.arrayDeDias[indexDia].ejerciciosDeLaRutina.push(ejercicio); } removerEjercicio(ejercicio, indexDia): void { if (this.ejerciciosUsuario === true) { this.arrayDeDias[indexDia].ejerciciosDelEntrenador.push(ejercicio); } else { this.arrayDeDias[indexDia].ejerciciosDeTodos.push(ejercicio); } this.arrayDeDias[indexDia].ejerciciosDeLaRutina = this.arrayDeDias[indexDia].ejerciciosDeLaRutina.filter(ejer =>{ return ejer.nombre !== ejercicio.nombre }) } cerrarModal(): void { this.viewCtrl.dismiss(); } pasarASiguientePaso(): void { if (this.infoRutina.numeroDeDias !== null && this.nombreDeLaRutina !== undefined && this.descripcionDeLaRutina !== undefined) { this.pasoUnoCompleto = true; } } cargarEjercicios(): void { this.servicioEjercicios.getTodosLosEjercicios().then((ejercicios) => { this.todosLosEjercicios = ejercicios; }) var entrenadorRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); this.todosLosEjerciciosDelEntrenador = entrenadorRegistrado.listaDeEjercicios; } crearRutina(): void { var datosCompletos = false; for (let i = 0; i < this.arrayDeDias.length; i++) { if (this.arrayDeDias[i].titulo === undefined || this.arrayDeDias[i].descripcion === undefined || this.arrayDeDias[i].ejerciciosDeLaRutina.length === 0) { datosCompletos = false; } else { datosCompletos = true; } } if (datosCompletos) { var rutina = new Rutina; var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); rutina.nombreRutina = this.nombreDeLaRutina; rutina.descripcionRutina = this.descripcionDeLaRutina; rutina.emailDelCreador = usuarioRegistrado.email; rutina.listaDeDias = []; for (let i = 0; i < this.arrayDeDias.length; i++) { var rutinaDiaria = new RutinaDiaria; rutinaDiaria.diaNumero = i + 1; rutinaDiaria.titulo = this.arrayDeDias[i].titulo; rutinaDiaria.descripcion = this.arrayDeDias[i].descripcion; rutinaDiaria.listaDeEjercicios = this.arrayDeDias[i].ejerciciosDeLaRutina; rutina.listaDeDias.push(rutinaDiaria); } console.log(rutina); this.servicioRutinas.setRutina(rutina); this.alerta.mostrarToast('Se le ha creado la rutina con éxito', 'top', 2500); this.viewCtrl.dismiss(); } else { this.alerta.mostrarAlerta('Atención', 'Campos no completos', 'Volver'); } } crearRutinaYAsignar(): void { var datosCompletos = false; for (let i = 0; i < this.arrayDeDias.length; i++) { if (this.arrayDeDias[i].titulo === undefined || this.arrayDeDias[i].descripcion === undefined || this.arrayDeDias[i].ejerciciosDeLaRutina.length === 0) { datosCompletos = false; } else { datosCompletos = true; } } if (datosCompletos) { var rutina = new Rutina; var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); rutina.nombreRutina = this.nombreDeLaRutina; rutina.descripcionRutina = this.descripcionDeLaRutina; rutina.emailDelCreador = usuarioRegistrado.email; rutina.listaDeDias = []; for (let i = 0; i < this.arrayDeDias.length; i++) { var rutinaDiaria = new RutinaDiaria; rutinaDiaria.diaNumero = i + 1; rutinaDiaria.titulo = this.arrayDeDias[i].titulo; rutinaDiaria.descripcion = this.arrayDeDias[i].descripcion; rutinaDiaria.listaDeEjercicios = this.arrayDeDias[i].ejerciciosDeLaRutina; rutina.listaDeDias.push(rutinaDiaria); } this.servicioRutinas.setRutina(rutina); this.viewCtrl.dismiss(); this.alerta.mostrarToast('Se le ha creado la rutina con éxito', 'top', 2500); this.navCtrl.push(AsignarRutina, {rutinaCreada: rutina}); } else { this.alerta.mostrarAlerta('Atención', 'Campos no completos', 'Volver'); } } }<file_sep>import { Persona } from './persona'; import { Cliente } from './cliente'; import { Gimnasio } from './gimnasio'; import { Dieta } from './dieta'; export class Nutricionista extends Persona { gimnasio: Gimnasio; listaDeClientes: Cliente []; listaDeDietas: Dieta []; }<file_sep>import { Component , OnInit} from '@angular/core'; import { NavController, ModalController } from 'ionic-angular'; import { ServicioPersonas } from '../../app/servicios/servicio.persona'; import { ServicioLocal } from '../../app/servicios/servicio.local'; import { Cliente } from '../../app/Modelo/cliente'; import { Entrenador } from '../../app/Modelo/entrenador'; import { Gimnasio } from '../../app/Modelo/gimnasio'; import { Alertas } from '../../app/componentes/alertas/alertas'; import { CrearEjercicio } from '../../app/componentes/crearEjercicio/crearEjercicio'; import { CrearRutina } from '../../app/componentes/crearRutina/crearRutina'; import { AsignarRutina } from '../../app/componentes/asignarRutina/asignarRutina'; import { Page1 } from '../../pages/page1/page1'; @Component({ selector: 'crear-asignar-rutina', templateUrl: 'crearAsignarRutina.html' }) export class CrearAsignarRutina implements OnInit { constructor(public navCtrl: NavController, private servicioPersonas: ServicioPersonas, private cliente: Cliente, private alertas: Alertas, private entrenador: Entrenador, private servicioLocal: ServicioLocal, public modal: ModalController) {} infoDeEntrenador = this.servicioLocal.getUsuarioRegistrado(); ngOnInit(): void { } salir(): void { this.servicioLocal.limpiarUsuario(); this.servicioPersonas.logOut(); setTimeout(() => { this.navCtrl.push(Page1) }, 100); } crearEjercicio(): void { let profileModal = this.modal.create(CrearEjercicio); profileModal.present(); } crearRutina(): void { let profileModal = this.modal.create(CrearRutina); profileModal.present(); } asignarRutina(): void { let profileModal = this.modal.create(AsignarRutina); profileModal.present(); } }<file_sep>import { Component, Input, OnInit } from '@angular/core'; import { ViewController } from 'ionic-angular'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { ServicioPersonas } from '../../servicios/servicio.persona'; import { ServicioLocal } from '../../servicios/servicio.local'; import { ServicioRutinas } from '../../servicios/servicio.rutina'; import { Entrenador } from '../../Modelo/entrenador'; import { Cliente } from '../../Modelo/cliente'; import { Gimnasio } from '../../Modelo/gimnasio'; import { Alertas } from '../alertas/alertas'; import { AlertController } from 'ionic-angular'; @Component({ selector: 'asignar-cliente', templateUrl: 'asignarCliente.html' }) export class AsignarCliente implements OnInit { todosLosClientesDelGimnasio; constructor(public viewCtrl: ViewController, private servicioPersonas: ServicioPersonas, private cliente: Cliente, private entrenador: Entrenador, private gimnasio: Gimnasio, public formBuilder: FormBuilder, private servicioLocal: ServicioLocal, private alerta: Alertas, private servicioRutinas: ServicioRutinas, private alertCtrl: AlertController) { } ngOnInit(): void { this.cargarClientes(); } cargarClientes(): void { var entrenador: any = this.servicioLocal.getUsuarioRegistrado(); this.servicioPersonas.getTodosLosClientes().then((val) => { this.todosLosClientesDelGimnasio = val; this.todosLosClientesDelGimnasio = this.todosLosClientesDelGimnasio.filter(cliente =>{ return cliente.gimnasio.id === entrenador.gimnasio.id; }) this.todosLosClientesDelGimnasio = this.todosLosClientesDelGimnasio.filter(cliente =>{ return cliente.emailDelEntrenador === undefined; }) }) } asignarCliente(cliente: Cliente) { let alert = this.alertCtrl.create({ title: 'Agregar Cliente', message: 'Usted está por agregar a ' + cliente.nombre + ' ' + cliente.apellido + ' como cliente suyo.', buttons: [ { text: 'Cancelar', handler: () => { } }, { text: 'Asignar Cliente', handler: () => { this.servicioPersonas.asignarClienteAEntrenador(cliente); this.alerta.mostrarToast(cliente.nombre + ' ' + cliente.apellido + ' es ahora cliente suyo.', 'top', 2500); this.viewCtrl.dismiss(); } } ] }); alert.present(); } getItems(ev: any) { //TODO revisar que solo cuando borras todo fonca let val = ev.target.value; if (val && val.trim() != '') { this.todosLosClientesDelGimnasio = this.todosLosClientesDelGimnasio.filter((item) => { return (item.nombre.toLowerCase().indexOf(val.toLowerCase()) > -1); }) } else { this.cargarClientes(); } } cerrarModal(): void { this.viewCtrl.dismiss(); } }<file_sep>import { Storage } from '@ionic/storage'; import { Injectable } from '@angular/core'; import { Cliente } from '../Modelo/cliente'; import { Entrenador } from '../Modelo/entrenador'; import { Gimnasio } from '../Modelo/gimnasio'; import { Rutina } from '../Modelo/rutina'; import { ServicioLocal } from './servicio.local'; @Injectable() export class ServicioPersonas { constructor(private storage: Storage, private gimnasio: Gimnasio, private servicioLocal: ServicioLocal) { } setUsuario(dataUsuario: any, tipoUsuario: string): void { var arrayUsuarios = [], usuario = (tipoUsuario == 'cliente') ? 'clientes' : 'entrenadores'; this.storage.get(usuario).then((usuarios) => { if (usuarios == null) { arrayUsuarios.push(dataUsuario); } else { arrayUsuarios = usuarios; arrayUsuarios.push(dataUsuario); } this.storage.set(usuario, arrayUsuarios); }) } actualizarUsuario(): void { var promesaCliente = this.getTodosLosClientes(), promesaEntrenador = this.getTodosLosEntrenadores(), nuevoArrayClientes = [], nuevoArrayEntrenadores = [], cantidadDeClientes = null, cantidadDeEntrenadores = null, usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); Promise.all([promesaCliente, promesaEntrenador]).then(val => { cantidadDeClientes = val[0].length; cantidadDeEntrenadores = val[1].length; nuevoArrayClientes = val[0].filter(elemento =>{ return elemento.email !== usuarioRegistrado.email }) nuevoArrayEntrenadores = val[1].filter(elemento =>{ return elemento.email !== usuarioRegistrado.email }) if (nuevoArrayClientes.length === cantidadDeClientes) { nuevoArrayEntrenadores.push(usuarioRegistrado); this.storage.set('entrenadores', nuevoArrayEntrenadores); } else { nuevoArrayClientes.push(usuarioRegistrado); this.storage.set('clientes', nuevoArrayClientes); } }) } actualizarCliente(cliente: Cliente) { this.getTodosLosClientes().then(val => { var nuevoArrayClientes = val.filter(elemento =>{ return elemento.email !== cliente.email; }); nuevoArrayClientes.push(cliente); this.storage.set('clientes', nuevoArrayClientes); }) } asignarRutinaACliente(cliente: Cliente, rutina: Rutina) { var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); if (cliente.hasOwnProperty('listaDeRutinas')) { cliente.listaDeRutinas.push(rutina); } else { cliente.listaDeRutinas = []; cliente.listaDeRutinas.push(rutina); } cliente.solicitoRutina = false; this.actualizarCliente(cliente); } setUsuarioIniciadoSesion(dataUsuario: any, tipoUsuario: String): void { var objetoUsuario = {sesionIniciada: true, datosDeUsuario: dataUsuario, claseUsuario: tipoUsuario}; this.storage.set('usuario', objetoUsuario); } getUsuarioIniciadoSesion(): any { return this.storage.get('usuario'); } logOut(): void { var objetoUsuario = {sesionIniciada: false, datosDeUsuario: {}}; this.storage.set('usuario', objetoUsuario) } setGimnasios(): void { var arrayGimnasios = []; var gym1 = new Gimnasio(); gym1.barrio = 'Nueva Córdoba'; gym1.ciudad = 'Córdoba'; gym1.cp = 5000; gym1.id = 1; gym1.nombre = 'Synergy'; gym1.pais = 'Argentina'; arrayGimnasios.push(gym1); var gym2 = new Gimnasio(); gym2.barrio = 'Cofico'; gym2.ciudad = 'Córdoba'; gym2.cp = 5001; gym2.id = 2; gym2.nombre = 'Hercules'; gym2.pais = 'Argentina'; arrayGimnasios.push(gym2); var gym3 = new Gimnasio(); gym3.barrio = 'Nueva Córdoba'; gym3.ciudad = 'Córdoba'; gym3.cp = 5001; gym3.id = 3; gym3.nombre = 'Best Club'; gym3.pais = 'Argentina'; arrayGimnasios.push(gym3); var gym4 = new Gimnasio(); gym4.barrio = 'Recoleta'; gym4.ciudad = 'Buenos Aires'; gym4.cp = 1001; gym4.id = 4; gym4.nombre = 'Gym City'; gym4.pais = 'Argentina'; arrayGimnasios.push(gym4); this.storage.set('gimnasios', arrayGimnasios); } asignarClienteAEntrenador(cliente: Cliente): void { var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); var listaDeClientes = []; if (usuarioRegistrado.hasOwnProperty('listaDeClientes')) { usuarioRegistrado.listaDeClientes.push(cliente.email); } else { usuarioRegistrado.listaDeClientes = []; usuarioRegistrado.listaDeClientes.push(cliente.email); } this.servicioLocal.setUsuarioRegistrado(usuarioRegistrado); this.actualizarUsuario(); //ahora se lo seteo al cliente. cliente.emailDelEntrenador = usuarioRegistrado.email; this.actualizarCliente(cliente); } usuarioPideRutina(): void { var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); usuarioRegistrado.solicitoRutina = true; this.actualizarCliente(usuarioRegistrado); } getGimnasios(): any { return this.storage.get('gimnasios'); } getTodosLosClientes(): any { return this.storage.get('clientes'); } getTodosLosEntrenadores(): any { return this.storage.get('entrenadores'); } eliminarTodo(): void { this.storage.clear(); } }<file_sep>import { Persona } from './persona'; import { Rutina } from './rutina'; import { Cliente } from './cliente'; import { Gimnasio } from './gimnasio'; import { Ejercicio } from './ejercicio'; export class Entrenador extends Persona { listaDeEjercicios: Ejercicio []; gimnasio: Gimnasio; listaDeClientes: Cliente []; listaDeRutinas: Rutina []; }<file_sep>import { Component, Input } from '@angular/core'; import { AlertController } from 'ionic-angular'; import { ToastController } from 'ionic-angular'; @Component({ selector: 'alerta', template: 'alertas.html' }) export class Alertas { constructor(public alertCtrl: AlertController, public toastCtrl: ToastController) { } mostrarAlerta(titulo: string, subtitulo: string, boton: string) { let alert = this.alertCtrl.create({ title: titulo, subTitle: subtitulo, buttons: [boton] }); alert.present(); } mostrarToast(mensaje: string, posicion: string, duracion: number, ) { //posicion: top/middle/bottom let toast = this.toastCtrl.create({ message: mensaje, duration: duracion, position: posicion }); toast.present(toast); } }<file_sep>import { Storage } from '@ionic/storage'; import { Injectable } from '@angular/core'; import { Cliente } from '../Modelo/cliente'; import { Entrenador } from '../Modelo/entrenador'; import { Ejercicio } from '../Modelo/ejercicio'; import { ServicioLocal } from './servicio.local'; import { ServicioPersonas } from './servicio.persona'; @Injectable() export class ServicioEjercicios { constructor(private storage: Storage, private ejercicio: Ejercicio, private servicioLocal: ServicioLocal, private servicioPersonas: ServicioPersonas) { } entrenador = this.servicioLocal.getUsuarioRegistrado(); setEjercicio(ejercicio: Ejercicio): void { var arrayEjercicios = []; this.storage.get('ejercicios').then((ejercicios) => { if (ejercicios == null) { arrayEjercicios.push(ejercicio); } else { arrayEjercicios = ejercicios; arrayEjercicios.push(ejercicio); } this.storage.set('ejercicios', arrayEjercicios); }) this.cargarEjercicioAlEntrenador(ejercicio); this.servicioPersonas.actualizarUsuario(); } getTodosLosEjercicios(): any { return this.storage.get('ejercicios'); } eliminarTodosLosEjercicios(): any { return this.storage.remove('ejercicios'); } cargarEjercicioAlEntrenador(ejercicio: Ejercicio): void { var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); var listaDeEjercicios = []; if (usuarioRegistrado.hasOwnProperty('listaDeEjercicios')) { usuarioRegistrado.listaDeEjercicios.push(ejercicio); } else { usuarioRegistrado.listaDeEjercicios = []; usuarioRegistrado.listaDeEjercicios.push(ejercicio); } this.servicioLocal.setUsuarioRegistrado(usuarioRegistrado); } }<file_sep>import { Component, Input, OnInit } from '@angular/core'; import { ViewController, NavParams, NavController } from 'ionic-angular'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { ServicioPersonas } from '../../servicios/servicio.persona'; import { ServicioLocal } from '../../servicios/servicio.local'; import { ServicioRutinas } from '../../servicios/servicio.rutina'; import { Entrenador } from '../../Modelo/entrenador'; import { Cliente } from '../../Modelo/cliente'; import { Gimnasio } from '../../Modelo/gimnasio'; import { Rutina } from '../../Modelo/rutina'; import { Ejercicio } from '../../Modelo/ejercicio'; import { AlertController } from 'ionic-angular'; import { VerEjercicio } from '../verEjercicio/verEjercicio'; @Component({ selector: 'ver-rutina', templateUrl: 'verRutina.html' }) export class VerRutina implements OnInit { constructor(public viewCtrl: ViewController, private servicioPersonas: ServicioPersonas, private cliente: Cliente, private entrenador: Entrenador, private gimnasio: Gimnasio, public formBuilder: FormBuilder, private servicioLocal: ServicioLocal, private alertCtrl: AlertController, private servicioRutinas: ServicioRutinas, public navParams: NavParams, public navCtrl: NavController) { } diaSeleccionado; rutina; ngOnInit(): void { var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); this.rutina = this.navParams.get('rutinaSeleccionada'); this.diaSeleccionado = '1'; } mostrarEjercicio(ejercicio: Ejercicio): void { console.log(ejercicio); this.navCtrl.push(VerEjercicio, {ejercicioSeleccionado: ejercicio}); } cerrarModal(): void { this.viewCtrl.dismiss(); } }<file_sep>import { Component, OnInit } from '@angular/core'; import { NavController } from 'ionic-angular'; import { ServicioPersonas } from '../../app/servicios/servicio.persona'; import { ServicioLocal } from '../../app/servicios/servicio.local'; import { Cliente } from '../../app/Modelo/cliente'; import { Entrenador } from '../../app/Modelo/entrenador'; import { Alertas } from '../../app/componentes/alertas/alertas'; import { Gimnasio } from '../../app/Modelo/gimnasio'; import { RegistrarUsuario } from '../../pages/registrarUsuario/registrarUsuario'; import { MainEntrenador } from '../../pages/mainEntrenador/mainEntrenador'; import { MainCliente } from '../../pages/mainCliente/mainCliente'; @Component({ selector: 'page-page1', templateUrl: 'page1.html' }) export class Page1 implements OnInit { constructor(public navCtrl: NavController, private servicioPersonas: ServicioPersonas, private cliente: Cliente, private alertas: Alertas, private servicioLocal: ServicioLocal) { } email = ''; contrasenna = ''; habilitarBoton = false; todosLosClientes; todosLosEntrenadores; mostrarDevTools; ngOnInit(): void { this.servicioPersonas.getUsuarioIniciadoSesion().then((val) => { console.log(val); if(val.sesionIniciada) { if (val.claseUsuario == 'cliente') { this.servicioLocal.setUsuarioRegistrado(val.datosDeUsuario); this.navCtrl.push(MainCliente); } else if (val.claseUsuario == 'entrenador') { this.servicioLocal.setUsuarioRegistrado(val.datosDeUsuario); this.navCtrl.push(MainEntrenador); } } }) .catch((err) => { this.servicioPersonas.logOut(); console.log('primera vez que se entra en este dispositivo'); }); this.servicioPersonas.getTodosLosClientes().then((val) => { this.todosLosClientes = val; }); this.servicioPersonas.getTodosLosEntrenadores().then((val) => { this.todosLosEntrenadores = val; }); this.mostrarDevTools = true; } iniciarSesion(): void { console.log('esto valen todos los clientes', this.todosLosClientes); var cliente = this.todosLosClientes.find(usuario => usuario.email == this.email), entrenador = this.todosLosEntrenadores.find(usuario => usuario.email == this.email); if (cliente !== undefined && entrenador === undefined) { if (cliente.contraseña === this.contrasenna) { console.log('tengo un cliente válido'); this.servicioPersonas.setUsuarioIniciadoSesion(cliente, 'cliente'); this.servicioLocal.setUsuarioRegistrado(cliente); this.navCtrl.push(MainCliente); } else { this.contrasenna = ''; this.revisarCampos(); this.alertas.mostrarAlerta('Uuups!', 'Contraseña equivocada, inténtelo de nuevo', 'Ok'); } } else if (cliente === undefined && entrenador !== undefined) { if (entrenador.contraseña === this.contrasenna) { console.log('tengo un entrenador válido'); this.servicioPersonas.setUsuarioIniciadoSesion(entrenador, 'entrenador'); this.servicioLocal.setUsuarioRegistrado(entrenador); //redirigir apagina de entrenador this.navCtrl.push(MainEntrenador); } else { this.contrasenna = ''; this.revisarCampos(); this.alertas.mostrarAlerta('Uuups!', 'Contraseña equivocada, inténtelo de nuevo', 'Ok'); } } else { this.email = ''; this.contrasenna = ''; this.revisarCampos(); this.alertas.mostrarAlerta('Uuups!', 'Usuario no existente!', 'Ok'); } } registrarUsuario(): void { this.email = ''; this.contrasenna = ''; this.revisarCampos(); this.navCtrl.push(RegistrarUsuario); } revisarCampos(): void { this.habilitarBoton = true; if(this.email == '' || this.contrasenna == '') { this.habilitarBoton = false; //fire up alert component } } agregarGimnasios(): void { this.servicioPersonas.setGimnasios(); } mostrarGimnasios(): void { this.servicioPersonas.getGimnasios().then((val) => { console.log('todos los gimnasios', val); }) } eliminar(): void { this.servicioPersonas.eliminarTodo(); } mostrar(): void { this.servicioPersonas.getTodosLosClientes().then((val) => { console.log('todos los clientes', val); }) this.servicioPersonas.getTodosLosEntrenadores().then((val) => { console.log('todos los entrenadores', val); }) } cargar1y1(): void { var cliente = new Cliente; var entrenador = new Entrenador; var gym1 = new Gimnasio(); gym1.barrio = 'Nueva Córdoba'; gym1.ciudad = 'Córdoba'; gym1.cp = 5000; gym1.id = 1; gym1.nombre = 'Synergy'; gym1.pais = 'Argentina'; cliente.nombre = 'Santiago'; cliente.apellido = 'Rubbiolo'; cliente.dni = 34315653; cliente.email = '<EMAIL>'; cliente.gimnasio = gym1; cliente.contraseña = '<PASSWORD>'; cliente.fechaNacimiento = new Date('11-4-1989'); cliente.telefono = 3516775504; entrenador.nombre = 'Federico'; entrenador.apellido = 'Ussei'; entrenador.dni = 34315654; entrenador.email = '<EMAIL>'; entrenador.gimnasio = gym1; entrenador.contraseña = '<PASSWORD>'; entrenador.fechaNacimiento = new Date('2-5-1988'); entrenador.telefono = 3516775505; this.servicioPersonas.setUsuario(cliente, 'cliente'); this.servicioPersonas.setUsuario(entrenador, 'entrenador'); } toggleDevTools(): void { if (this.mostrarDevTools) { this.mostrarDevTools = false; } else { this.mostrarDevTools = true; } } } <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { ViewController, NavParams } from 'ionic-angular'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { ServicioPersonas } from '../../servicios/servicio.persona'; import { ServicioLocal } from '../../servicios/servicio.local'; import { ServicioRutinas } from '../../servicios/servicio.rutina'; import { Entrenador } from '../../Modelo/entrenador'; import { Cliente } from '../../Modelo/cliente'; import { Gimnasio } from '../../Modelo/gimnasio'; import { Rutina } from '../../Modelo/rutina'; import { Alertas } from '../../componentes/alertas/alertas'; import { AlertController } from 'ionic-angular'; @Component({ selector: 'asignar-rutina', templateUrl: 'asignarRutina.html' }) export class AsignarRutina implements OnInit { rutinasDelEntrenador; todasLasRutinas; clientesDelEntrenador; clienteSeleccionado; rutinaSeleccionada; rutinasDeTodos; rutinasDeUsuario; constructor(public viewCtrl: ViewController, private servicioPersonas: ServicioPersonas, private cliente: Cliente, private entrenador: Entrenador, private gimnasio: Gimnasio, public formBuilder: FormBuilder, private servicioLocal: ServicioLocal, private alertCtrl: AlertController, private servicioRutinas: ServicioRutinas, private navParams: NavParams, private alerta: Alertas) { } ngOnInit(): void { var usuarioRegistrado: any = this.servicioLocal.getUsuarioRegistrado(); this.servicioPersonas.getTodosLosClientes().then((clientes) => { this.clientesDelEntrenador = clientes.filter(cliente =>{ return cliente.emailDelEntrenador === usuarioRegistrado.email; }) }); this.servicioRutinas.getTodasLasRutinas().then((rutinas) => { this.todasLasRutinas = rutinas; }); this.rutinasDelEntrenador = usuarioRegistrado.listaDeRutinas; this.clienteSeleccionado = null; this.rutinaSeleccionada = (this.navParams.get('rutinaCreada')) !== undefined ? this.navParams.get('rutinaCreada') : null; this.rutinasDeTodos = false; this.rutinasDeUsuario = true; } seleccionarCliente(cliente: Cliente): void { this.clienteSeleccionado = cliente; //en caso que vengo desde crear rutina y ya la tengo seteada if (this.rutinaSeleccionada !== null) { this.asignarRutina(); } } seleccionarRutina(rutina: Rutina): void { this.rutinaSeleccionada = rutina; this.asignarRutina(); } cambiarLista(): void { if (this.rutinasDeUsuario === true) { this.rutinasDeUsuario = false; this.rutinasDeTodos = true; } else { this.rutinasDeUsuario = true; this.rutinasDeTodos = false; } } asignarRutina(): void { let alert = this.alertCtrl.create({ title: 'Asignar Rutina a Cliente', message: 'Usted está por asignar a: ' + this.clienteSeleccionado.nombre + ' ' + this.clienteSeleccionado.apellido + ' la rutina ' + this.rutinaSeleccionada.nombreRutina, buttons: [ { text: 'Cancelar y volver', handler: () => { this.viewCtrl.dismiss(); } }, { text: 'Confirmar', handler: () => { this.servicioPersonas.asignarRutinaACliente(this.clienteSeleccionado, this.rutinaSeleccionada); this.alerta.mostrarToast('Se le ha asignado la rutina con éxito a: ' + this.clienteSeleccionado.nombre + ' ' + this.clienteSeleccionado.apellido, 'top', 2500); this.viewCtrl.dismiss(); } } ] }); alert.present(); } cerrarModal(): void { this.viewCtrl.dismiss(); } }<file_sep>import { Entrenador } from './entrenador'; import { Cliente } from './cliente'; export class Gimnasio { id: number; nombre: String; ciudad: String; barrio: String; cp: number; pais: String; entrenadores: Entrenador []; clientes: Cliente []; }<file_sep>import { Ejercicio } from './ejercicio'; import { RutinaDiaria } from './rutinaDiaria'; export class Rutina { emailDelCreador: String; nombreRutina: String; descripcionRutina: String; listaDeDias: RutinaDiaria []; }<file_sep>//TODO: permitir seleccionar entrenador al usuario,sería igual que el select gimnasio. //TODO: validar bien todo los campos, por ahora no valido un orto import { Component , OnInit} from '@angular/core'; import { NavController } from 'ionic-angular'; import { ServicioPersonas } from '../../app/servicios/servicio.persona'; import { ServicioLocal } from '../../app/servicios/servicio.local'; import { Cliente } from '../../app/Modelo/cliente'; import { Entrenador } from '../../app/Modelo/entrenador'; import { Gimnasio } from '../../app/Modelo/gimnasio'; import { Alertas } from '../../app/componentes/alertas/alertas'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { MainCliente } from '../mainCliente/mainCliente'; import { MainEntrenador } from '../mainEntrenador/mainEntrenador'; @Component({ selector: 'registrar-usuario', templateUrl: 'registrarUsuario.html' }) export class RegistrarUsuario implements OnInit{ TIEMPO_TIMEOUT = 300; todosLosClientes; todosLosEntrenadores; gimnasios: Gimnasio[]; gimnasioSeleccionado; usuarioSeleccionado; datosCompletados; tipoUsuario; gimnasioDeUsuario: Gimnasio; sonPasswordsIguales; dniDuplicado; emailDuplicado; miForm: FormGroup; infoUsuario: {nombre: string, apellido: string, dni: string, fechaDeNacimiento: Date, email: string, telefono: string, password: string, password2: string } = { nombre: '', apellido: '', dni: '', fechaDeNacimiento: null, email: '', telefono: '', password: '', password2: ''}; constructor(public navCtrl: NavController, private servicioPersonas: ServicioPersonas, private cliente: Cliente, private alertas: Alertas, private entrenador: Entrenador, private gimnasio: Gimnasio, public formBuilder: FormBuilder, private servicioLocal: ServicioLocal) { this.miForm = this.formBuilder.group({ 'nombre': ['', [Validators.required, this.nombreValidator.bind(this)]], 'apellido': ['', [Validators.required, this.nombreValidator.bind(this)]], 'dni': ['', [Validators.required, this.dniValidator.bind(this)]], 'fechaDeNacimiento': ['', [Validators.required]], 'email': ['', [Validators.required, this.emailValidator.bind(this)]], 'telefono': ['', [Validators.required, this.telefonoValidator.bind(this)]], 'password': ['', [Validators.required, this.passwordValidator.bind(this)]], 'password2': ['', [Validators.required, this.passwordValidator.bind(this)]] }); } ngOnInit(): void { this.gimnasioSeleccionado = false; this.usuarioSeleccionado = true; this.datosCompletados = true; this.sonPasswordsIguales = false; this.dniDuplicado = false; this.emailDuplicado = false; this.recargarGimnasios(); this.cargarTodosLosUsuarios(); } cargarTodosLosUsuarios(): void { this.servicioPersonas.getTodosLosClientes().then((val) => { this.todosLosClientes = val; }) this.servicioPersonas.getTodosLosEntrenadores().then((val) => { this.todosLosEntrenadores = val; }) } verificarDniDuplicado(): void { //TODO: Ver que quede rojo también el field var todosLosUsuarios; if (this.todosLosEntrenadores == null) { todosLosUsuarios = this.todosLosClientes; } else if (this.todosLosClientes == null) { todosLosUsuarios = this.todosLosEntrenadores; } else if (this.todosLosClientes == null && this.todosLosEntrenadores == null) { todosLosUsuarios = null; } else { todosLosUsuarios = this.todosLosClientes.concat(this.todosLosEntrenadores); } console.log(todosLosUsuarios); var usuarioDuplicado = todosLosUsuarios.find(usuario => usuario.dni == this.infoUsuario.dni); console.log(usuarioDuplicado); if (usuarioDuplicado !== undefined) { this.dniDuplicado = true; } else { this.dniDuplicado = false; } } verificarEmailDuplicado(): void { //TODO: Ver que quede rojo también el field var todosLosUsuarios; if (this.todosLosEntrenadores == null) { todosLosUsuarios = this.todosLosClientes; } else if (this.todosLosClientes == null) { todosLosUsuarios = this.todosLosEntrenadores; } else if (this.todosLosClientes == null && this.todosLosEntrenadores == null) { todosLosUsuarios = null; } else { todosLosUsuarios = this.todosLosClientes.concat(this.todosLosEntrenadores); } var usuarioDuplicado = todosLosUsuarios.find(usuario => usuario.email == this.infoUsuario.email); if (usuarioDuplicado !== undefined) { this.emailDuplicado = true; } else { this.emailDuplicado = false; } } nombreValidator(control: FormControl): {[s: string]: boolean} { if (control.value !== '') { if (!control.value.match(/^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.'-]+$/)) { return {invalidNombre: true}; } } } dniValidator(control: FormControl): {[s: string]: boolean} { if (control.value !== '') { if (!control.value.match(/^\s*?[0-9]{7,8}\s*$/)) { return {invalidDni: true}; } } } emailValidator(control: FormControl): {[s: string]: boolean} { if (control.value !== '') { if (!control.value.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) { return {invalidEmail: true}; } } } telefonoValidator(control: FormControl): {[s: string]: boolean} { if (control.value !== '') { if (!control.value.match(/^\+?\d{1,3}?[- .]?\(?(?:\d{2,3})\)?[- .]?\d\d\d[- .]?\d\d\d\d$/)) { return {invalidTelefono: true}; } } } passwordValidator(control: FormControl): {[s: string]: boolean} { if (control.value !== '') { if (!control.value.match(/^(?=.*\d).{4,30}$/)) { return {invalidPassword: true}; } } } revisarPasswordsIguales(): void { if(this.infoUsuario.password === this.infoUsuario.password2) { this.sonPasswordsIguales = true; } else { this.sonPasswordsIguales = false; } } isValid(field: string) { let formField = this.miForm.get(field); return formField.valid || formField.pristine; } onSubmit(): void { var usuario = (this.tipoUsuario == 'cliente') ? new Cliente : new Entrenador; usuario.nombre = this.infoUsuario.nombre; usuario.apellido = this.infoUsuario.apellido; usuario.dni = parseInt(this.infoUsuario.dni); usuario.email = this.infoUsuario.email; usuario.gimnasio = this.gimnasioDeUsuario; usuario.contraseña = this.infoUsuario.password; usuario.fechaNacimiento = new Date(this.infoUsuario.fechaDeNacimiento); usuario.telefono = parseInt(this.infoUsuario.telefono); // TODO: si es usuario agregar en caso que haya seleccionado un entrenador if (this.tipoUsuario == 'cliente') { this.servicioPersonas.setUsuario(usuario, 'cliente'); this.servicioPersonas.setUsuarioIniciadoSesion(usuario, 'cliente'); this.servicioLocal.setUsuarioRegistrado(usuario); this.navCtrl.push(MainCliente) } else { this.servicioPersonas.setUsuario(usuario, 'entrenador') this.servicioPersonas.setUsuarioIniciadoSesion(usuario, 'entrenador'); this.servicioLocal.setUsuarioRegistrado(usuario); this.navCtrl.push(MainEntrenador) } } recargarGimnasios(): void { this.servicioPersonas.getGimnasios().then((val) => { this.gimnasios = val; }) } tipoUsuarioSeleccionado() { setTimeout(() => { this.usuarioSeleccionado = true; this.datosCompletados = false; }, this.TIEMPO_TIMEOUT); } agregarGimnasio(gym: Gimnasio) { setTimeout(() => { this.gimnasioDeUsuario = gym; this.gimnasioSeleccionado = true; this.usuarioSeleccionado = false; }, this.TIEMPO_TIMEOUT); } sinGimnasio() { setTimeout(() => { this.gimnasioDeUsuario = null; this.gimnasioSeleccionado = true; this.usuarioSeleccionado = false; }, this.TIEMPO_TIMEOUT); } getItems(ev: any) { //TODO revisar que solo cuando borras todo fonca let val = ev.target.value; if (val && val.trim() != '') { this.gimnasios = this.gimnasios.filter((item) => { return (item.nombre.toLowerCase().indexOf(val.toLowerCase()) > -1); }) } else { this.recargarGimnasios(); } } } <file_sep>import { Ejercicio } from './ejercicio'; export class RutinaDiaria { diaNumero: number; titulo: String; descripcion: String; listaDeEjercicios: Ejercicio []; }<file_sep>export class Persona { nombre: String; apellido: String; dni: number; contraseña: String; fechaNacimiento: Date; email: String; telefono: number; }<file_sep>import { NgModule, ErrorHandler } from '@angular/core'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { Storage } from '@ionic/storage'; import { MyApp } from './app.component'; import { Page1 } from '../pages/page1/page1'; import { Page2 } from '../pages/page2/page2'; import { RegistrarUsuario } from '../pages/registrarUsuario/registrarUsuario'; import { MainEntrenador } from '../pages/mainEntrenador/mainEntrenador'; import { MainCliente } from '../pages/mainCliente/mainCliente'; import { CrearAsignarRutina } from '../pages/crearAsignarRutina/crearAsignarRutina'; import { RutinasDeCliente } from '../pages/rutinasDeCliente/rutinasDeCliente'; import { ServicioPersonas} from '../app/servicios/servicio.persona'; import { ServicioEjercicios} from '../app/servicios/servicio.ejercicio'; import { ServicioRutinas } from '../app/servicios/servicio.rutina'; import { Cliente } from '../app/Modelo/cliente'; import { Entrenador } from '../app/Modelo/entrenador' import { Gimnasio } from '../app/Modelo/gimnasio'; import { Ejercicio } from '../app/Modelo/ejercicio'; import { ServicioLocal } from '../app/servicios/servicio.local'; import { Alertas } from '../app/componentes/alertas/alertas'; import { CrearEjercicio } from '../app/componentes/crearEjercicio/crearEjercicio'; import { CrearRutina } from '../app/componentes/crearRutina/crearRutina'; import { AsignarRutina } from '../app/componentes/asignarRutina/asignarRutina'; import { AsignarCliente } from '../app/componentes/asignarCliente/asignarCliente'; import { VerRutina } from '../app/componentes/verRutina/verRutina'; import { RutinaDiaria } from '../app/Modelo/rutinaDiaria'; import { VerEjercicio } from '../app/componentes/verEjercicio/verEjercicio'; @NgModule({ declarations: [ MyApp, Page1, Page2, RegistrarUsuario, MainEntrenador, MainCliente, CrearAsignarRutina, CrearEjercicio, CrearRutina, AsignarRutina, AsignarCliente, RutinasDeCliente, VerRutina, VerEjercicio ], imports: [ IonicModule.forRoot(MyApp, { scrollAssist: true, autoFocusAssist: true }) ], bootstrap: [IonicApp], entryComponents: [ MyApp, Page1, Page2, RegistrarUsuario, MainEntrenador, MainCliente, CrearAsignarRutina, CrearEjercicio, CrearRutina, AsignarRutina, AsignarCliente, RutinasDeCliente, VerRutina, VerEjercicio ], providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, Storage, ServicioPersonas, Cliente, ServicioLocal, Alertas, Entrenador, Gimnasio, Ejercicio, ServicioEjercicios, ServicioRutinas] }) export class AppModule {}
afce00c0178d70fb60e98b653462ca1a567bd9cd
[ "TypeScript" ]
28
TypeScript
srubbiolo/rutinApp
13f60ba727d7894c9b52fd17244c564641df9586
fe9c122ffb1bb22ab1e52199a3e492985f4fbc60
refs/heads/master
<file_sep>""" put your age, and you will know if you ca go inside """ name = input('Hey there.. Whats your name?') #the user inputs their name age = input('How old are you?') #the user inputs their age if int(age) > 20: print('Hey', name, "Welcome inside. Please have a drink") elif int(age) < 20 and int(age) > 18: print('Hey', name, 'Welcome in.. BUT you cannot have a drink!') elif float(age) < 18: print('Sorry', name, "your too young. You CANNOT come inside")<file_sep>""" this script has a class named employees, and we will get the email address combined by the first and last name """ class employees: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@gmail.com' # connect first + last name and add @gmail.. emp1 = employees('Saar', 'Cohen', 22000) emp2 = employees('Yossi', 'Cohen', 23000) emp3 = employees('Liran', 'Cohen', 24000) print('Hello', emp1.first + '!', 'Your new Email Address is:', emp1.email, end='\n\n') # getting emp1 1 email address print('Hello', emp2.first + '!', "Your new Email Address is:", emp2.email, end='\n\n') # getting user 2 email address print("Hello", emp3.first + '!', 'Your new Email Address is:', emp3.email, end='\n\n') # getting user 3 email address
94641b7cbc26d80bf9097df9b7b77365f169c82d
[ "Python" ]
2
Python
saarco777/Project
5cc01f2223501edae5f70df4472ade3467d4945a
34f6aeecc4507e47c1895d30e51a7b91f08cb3c6
refs/heads/master
<file_sep># -*- coding: utf-8 -*- BOT_NAME = 'books' SPIDER_MODULES = ['books.spiders'] NEWSPIDER_MODULE = 'books.spiders' user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1" ROBOTSTXT_OBEY = True HTTPCACHE_ENABLED = True
a591ffd0a8139287f93a5219f729df5796bcc332
[ "Python" ]
1
Python
oi7/scrapy
64926dd4f4e29dc0eaeb0c06fec57dec4ed6eb3d
e13dfb2645052694fddddb5b3268e26214d42647
refs/heads/master
<file_sep>import React, { useState } from "react"; import ComboBox from "./ComboBox"; // Import static assets for app import "./ComboBox/index.css"; import "@fortawesome/fontawesome-free/css/all.css"; const examples = [ { value: 1, label: "Example 1", className: "px-4 py-2 border hover:bg-blue-200", }, { value: 2, label: "Example 2", className: "px-4 py-2 border hover:bg-blue-200", }, { value: 3, label: "Example 3", className: "px-4 py-2 border hover:bg-blue-200", }, { value: 4, label: "Example 4", className: "px-4 py-2 border hover:bg-blue-200", }, { value: 5, label: "Example 5", className: "px-4 py-2 border hover:bg-blue-200", }, ]; function App() { const [value, setValue] = useState(""); return ( <section className="max-w-screen-xl px-4 md:px-8 mx-auto border flex flex-col justify-center items-stretch h-screen"> <ComboBox name="example" value={value} onChange={(ev) => setValue(ev.target.value)} className="px-4 py-2 w-full border border-black rounded" placeholder="ComboBox Example" items={examples} mutateItem={(item) => String(item.value) === String(value) ? { ...item, className: `${item.className} bg-blue-200` } : item } navs={{ reset: <i className="fas fa-times inline-block mr-4 mt-3"></i>, open: <i className="fas fa-chevron-up inline-block mr-4 mt-3"></i>, close: <i className="fas fa-chevron-down inline-block mr-4 mt-3"></i>, }} /> </section> ); } export default App;
aea3e12014b883f2230d739c75f254bfd2715127
[ "JavaScript" ]
1
JavaScript
alHasandev/react-combobox
458e59a2f865afa7a02525b6c8b87590137dc473
83e431cad45e28351a4cadec090e1bc4b8c6d16a
refs/heads/master
<file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest from parglare import GLRParser, Grammar, Parser, ParseError from parglare.exceptions import SRConflicts def test_lr2_grammar(): grammar = """ Model: Prods EOF; Prods: Prod | Prods Prod; Prod: ID "=" ProdRefs; ProdRefs: ID | ProdRefs ID; terminals ID: /\w+/; """ input_str = """ First = One Two three Second = Foo Bar Third = Baz """ g = Grammar.from_string(grammar) # This grammar is not LR(1) as it requires # at least two tokens of lookahead to decide # what to do on each ID from the right side. # If '=' is after ID than it should reduce "Prod" # else it should reduce ID as ProdRefs. with pytest.raises(SRConflicts): Parser(g, prefer_shifts=False) # prefer_shifts strategy (the default) # will remove conflicts but the resulting parser # will fail to parse any input as it will consume # greadily next rule ID as the body element of the previous Prod rule. parser = Parser(g) with pytest.raises(ParseError): parser.parse(input_str) # But it can be parsed unambiguously by GLR. p = GLRParser(g) results = p.parse(input_str) assert len(results) == 1 def test_nops(): """ Test that nops (no prefer shifts) will honored per rule. """ grammar = """ Program: "begin" statements=Statements ProgramEnd EOF; Statements: Statements1 | EMPTY; Statements1: Statements1 Statement | Statement; ProgramEnd: End; Statement: End "transaction" | "command"; terminals End: "end"; """ g = Grammar.from_string(grammar, ignore_case=True) parser = GLRParser(g, build_tree=True, prefer_shifts=True) # Here we have "end transaction" which is a statement and "end" which # finish program. Prefer shift strategy will make parser always choose to # shift "end" in anticipation of "end transaction" statement instead of # reducing by "Statements" and finishing. with pytest.raises(ParseError): parser.parse(""" begin command end transaction command end transaction command end """) # When {nops} is used, GLR parser will investigate both possibilities at # this place and find the correct interpretation while still using # prefer_shift strategy globaly. grammar = """ Program: "begin" statements=Statements ProgramEnd EOF; Statements: Statements1 {nops} | EMPTY; Statements1: Statements1 Statement | Statement; ProgramEnd: End; Statement: End "transaction" | "command"; terminals End: "end"; """ g = Grammar.from_string(grammar, ignore_case=True) parser = GLRParser(g, build_tree=True, prefer_shifts=True) parser.parse(""" begin command end transaction command end transaction command end """) def test_expressions(): actions = { "E": [ lambda _, nodes: nodes[0] + nodes[2], lambda _, nodes: nodes[0] * nodes[2], lambda _, nodes: nodes[1], lambda _, nodes: int(nodes[0]) ] } # This grammar is highly ambiguous if priorities and # associativities are not defined to disambiguate. grammar = """ E: E "+" E | E "*" E | "(" E ")" | Number; terminals Number: /\d+/; """ g = Grammar.from_string(grammar) p = GLRParser(g, actions=actions, debug=True) # Even this simple expression has 2 different interpretations # (4 + 2) * 3 and # 4 + (2 * 3) results = p.parse("4 + 2 * 3") assert len(results) == 2 assert 18 in results and 10 in results # Adding one more operand rises number of interpretations to 5 results = p.parse("4 + 2 * 3 + 8") assert len(results) == 5 # One more and there are 14 interpretations results = p.parse("4 + 2 * 3 + 8 * 5") assert len(results) == 14 # The number of interpretation will be the Catalan number of n # where n is the number of operations. # https://en.wikipedia.org/wiki/Catalan_number # This number rises very fast. For 10 operations number of interpretations # will be 16796! # If we rise priority for multiplication operation we reduce ambiguity. # Default production priority is 10. Here we will raise it to 15 for # multiplication. grammar = """ E: E "+" E | E "*" E {15}| "(" E ")" | Number; terminals Number: /\d+/; """ g = Grammar.from_string(grammar) p = GLRParser(g, actions=actions) # This expression now has 2 interpretation: # (4 + (2*3)) + 8 # 4 + ((2*3) + 8) # This is due to associativity of + operation which is not defined. results = p.parse("4 + 2 * 3 + 8") assert len(results) == 2 # If we define associativity for both + and * we have resolved all # ambiguities in the grammar. grammar = """ E: E "+" E {left}| E "*" E {left, 15}| "(" E ")" | Number; terminals Number: /\d+/; """ g = Grammar.from_string(grammar) p = GLRParser(g, actions=actions) results = p.parse("4 + 2 * 3 + 8 * 5 * 3") assert len(results) == 1 assert results[0] == 4 + 2 * 3 + 8 * 5 * 3 def test_epsilon_grammar(): grammar = """ Model: Prods EOF; Prods: Prod | Prods Prod | EMPTY; Prod: ID "=" ProdRefs; ProdRefs: ID | ProdRefs ID; terminals ID: /\w+/; """ g = Grammar.from_string(grammar) p = GLRParser(g, debug=True) txt = """ First = One Two three Second = Foo Bar Third = Baz """ results = p.parse(txt) assert len(results) == 1 results = p.parse("") assert len(results) == 1 def test_non_eof_grammar_nonempty(): """ Grammar that is not anchored by EOF at the end might result in multiple trees that are produced by sucessful parses of the incomplete input. """ grammar_nonempty = """ Model: Prods; Prods: Prod | Prods Prod; Prod: ID "=" ProdRefs; ProdRefs: ID | ProdRefs ID; terminals ID: /\w+/; """ g_nonempty = Grammar.from_string(grammar_nonempty) txt = """ First = One Two three Second = Foo Bar Third = Baz """ p = GLRParser(g_nonempty, debug=True) results = p.parse(txt) # There is three succesful parses. # e.g. one would be the production 'First = One Two three Second' and the # parser could not continue as the next token is '=' but it succeds as # we haven't terminated our model with EOF so we allow partial parses. assert len(results) == 3 def test_non_eof_grammar_empty(): """ Grammar that is not anchored by EOF at the end might result in multiple trees that are produced by sucessful parses of the incomplete input. """ grammar_empty = """ Model: Prods; Prods: Prod | Prods Prod | EMPTY; Prod: ID "=" ProdRefs; ProdRefs: ID | ProdRefs ID; terminals ID: /\w+/; """ g_empty = Grammar.from_string(grammar_empty) txt = """ First = One Two three Second = Foo Bar Third = Baz """ p = GLRParser(g_empty, debug=True) results = p.parse(txt) assert len(results) == 3 results = p.parse("") assert len(results) == 1 <file_sep># History - 2018-09-25 Version 0.8.0 - Implemented table caching. See: https://github.com/igordejanovic/parglare/issues/36 https://github.com/igordejanovic/parglare/issues/52 https://github.com/igordejanovic/parglare/issues/20 parglare will store calculated LR table in `<grammar_file_name>.pgt` file. If the file exists and is newer than all of imported grammar files it will load table from the cached table file. Use `pglr compile` command to produce `.pgt` file in advance. See the docs on `pglr compile` command. - `force_load_table` parser param added that will load parser table if exists without checking modification time. - `pglr check` command changed to `pglr compile` which checks the grammar and produces table file `<grammar_file_name>.pgt`. - Fixes: - Recognizer context passing made more robust. - Fixing location message bug in GrammarError - 2018-09-13 Version 0.7.0 - Rework/cleanup of both LR and GLR parsers. Backward incompatible changes (see below). - Added optional first param to recognizers passing in Context object. See https://github.com/igordejanovic/parglare/pull/55 Thanks jwcraftsman@GitHub - `Context` object now uses `__slots__` and has `extra` attribute for user usage. By default `extra` is initialized to an empty dict if context object is not created by the user. - `dynamic_filter` callback params changed from `action, token, production, subresults, state, context` to `context, action, subresults`. To access previous param values use `context.tokens_ahead` for `token`, `context.production` for `production` and `context.state` for `state`. - `error_recovery` callback params changed from `(parser, input, position, expected_symbols)` to `(context, error)`. To access previous param values use `context.parser`, `context.input_str`, `context.position`, `error.symbols_expected`. The other way to access expected symbols is `context.state.actions.keys()` but in the context of GLR `error.symbols_expected` will give a subset of all possible symbols in the given state for which parser is guaranteed to continue (e.g. to execute SHIFT). - Error recovery function now returns token and position. The error is automatically registered and returned with parsing results. - `custom_lexical_disambiguation` parser param/callback changed to `custom_token_recognition`. - `custom_token_recognition` callback params changed from `symbols, input_str, position, get_tokens` to `context, get_tokens`. To access previous param values use `context.state.actions.keys()` for `symbols`, `context.input_str` and `context.position` for `input_str` and `position`. - Lexical ambiguity results in `DisambiguationError` now instead of `ParseError`for LR parser. - `start_production` parser param now accepts a fully qualified rule name instead of id. First production id for the given rule is used. - `NodeTerm` keeps a reference to the token. `value` is now a read-only property that proxies `token.value`. - Support for arbitrary user meta-data. See issue: https://github.com/igordejanovic/parglare/issues/57 - `ParseError` now has `symbols_expected`, `tokens_ahead` and `symbols_before` attributes. See [Handling errors section](http://www.igordejanovic.net/parglare/0.7/handling_errors/). - 2018-05-24 Version 0.6.1 - Fixed issue with actions resolving search order. - Fixed #31 GLR drops valid parses on lexical ambiguity. - Fix in GLR graphical debug trace. - 2018-05-22 Version 0.6.0 - New feature: grammar modularization - see the docs: http://www.igordejanovic.net/parglare/grammar_modularization/ - Backward incopatibile change: terminals are now specified in a separate section which starts with keyword `terminals`. This section should be defined after production rules. You can still use inline terminals for string matches but not for regex matchers. This change will prevent problems reported on issue #27. See the changes in the docs. - Fixed issue #32 - Conflict between string match and rule with the same name - Various improvements in error reporting, docs and tests. - Support for Python 3.3 dropped. - 2018-03-25 Version 0.5 - Added file_name to the parse context. - Added `re_flags` param to the `Grammar` class factory methods. - Added `_pg_start_position/_pg_end_position` attributes to auto-created objects. - Improved reporting of regex compile errors. Thanks <NAME> (alberth@GitHub)! - Keyword-like string recognizers (matched on word boundaries). Issue: https://github.com/igordejanovic/parglare/issues/12 - Support for case-insensitive parsing. `ignore_case` param to the `Grammar` factory methods. - Added `prefer_shifts` and `prefer_shifts_over_empty` disambiguation strategies. - Introduced disambiguation keywords `shift` and `reduce` as synonyms for `right` and `left`. - Introduced per-production `nops` (no prefer shift) and `nopse` (no prefer shift over empty) for per-production control of disambiguation strategy. - Introduced `nofinish` for terminals to disable `finish` optimization strategy. - Introduced `action` Python decorator for action definition/collection. - Better visuals for killed heads in GLR dot trace. - Fixed multiple rules with assignment bug: Issue: https://github.com/igordejanovic/parglare/issues/23 - Report error on multiple number of actions for rule with multiple productions. - Improved debug/trace output. - Improved parse tree str output. - More tests. - More docs. - Code cleanup and refactorings. - 2017-10-18 Version 0.4.1 - Fix in GLR parser. Parser reference not set on the parser context. - 2017-10-18 Version 0.4 - Added regex-like syntax extension for grammar language (`?`, `*`, `+`). Issue: https://github.com/igordejanovic/parglare/issues/3 - Rule actions can be defined in grammar using `@` syntax for both built-in actions and user supplied ones. Issues: https://github.com/igordejanovic/parglare/issues/1 https://github.com/igordejanovic/parglare/issues/6 - Introduced named matches (a.k.a. assignments). Python classes created for each rule using named matches. Issue: https://github.com/igordejanovic/parglare/issues/2 - Introduced built-in action for creating Python object for rules using named matches. - Colorized and nicely formatted debug/trace output based on `click` package. Issue: https://github.com/igordejanovic/parglare/issues/8 - Introduced `build_tree` parameter for explicitly configuring parser for building a parse tree. - Introducing default actions that build nested lists. Simplifying actions writing. - Added input_str to parser context. - Added `click` dependency. - Reworked `pglr` CLI to use `click`. - Docs reworkings/updates. - Various bugfixes + tests. - 2017-08-24 Version 0.3 - Dynamic disambiguation filters. Introducing `dynamic` disambiguation rule in the grammar. - Terminal definitions with empty bodies. - Improved error reporting in recovery. - Report LR state symbol in conflict debug output. - Report killing head on unsuccessful recovery. - Parameter rename layout_debug -> debug_layout - GLR visual tracing parameter is separated from debug. - Fixing GLR trace visualization. - 2017-08-09 Version 0.2 - GLR parsing. Support for epsilon grammars, cyclic grammars and grammars with infinite ambiguity. - Lexical recognizers. Parsing the stream of arbitrary objects. - Error recovery. Builtin default recovery, custom user defined. - Common semantic actions. - Documentation. - pglr CLI command. - Automata visualization, GLR visual tracing. - Lexical disambiguation improvements. - Support for epsilon grammar (empty productions). - Support for comments in grammars. - `finish` and `prefer` terminal rules. - Change in the grammar language `=` - > `:` - Additions to examples and tests. - Various optimizations and bug fixes. - 2017-02-02 - Version 0.1 - Textual syntax for grammar specification. Parsed with parglare. - SLR and LALR tables calculation (LALR is the default) - Scannerless LR(1) parsing - Scanner is integrated into parsing. This give more power as the token recognition is postponed and done in the parsing context at the current parsing location. - Declarative associativity and priority based conflict resolution for productions - See the `calc` example, or the quick intro below. - Lexical disambiguation strategy. - The default strategy is longest-match first and then `str` over `regex` match (i.e. the most specific match). Terminal priority can be provided for override if necessary. - Semantic actions and default actions which builds the parse tree (controlled by `actions` and `default_actions` parameters for the `Parser` class). - If no actions are provided and the default actions are explicitely disabled parser works as a recognizer, i.e. no reduction actions are called and the only output of the parser is whether the input was recognized or not. - Support for language comments/whitespaces using special rule `LAYOUT`. - Debug print/tracing (set `debug=True` and/or `debug_layout=True`to the `Parser` instantiation). - Tests - Few examples (see `examples` folder) <file_sep>setuptools pip flake8==2.6.0 tox==2.3.1 coverage==4.1 coveralls==1.1 pytest==2.9.2 click==6.7
849b1d1c0be5c4172c1b9894ff2debcee317e3ed
[ "Markdown", "Python", "Text" ]
3
Python
chenl/parglare
72470b012d5c1e144c838c67624c98951c1fbf7f
24fe625913ad373fe6dc25a8e3633c3b96992799
refs/heads/master
<repo_name>shakyShane/ncn-js<file_sep>/js/menu.js (function(window, document) { /** * Select the menu button in the header */ const button = document.querySelector('.menu'); /** * Select the site-nav wrapper */ const nav = document.querySelector('.site-nav'); /** * Finally add a listener */ button.addEventListener('click', function() { nav.classList.toggle('active'); }); /** * Listen for clicks on the entire page * and close the menu if it's open */ document.addEventListener('click', function (e) { if ( nav.classList.contains('active') && !nav.contains(e.target) && e.target !== button ) { nav.classList.remove('active'); } }); })(window, document);
801d8ccad0e51021dc659e7f094d5650041b2f6b
[ "JavaScript" ]
1
JavaScript
shakyShane/ncn-js
e739d0ca7a3aee7c44490573f5caeeb8bcdc5561
667e0b4d8076c72b75760c2e5ab66231475dfad1
refs/heads/main
<repo_name>Anushreejain27/tower-siege2<file_sep>/block.js class block{ constructor(x,y){ var options={ isStatic:false, restitution : 0.2, friction : 1.2, density : 0.01, visiblity:255 } this.visiblity=255 this.body=Bodies.rectangle(x,y,45,55,options) this.width=45 this.height=55 World.add(world,this.body) } display(){ if (this.body.speed<3){ push() rectMode(CENTER) //fill("yellow") stroke("white") fill("black") strokeWeight(4) //tint(255, 126) rect(this.body.position.x,this.body.position.y,this.width,this.height) pop() } else{ World.remove(world,this.body) push() this.visiblity=this.visiblity-5 tint(255,this.visiblity) rect(this.body.position.x,this.body.position.y,this.width,this.height) pop() } } }
54637e41aabd9a85f61c4434a172a6554fa09ccc
[ "JavaScript" ]
1
JavaScript
Anushreejain27/tower-siege2
8d43e189aee718fc86d7565104dbc5b154c78eda
0333b011d957096a349205fbeb34448e5731feb4
refs/heads/master
<repo_name>kyunwang/Riddleship<file_sep>/public/scripts/back.js // Source: http://javabeat.net/javascript-snippets-back-button/ const backBtn = document.querySelector('[data-back]'); backBtn.classList.remove('noJs'); backBtn.addEventListener('click', () => { history.go(-1); }); <file_sep>/app.js const path = require('path'); const express = require('express'), bodyparser = require('body-parser'), multer = require('multer'), session = require('express-session'), validator = require('express-validator'), mysql = require('mysql'), myConnection = require('express-myconnection'); const port = 3000; const app = express(); // 'importing' the routes const index = require('./routes/index'), user = require('./routes/user'), admin = require('./routes/admin'), api = require('./routes/api'); var myID; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // defining upload destination var upload = multer({dest: 'public/uploads/'}); // mysql connection app.use(myConnection(mysql, { host: '127.0.0.1', user: 'root', password: '<PASSWORD>', // socketPath : '/Applications/MAMP/tmp/mysql/mysql.sock', port: 3306, database: 'riddleshipdb' } , 'request')); // body parser middleware app.use(bodyparser.json()); app.use(bodyparser.urlencoded({extended: false})); app.use(upload.single('profilePic')); // this line must be immediately after any of the bodyParser middlewares! app.use(validator({ errorFormatter: function(param, msg, value) { var namespace = param.split('.') , root = namespace.shift() , formParam = root; while (namespace.length) { formParam += '[' + namespace.shift() + ']'; } return { param: formParam, msg: msg, value: value }; } })); app.use(session({ secret: 'MisterChocolateMintVanillaIceCreamThe3rd!Is3x3#PlaceChampion', resave: false, saveUnitialized: true })); // Set static path app.use(express.static(path.join(__dirname, 'public'))); // Global variables app.use((req, res, next) => { res.locals.loggedIn = req.session.loggedIn; res.locals.admin = req.session.admin; res.locals.myName = req.session.myName; next(); }); // Use the defined routes app.use('/', index); app.use('/', user); app.use('/', admin); app.use('/', api); // Source: 404 http://www.hacksparrow.com/express-js-custom-error-pages-404-and-500.html app.use(function(req, res) { res.status(404); res.render('404.ejs', {title: '404: File Not Found', message: "This page is still in construction or doesn't exist(yet)"}); }); app.listen(port, () => { console.log(`Listening at port ${port}`); }); <file_sep>/routes/admin.js const express = require('express'); const router = express.Router(); router.get('/dashboard', (req, res) => { res.render('admin/dashboard'); }); // not made yet // router.get('/reported', (req, res) => { // res.render('admin/reported'); // }); router.get('/users', (req, res) => { req.getConnection((err, connection) => { if(err) return next(err); connection.query('SELECT * FROM user WHERE admin = 0', (err, results) => { if (err) return next(err); res.locals.results = results; res.render('admin/users'); }); }); }); router.get('/users/online', (req, res) => { res.render('admin/users_online'); }); router.get('/users/banned', (req, res) => { req.getConnection((err, connection) => { if (err) return next(err); connection.query('SELECT * FROM user WHERE banned = 1', (err, results) => { if (err) return next(err); res.render('admin/users_ban', {results: results}); }); }); }); router.post('/users/ban/:id', (req, res) => { req.getConnection((err, connection) => { if (err) return next(err); connection.query('UPDATE user SET banned = 1 WHERE userID = ?', req.params.id, (err, results) => { if (err) return next(err); res.end(); }); }); }); router.post('/users/unban/:id', (req, res) => { req.getConnection((err, connection) => { if (err) return next(err); connection.query('UPDATE user SET banned = 0 WHERE userID = ?', req.params.id, (err, results) => { if (err) return next(err); res.end(); }); }); }); router.get('/users/delete/:id', (req, res) => { req.getConnection((err, connection) => { if (err) return next(err); connection.query('SELECT name, userID FROM user WHERE userID = ?', req.params.id, (err, results) => { if (err) return next(err); res.render('admin/deleteUser', {results: results[0]}); }) }); }); router.post('/users/delete/:id', (req, res, next) => { req.getConnection((err, connection) => { if (err) return next(err); connection.query('DELETE FROM user WHERE userID = ?', req.params.id, (err, results) => { if (err) return next(err); res.redirect('/users/'); }); }); }); module.exports = router; <file_sep>/public/scripts/banPopUp.js // Sources for AJAX // <NAME>: https://github.com/CMDA/backend-example // http://youmightnotneedjquery.com/ const togglePopUp = document.querySelectorAll('[data-id]'); const popUp = document.querySelector('#popUp'); const popUpLinks = document.querySelectorAll('#popUp button'); const banText = document.querySelector('#popUp p'); for (let i = 0; i < togglePopUp.length; i++) { togglePopUp[i].addEventListener('click', getData); // } popUpLinks[0].addEventListener('click', hidePopUp); // add event to the cancel btn to hide the popup function hidePopUp(event) { popUp.classList.add('hide'); } function getData(event) { event.preventDefault(); const node = event.target; const request = new XMLHttpRequest(); request.open('GET', '/api/' + node.dataset.id , true); request.onload = onload; request.send(); function onload() { if (request.status != 200) { // We reached our target server, but it returned an error console.log('sorry mate'); } else { let userData = JSON.parse(request.responseText); // checks whether user if (userData[0].banned === 1) { popUpLinks[1].innerHTML = 'unban'; banText.innerHTML = `Are you sure that you want to unban ${userData[0].name}?`; } else { popUpLinks[1].innerHTML = 'ban'; banText.innerHTML = `Are you sure that you want to ban ${userData[0].name}?`; } popUp.classList.remove('hide'); // show the pop up after assigning the values popUpLinks[1].addEventListener('click', function() { banDecision(userData[0]); }); } } } function banDecision(userBan) { const dataId = document.querySelector(`[data-id="${userBan.userID}"]`); // to change the button text const request = new XMLHttpRequest(); // sends a post request to ban user if not banned else unban if (userBan.banned) { request.open('POST', '/users/unban/' + userBan.userID, true); dataId.innerHTML = 'ban user'; } else { request.open('POST', '/users/ban/' + userBan.userID, true); dataId.innerHTML = 'unban user'; } request.onload = onload; request.send(); function onload() { if (request.status != 200) { console.log('sorry mate'); } } hidePopUp(); // hide the popup after banning/unbanning } <file_sep>/public/scripts/toggleList.js const UserMenu = function (element) { this.root = element; this.btnToggle = this.root.querySelectorAll('button'); this.menuList = this.root.querySelectorAll('.userMenu'); // Adding click events to all buttons and adding the corresponding list with it for (let i = 0; i < this.btnToggle.length; i++) { this.btnToggle[i].addEventListener('click', (element) => { // element.preventDefault(); // Prevent the default action this.menuToggle(this.menuList[i]); }); } }; UserMenu.prototype.menuToggle = element => { element.classList.toggle('hide'); }; const userTableRoot = document.querySelector('main') const ownTableMenu = new UserMenu(userTableRoot);
b81f1f21d7942f5f979076cbeebaf0ac29622ad3
[ "JavaScript" ]
5
JavaScript
kyunwang/Riddleship
90fe0abbc6c925ca5a9e4c762c645b9d8423452e
2408c38371fe24edd2509d007f730d9ceadc195f
refs/heads/master
<file_sep>import { UserCredentialsDbAccess } from 'app/Authorization/UserCredentialsDbAccess' import { UserCredentials } from 'app/Models/ServerModels'; describe('User Credentials test suite', () => { let userCredentialsDBAccess: UserCredentialsDbAccess; const username = 'user'; const password = '<PASSWORD>'; const someCredentials: UserCredentials = { accessRights: [1,2,3], username, password } const nedbMock = { insert: jest.fn(), find: jest.fn(), loadDatabase: jest.fn() } beforeEach(() => { userCredentialsDBAccess = new UserCredentialsDbAccess(nedbMock as any); expect(nedbMock.loadDatabase).toBeCalled(); }); afterEach(() => { jest.clearAllMocks() }); test('putUserCredential without error', async () => { nedbMock.insert.mockImplementationOnce( (err, callback: any) => callback(null, someCredentials) ); const resultCredentials = await userCredentialsDBAccess.putUserCredential(someCredentials); expect(resultCredentials).toEqual(someCredentials); expect(nedbMock.insert).toBeCalledWith(someCredentials, expect.any(Function)); }); test('putUserCredentials with error message', async () => { nedbMock.insert.mockImplementationOnce( (err, callback: any) => callback(new Error('error'), null) ); await expect(userCredentialsDBAccess.putUserCredential(someCredentials)).rejects.toThrowError('error'); expect(nedbMock.insert).toBeCalledWith(someCredentials, expect.any(Function)); }); test('getUserCredential without error and with the data', async () => { nedbMock.find.mockImplementationOnce( (err, callback: any) => callback(null, [someCredentials]) ); const resultCredentials = await userCredentialsDBAccess.getUserCredential(username, password); expect(resultCredentials).toEqual(someCredentials); expect(nedbMock.find).toBeCalledWith({username, password}, expect.any(Function)); }); test('getUserCredential without error and without any data', async () => { nedbMock.find.mockImplementationOnce( (err, callback: any) => callback(null, []) ); const resultCredentials = await userCredentialsDBAccess.getUserCredential('username', '<PASSWORD>'); expect(resultCredentials).toBeNull; expect(nedbMock.find).toBeCalledWith({username: 'username', password: '<PASSWORD>'}, expect.any(Function)); }); test('getUserCredentials with error message', async () => { nedbMock.find.mockImplementationOnce( (err, callback: any) => callback(new Error('error'), null) ); await expect(userCredentialsDBAccess.getUserCredential('' , '')).rejects.toThrowError('error'); expect(nedbMock.find).toBeCalledWith({username: '', password: ''}, expect.any(Function)); }); }) <file_sep>import { UserCredentialsDbAccess } from 'app/Authorization/UserCredentialsDbAccess'; import { HTTP_CODES, SessionToken, UserCredentials } from 'app/Models/ServerModels'; import * as axios from 'axios'; axios.default.defaults.validateStatus = () => true; const serverUrl = 'http://localhost:8080'; const itestUserCredentials: UserCredentials = { accessRights: [1,2,3], password: '<PASSWORD>', username: 'iTestUser' } describe('Server itest suite', () => { let userCredentialsDBAccess: UserCredentialsDbAccess; let sessionToken: SessionToken; beforeAll(() => { userCredentialsDBAccess = new UserCredentialsDbAccess(); }) test('should reach the server', async () => { const response = await axios.default.options(serverUrl); expect(response.status).toBe(HTTP_CODES.OK); }); test('should reject invalid credentials', async () => { const response = await axios.default.post( serverUrl + '/login', { 'username': 'someWrongUsername', 'password': 'any'} ); expect(response.status).toBe(HTTP_CODES.NOT_fOUND); }); test('should login successfully with the correct credentials', async () => { const response = await axios.default.post( serverUrl + '/login', { 'username': itestUserCredentials.username, 'password': itestUserCredentials.password} ); expect(response.status).toBe(HTTP_CODES.CREATED); sessionToken = response.data; }); test('should query data', async () => { const response = await axios.default.get( serverUrl + '/users?name=some', { headers: { Authorization: sessionToken.tokenId }} ); expect(response.status).toBe(HTTP_CODES.OK); }); test('query data with invalid token', async () => { const response = await axios.default.get( serverUrl + '/users?name=some', { headers: { Authorization: sessionToken.tokenId + 'someTrash' }} ); expect(response.status).toBe(HTTP_CODES.UNAUTHORIZED); }); }); <file_sep>import { Authorizer } from 'app/Authorization/Authorizer' import { SessionTokenDBAccess } from 'app/Authorization/SessionTokenDBAccess'; import { UserCredentialsDbAccess } from 'app/Authorization/UserCredentialsDbAccess'; import { Account, SessionToken, TokenState } from 'app/Models/ServerModels'; jest.mock('app/Authorization/SessionTokenDBAccess'); jest.mock('app/Authorization/UserCredentialsDbAccess'); const someAccount: Account = { username: 'someUser', password: '<PASSWORD>' } describe('Authorizer test suite', () => { let authorizer: Authorizer; const sessionTokenDBAccessMock = { storeSessionToken: jest.fn(), getToken: jest.fn() }; const userCredentialsDbAccessMock = { getUserCredential: jest.fn() }; beforeEach(() => { authorizer = new Authorizer( sessionTokenDBAccessMock as any, userCredentialsDbAccessMock as any ) }); afterAll(() => { jest.clearAllMocks(); }); test('constructor arguments', () => { new Authorizer(); expect(SessionTokenDBAccess).toBeCalledTimes(1); expect(UserCredentialsDbAccess).toBeCalledTimes(1); }); describe('login user test suite', () => { test('should return null for invalid credentials', async () => { userCredentialsDbAccessMock.getUserCredential.mockReturnValueOnce(null); const loginResult = await authorizer.generateToken(someAccount); expect(loginResult).toBeNull; expect(userCredentialsDbAccessMock.getUserCredential).toBeCalledWith( someAccount.username, someAccount.password ); }) test('should return sessionToken for valid credentials', async () => { jest.spyOn(global.Math, 'random').mockReturnValueOnce(0); jest.spyOn(global.Date, 'now').mockReturnValueOnce(0); userCredentialsDbAccessMock.getUserCredential.mockResolvedValueOnce({ username: 'someUser', accessRights: [1,2,3] }); const expectedSessionToken: SessionToken = { userName: 'someUser', accessRights: [1,2,3], valid: true, tokenId: '', expirationTime: new Date(60 * 60 * 1000) } const sessionToken = await authorizer.generateToken(someAccount); expect(expectedSessionToken).toEqual(sessionToken); expect(sessionTokenDBAccessMock.storeSessionToken).toBeCalledWith(sessionToken); }); }); describe('validateToken tests', () => { test('should return valid access rights and state for valid token', async () => { const dateInFuture = new Date(Date.now() + 100000); sessionTokenDBAccessMock.getToken.mockReturnValueOnce({ valid: true, expirationTime: dateInFuture, accessRights: [1,2,3] }); const sessionToken = await authorizer.validateToken(''); expect(sessionToken).toStrictEqual({ accessRights: [1,2,3], state: TokenState.VALID }); }); test('should return invalid state and empty access rights for invalid token', async () => { sessionTokenDBAccessMock.getToken.mockReturnValueOnce(null); const sessionToken = await authorizer.validateToken(''); expect(sessionToken).toStrictEqual({ accessRights: [], state: TokenState.INVALID }); }); test('should return expired state for the expired token', async () => { const dateInPast = new Date(Date.now() - 1); sessionTokenDBAccessMock.getToken.mockReturnValueOnce({ valid: true, expirationTime: dateInPast }); const sessionToken = await authorizer.validateToken(''); expect(sessionToken).toStrictEqual({ accessRights: [], state: TokenState.EXPIRED }); }); }); }); <file_sep># Typescript unit testing<file_sep>import { SessionTokenDBAccess } from 'app/Authorization/SessionTokenDBAccess' import { SessionToken } from 'app/Models/ServerModels'; describe('SessionToken DB Access test suite', () => { let sessionTokenDBAccess: SessionTokenDBAccess; const someToken: SessionToken = { accessRights: [], expirationTime: new Date(), tokenId: '123', userName: 'John', valid: true }; const someTokenId = '123'; const nedbMock = { loadDatabase: jest.fn(), insert: jest.fn(), find: jest.fn() }; beforeEach(() => { sessionTokenDBAccess = new SessionTokenDBAccess(nedbMock as any); expect(nedbMock.loadDatabase).toBeCalled(); }); afterEach(() => { jest.clearAllMocks(); }); test('store sessionToken without error', async () => { nedbMock.insert.mockImplementationOnce( (someToken: any, callback: any) => { callback() } ) await sessionTokenDBAccess.storeSessionToken(someToken); expect(nedbMock.insert).toBeCalledWith(someToken, expect.any(Function)); }) test('store sessionToken with error', async () => { nedbMock.insert.mockImplementationOnce( (someToken: any, callback: any) => { callback(new Error('Something went wrong!')) } ) await expect(sessionTokenDBAccess.storeSessionToken(someToken)).rejects.toThrowError('Something went wrong!'); expect(nedbMock.insert).toBeCalledWith(someToken, expect.any(Function)); }) test('get token without error and with the result', async () => { nedbMock.find.mockImplementationOnce( (someTokenId: string, callback: any) => { callback(null, [someToken]) } ) const getTokenResult = await sessionTokenDBAccess.getToken(someTokenId); expect(getTokenResult).toBe(someToken); expect(nedbMock.find).toBeCalledWith({tokenId: someTokenId }, expect.any(Function)); }) test('get token without error and without the result', async () => { nedbMock.find.mockImplementationOnce( (someTokenId: string, callback: any) => { callback(null, []) } ) const getTokenResult = await sessionTokenDBAccess.getToken('1234'); expect(getTokenResult).toBeUndefined(); expect(nedbMock.find).toBeCalledWith({tokenId: '1234' }, expect.any(Function)); }) test('get token throws an error and gives no result', async () => { nedbMock.find.mockImplementationOnce( (someTokenId: string, callback: any) => { callback(new Error('something went wrong'), []) } ); await expect(sessionTokenDBAccess.getToken(someTokenId)).rejects.toThrowError('something went wrong'); expect(nedbMock.find).toBeCalledWith({tokenId: someTokenId }, expect.any(Function)); }) })
9f1505bbd0ea7ad61bc1d7413c8be0682f91af8b
[ "Markdown", "TypeScript" ]
5
TypeScript
kucabix/ts-unit-testing
c3a339cb93f2a185715336676f3b17629fe8739a
f9f3bf1a7610a0f0182d8fd02d037eda87c69794
refs/heads/main
<file_sep>import React, { useContext, useState, useEffect, useRef } from 'react'; import { Input, Button, Form, } from 'antd'; import "../../css/AdminPage.css"; import {updateBook, getBookById, getBooks} from "../../service/BookService"; const EditableContext = React.createContext(null); const { TextArea } = Input; const formItemLayout = { labelCol: { xs: {span: 24}, sm: {span: 8}, }, wrapperCol: { xs: {span: 24}, sm: {span: 16}, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 16, offset: 8, }, }, }; const ModifyBook=(data)=>{ const onFinishFailed = (errorInfo) => { console.log('ModifyBook Failed:', errorInfo); }; const handleSubmit =(values) => { console.log('ModifyBook Received values of form:',values); updateBook(values); window.location.href = "../admin/2"; } let book=null; const [form] = Form.useForm(); const handleBook=(detail)=>{ book=detail; console.log("handlebook called"); // console.log(book); form.setFieldsValue({ name:book.name, author:book.author, price:book.price.toFixed(2), inventory:book.inventory, description:book.description, brief:book.brief, type:book.type, image:book.image, isbn:book.isbn, bookId:book.bookId, }) } useEffect(()=>{ getBookById(data.id,handleBook); }); return ( <div> <h3 style={{marginLeft: 50}}>修改图书信息</h3> <div className="addbook-container"> <Form {...formItemLayout} form={form} name="modifybook" onFinish={handleSubmit} onFinishFailed={onFinishFailed} scrollToFirstError className="addbook-form" > <Form.Item name="bookId" label="图书编号" // rules={[ // { // required: false, // whitespace: true, // }, // ]} > <Input disabled="true"/> </Form.Item> <Form.Item name="name" label="名称" hasFeedback rules={[ { required: true, message: '请输入图书名称。', whitespace: true, }, ]} > <Input/> </Form.Item> <Form.Item name="author" label="作者" hasFeedback rules={[ { required: true, message: '请输入图书作者。', }, ]} > <Input/> </Form.Item> <Form.Item name="price" label="价格" dependencies={['password']} hasFeedback rules={[ { required: true, pattern: new RegExp(/^(([1-9]\d*)|\d)(\.\d{1,2})?$/, 'g'), message: '请输入正确的图书价格(最多两位小数)。', }, ]} > <Input/> </Form.Item> <Form.Item name="isbn" label="ISBN" hasFeedback rules={[ { required: true, message: '请输入图书的ISBN号(13位数字)。', whitespace: true, pattern: new RegExp(/\d{13}$/, 'g'), }, ]} > <Input/> </Form.Item> <Form.Item name="inventory" label="库存量" hasFeedback rules={[ { required: true, message: '请输入正确的库存量(正整数)。', whitespace: true, pattern: new RegExp(/^[1-9]\d*$/, 'g'), }, ]} > <Input/> </Form.Item> <Form.Item name="description" label="详情" hasFeedback rules={[ { required: true, message: '请输入书籍详情。', whitespace: true, }, ]} > <TextArea/> </Form.Item> <Form.Item name="image" label="封面地址" hasFeedback rules={[ { required: true, message: '请输入正确的封面地址。', pattern: new RegExp( "^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&amp;%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&amp;%\$#\=~_\-]+))*$"), whitespace: true, }, ]} > <TextArea/> </Form.Item> <Form.Item name="type" label="类别" hasFeedback rules={[ { required: true, message: '请输入书籍类别。', whitespace: true, }, ]} > <Input/> </Form.Item> <Form.Item name="brief" label="简介" hasFeedback rules={[ { required: true, message: '请输入书籍简介。', whitespace: true, }, ]} > <TextArea/> </Form.Item> <Form.Item {...tailFormItemLayout}> <Button type="primary" htmlType="submit" block="true"> 提交 </Button> </Form.Item> </Form> </div> </div> ); }; export default ModifyBook;<file_sep>import React from 'react'; import {Descriptions, Button, InputNumber, Divider, message} from 'antd'; import "../../css/BookPage.css"; import img from "../../resources/book/book_1.jpg" import {ShoppingCartOutlined} from "@ant-design/icons"; import {getBookById} from "../../service/BookService"; import {addCartItem} from "../../service/CartService"; export class BookDetail extends React.Component { constructor(props) { super(props); this.state={ detail:null, amount:1, success:false, } } handleDetail = data => { this.setState({ detail: data, }); } componentDidMount() { getBookById(this.props.bookId,this.handleDetail); } onChange_input = value => { console.log("value"); this.state.amount=value; } onAddCartItem = (e) => { message .loading("加入购物车中...") .then( () => { console.log("addCartItem: "+this.props.bookId+" "+this.state.amount); addCartItem(this.props.bookId,this.state.amount,1); } ) .then( ()=> { message.success("加入购物车成功!") }); }; render() { if(this.state.detail==null) return null; console.log(this.state.detail); return ( <div className={"content"}> <div className={"book-detail"} style={{display: 'inline-block'}}> <div className={"book-image"} style={{display: 'inline-block'}}> <img alt="image" src={this.state.detail.image} style={{width: "400px", height: "400px"}}/> </div> <div className={"descriptions"} style={{display: 'inline-block', left: 500}}> <Descriptions> <Descriptions.Item contentStyle={{fontSize: 100}} className={"title"} span={3}>{this.state.detail.name} </Descriptions.Item> <Descriptions.Item className={"book-brief"} span={3}>{this.state.detail.brief}</Descriptions.Item> <Descriptions.Item label={"作 者"} span={3}>{this.state.detail.author}</Descriptions.Item> <Descriptions.Item label={"分 类"} span={3}>{this.state.detail.type}</Descriptions.Item> <Descriptions.Item className={"price"} label={"价 格"} span={3}>{'¥' + this.state.detail.price.toFixed(2)} <div className={"original-price"}> ¥158.00 </div> </Descriptions.Item> <Descriptions.Item label={"状 态 "} className={"book-condition"} span={3}>{this.state.detail.inventory !== 0 ? <span>有货 <span className={"inventory"}>库存{this.state.detail.inventory}件</span></span> : <span className={"status"}>无货</span>}</Descriptions.Item> <Descriptions.Item label={"ISBN"} span={3}>{this.state.detail.isbn}</Descriptions.Item> <Descriptions.Item label={"作品简介"} span={3}>{this.state.detail.description}</Descriptions.Item> <Descriptions.Item className={"input-button"} style={{display: 'block'}}> <div> 数量:</div> <InputNumber min={1} max={this.state.detail.inventory} defaultValue={1} onChange={this.onChange_input} className={"input-button"}/> </Descriptions.Item> <Descriptions.Item className={"button-groups"} style={{display: 'block'}}> <Button type="primary" danger icon={<ShoppingCartOutlined/>} size={"large"} className={"cart-button"} onClick={this.onAddCartItem}> 加入购物车 </Button> {/*<Button danger size={"large"} className={"buy-button"}>*/} {/* 立即购买*/} {/*</Button>*/} </Descriptions.Item> </Descriptions> </div> </div> </div> ); } } export default BookDetail;<file_sep>import React from 'react'; import MyFooter from "../components/footer"; import {Layout} from 'antd'; import {withRouter} from 'react-router-dom'; import "../css/HomePage.css"; import HeadWrap from "../components/HeadWrap"; import SideBar from "../components/SideBar"; import BookStats from "../components/UserPage/BookStats"; class UserView extends React.Component { constructor(props) { super(props); } render() { return ( <div className="user-page"> <div className="head-container"> <HeadWrap/> </div> <div className="user-container"> <Layout className="bookview-layout"> <SideBar selected={"5"}/> <div className="userorder-container"> <BookStats isadmin={"0"}/> </div> </Layout> <MyFooter/> </div> </div> ) } }; export default withRouter(UserView);<file_sep>import React from 'react'; import {Table, Button, ImportNumber} from "antd"; import { getCartItems, deleteCartItem, setCartItem } from "../../service/CartService"; import "../../css/CartPage.css"; const columns = [ { title: '商品信息', dataIndex: 'name', }, { title: '价格(元)', dataIndex: 'price', }, { title: '数量', dataIndex: 'number', }, { title: '小计', dataIndex: 'total' }, { title: '操作', dataIndex: 'operation' } ]; class CartTable extends React.Component { state = { selectedRowKeys: [], loading: false, cart:[], }; start = () => { this.setState({loading: true}); // ajax request after empty completing setTimeout(() => { this.setState({ selectedRowKeys: [], loading: false, }); }, 1000); }; handleDelete(data,event){ console.log(data); deleteCartItem(data); // this.setState({data:data}); } handleCartItems = data => { console.log("handleCartItems:"); console.log(data); let tmp=[]; for(let i in data) { tmp.push( { id: i, // must add id in order to apply rowSelection name: data[i].book.name, price: data[i].book.price.toFixed(2), number: data[i].amount, total: (data[i].book.price*data[i].amount).toFixed(2), operation: <a onClick={this.handleDelete.bind(this,data[i].bookId)}>删除</a>, bookId: data[i].bookId, } ); } this.setState({ cart:tmp, }) } onSelectChange = selectedRowKeys => { console.log('selectedRowKeys changed: ', selectedRowKeys); this.setState({selectedRowKeys}); for(let i in this.state.cart) { if(this.state.selectedRowKeys.includes(i)) { console.log("setCartItem: "+this.state.cart[i].bookId+" 1"); setCartItem(this.state.cart[i].bookId,1); } else { console.log("setCartItem: "+this.state.cart[i].bookId+" 0"); setCartItem(this.state.cart[i].bookId,0); } } }; handleClick = (e) => { this.onSelectChange(this.state.selectedRowKeys); window.location.href="/order"; } componentDidMount() { getCartItems(this.handleCartItems); } render() { const {loading, selectedRowKeys} = this.state; const rowSelection = { selectedRowKeys, onChange: this.onSelectChange, }; const hasSelected = selectedRowKeys.length > 0; console.log("cart=",this.state.cart); return ( <div className="carttable-container"> <Table rowSelection={rowSelection} columns={columns} rowKey={record=>record.id} dataSource={this.state.cart}/> <div className="cartfoot-container" style={{marginBottom: 16}}> <span style={{marginLeft: 8}} className="cartspan-container"> {hasSelected ? (<span> 已选 <span class="cart-totalcount"> {selectedRowKeys.length}</span> 项商品 </span>) : ''} </span> <Button type="primary" className="cartbutton-container" onClick={this.handleClick} disabled={!hasSelected} loading={loading}> 去结算 </Button> </div> </div> ); } } export default CartTable;<file_sep>package com.bookstore.dao; import com.bookstore.entity.Book; import com.github.pagehelper.PageInfo; import java.util.List; import java.util.Map; public interface BookDao { Book getBookByBookId(Integer bookId); List<Book> getBooks(); void deleteBookByBookId(Integer bookId); void addBook(Map<String, String> params); List<Book> getBookByName(String name); void updateBook(Map<String,String> params); PageInfo<Book> getBooksByPage(Integer num); } <file_sep>import postRequest from "../utils/ajax"; import {message} from "antd"; import {history} from "../utils/history"; export function getBooksByPage(num,callback) { const url=`http://localhost:8080/getBooksByPage?num=${Number(num)}`; postRequest(url,{},callback); } export function getBookById(bookId, callback) { const url=`http://localhost:8080/getBookById?id=${Number(bookId)}`; postRequest(url,{},callback); } export function getBookByName(name,callback) { const url=`http://localhost:8080/getBookByName?name=${name}`; postRequest(url,{},callback); } export function deleteBookById(id,callback) { const url=`http://localhost:8080/deleteBookById?id=${id}`; postRequest(url,{},callback); } export function addBook(data,callback) { const url = `http://localhost:8080/addBook`; postRequest(url, data, callback); } export function updateBook(data,callback) { const url=`http://localhost:8080/updateBook`; postRequest(url,data,callback); } export function getBooks(callback) { const url=`http://localhost:8080/getBooks`; postRequest(url,{},callback); }<file_sep>package com.bookstore.entity; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.FetchType; import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Data class PrimaryKey_OrderItem implements Serializable { private Integer orderId; private Integer bookId; } @Data @Entity @Table(name = "order_item") @IdClass(PrimaryKey_OrderItem.class) @JsonIgnoreProperties(value = {"handler","hibernateLazyInitializer","fieldHandler"}) //@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "bookId") public class OrderItem{ @Id private Integer orderId; @Id @Column(name="book_id",insertable = false, updatable = false) private Integer bookId; private Integer amount; // private Double price; @ManyToOne(fetch= FetchType.EAGER) @JoinColumn(name="book_id",referencedColumnName = "book_id") //@NotFound(action= NotFoundAction.IGNORE) private Book book; } <file_sep>package com.bookstore.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.math.BigDecimal; import javax.persistence.Entity; import javax.persistence.Table; import lombok.Data; @Data @Table(name = "user") @JsonIgnoreProperties(value = {"handler", "hibernateLazyInitializer", "fieldHandler"}) public class OrderStat { private Integer bookId; private String name; private Integer amount; private BigDecimal price; } <file_sep>import React from 'react'; import {withRouter} from 'react-router-dom'; import {Layout, Divider, Button} from 'antd'; import MyFooter from "../components/footer.js"; import "../css/OrderPage.css"; import HeadWrap_CartPage from "../components/OrderPage/HeadWrap"; import OrderTable from "../components/OrderPage/OrderTable"; import {submitCart} from "../service/CartService"; import SideBar from "../components/SideBar"; class OrderView extends React.Component { handleSubmit =() => { console.log("handleSubmit Order"); submitCart(); window.location.href="/success"; } render() { return ( <div className="order-container"> <HeadWrap_CartPage/> {/*<Divider style={{marginTop: 40}}/>*/} <Layout className="bookview-layout"> <SideBar selected={"3"}/> <div className="ordercontent-container"> <div className="order-title">送货清单</div> <div className="order-content"> <div className="order-table"> <OrderTable/> <div className="cartfoot-container" style={{marginBottom: 16}}> <Button type="primary" className="orderbutton-container" onClick={this.handleSubmit} > 支付订单 </Button> </div> </div> </div> </div> </Layout> <MyFooter/> </div> ); } } export default withRouter(OrderView);<file_sep>import React from "react"; import {Avatar, Dropdown, Menu} from 'antd'; import {UserOutlined} from '@ant-design/icons'; import {login, logout,getUser} from "../service/UserService"; import "../css/HomePage.css" class UserAvatar extends React.Component { constructor(props) { super(props); this.state={ username: "Hi, please login", } } handleUser = data => { if(data.name!=undefined) { this.setState({ username: "Hi, "+data.name, }) } } componentDidMount() { getUser(this.handleUser); } handleLogout =() => { // console.log('Received values of form:',values); logout(); } render() { const menu = ( <Menu> {/*<Menu.Item>*/} {/* <a target="_blank" rel="noopener noreferrer"*/} {/* href="http://www.alipay.com/">*/} {/* 用户信息*/} {/* </a>*/} {/*</Menu.Item>*/} <Menu.Item> <a onClick={this.handleLogout}> 登出 </a> </Menu.Item> {/*<Menu.Item>*/} {/* <a href="../register">*/} {/* 注册*/} {/* </a>*/} {/*</Menu.Item>*/} </Menu> ); return ( <div id="avatar" className="avatar-container"> <Dropdown overlay={menu} placement="bottomRight"> <Avatar icon={<UserOutlined/>} size={"large"} style={{cursor: "pointer", backgroundColor: '#87d068'}}/> </Dropdown> <span className="avatar-name">{this.state.username}</span> </div> ); } } export default UserAvatar;<file_sep>package com.bookstore.utils.messageUtils; import net.sf.json.JSONObject; public class Message { private int status; private String message; private JSONObject data; Message(int status, String message, JSONObject data) { this.status = status; this.message = message; this.data = data; } Message(int status, String message) { this.status = status; this.message = message; this.data = null; } public String getMessage() { return message; } public int getStatus() { return status; } public JSONObject getData() { return data; } } <file_sep>import React from 'react'; import {withRouter} from "react-router-dom"; import MyFooter from "../components/footer" import RegisterForm from "../components/RegisterPage/RegisterForm.js"; import {Layout, Divider} from 'antd'; import 'antd/dist/antd.css' import logo from '../resources/logo.svg' const {Header, Content, Footer} = Layout; class RegisterView extends React.Component { render() { return ( <div className="register-page"> <div className="register-container"> <div className="logo-container"> <img className="logo-image" src={logo} alt="logo"/> <span class="title-text">用户注册</span> </div> <Content className="RegisterBox-container"> <div className="RegisterBox-wrap"> <div className="RegisterForm-container"> <RegisterForm/> </div> </div> </Content> <Footer> <MyFooter/> </Footer> </div> </div> ); } } export default withRouter(RegisterView);<file_sep>import React from 'react'; import {Table, Tag, Space, Image, Popconfirm, Input, Button} from 'antd'; import {getBooksByPage} from "../../service/BookService"; import {SearchOutlined} from "@ant-design/icons"; import Highlighter from "react-highlight-words"; import "../../css/AdminPage.css"; class BooksTable extends React.Component { constructor(props) { super(props); this.columns= [ { title:'图书编号', dataIndex:'bookId', width:'10%', className:'column-book', }, { title: '书名', dataIndex: 'name', width: '15%', className:'column-book', ...this.getColumnSearchProps('name'), }, { title: '作者', dataIndex: 'author', width:'15%', className:'column-book', }, { title:'封面', dataIndex:'image', width:'20%', className:'column-book', render:(record)=> { console.log("render image:"); console.log(record); return <Image className="image-small" src={record}/> }, }, { title: 'ISBN编号', dataIndex: 'isbn', width:'5%', className:'column-book', }, { title: '库存量', dataIndex: 'inventory', width:'10%', className:'column-book', }, ]; this.state = { dataSource: null, count: 0, searchText: '', searchedColumn: '', }; } getColumnSearchProps = dataIndex => ({ filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => ( <div style={{ padding: 8 }}> <Input ref={node => { this.searchInput = node; }} placeholder={`搜索书名`} value={selectedKeys[0]} onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])} onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)} style={{ width: 188, marginBottom: 8, display: 'block' }} /> <Space> <Button type="primary" onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)} icon={<SearchOutlined />} size="small" style={{ width: 90 }} > 搜索 </Button> <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}> 复位 </Button> </Space> </div> ), filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />, onFilter: (value, record) => record[dataIndex] ? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()) : '', onFilterDropdownVisibleChange: visible => { if (visible) { setTimeout(() => this.searchInput.select(), 100); } }, render: text => this.state.searchedColumn === dataIndex ? ( <Highlighter highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }} searchWords={[this.state.searchText]} autoEscape textToHighlight={text ? text.toString() : ''} /> ) : ( text ), }); handleBooks =(data) => { console.log("handle books:"); console.log(data); let ans=[]; for(let i=0;i<(data.pageNum-1)*5;i++) { ans.push(null); } for(let i=0;i<data.list.length;i++){ ans.push(data.list[i]); } let res=data.total-ans.length; for(let i=0;i<res;i++) { ans.push(null); } this.setState({ dataSource:ans, count:data.total, }) }; handleChange= (page, pageSize) => { this.setState({ query: { pageNumber: page, pageSize: pageSize } }, () => { getBooksByPage(page.current,this.handleBooks); console.log("handlechange called"); }) }; componentDidMount() { getBooksByPage(1,this.handleBooks); } render() { return ( <div> <Table bordered dataSource={this.state.dataSource} columns={this.columns} pagination={{pageSize:5}} style={{marginLeft:75}} onChange={this.handleChange} total={this.state.count} /> </div> ); } } export default BooksTable;<file_sep>import React from 'react'; import "../../css/BookPage.css"; import {ShoppingCartOutlined} from '@ant-design/icons'; import {Button, InputNumber} from "antd"; import {getBookById} from "../../service/BookService"; export class ButtonGroup extends React.Component { // constructor(props) { // super(props); // this.state={ // detail:null, // } // } // // handleDetail = data => { // this.setState({ // detail: data, // }); // } // // componentDidMount() { // getBookById(this.props.bookId,this.handleDetail); // } // render() { // return ( // <div className={"button-groups"}> // <div style={{marginLeft: 80}}> // <span> 数量:</span> // <InputNumber min={1} max={100} defaultValue={1} // onChange={this.onChange_input} // className={"input-button"}/> // </div> // <Button type="primary" danger icon={<ShoppingCartOutlined/>} // size={"large"} className={"cart-button"}> // 加入购物车 // </Button> // <Button danger size={"large"} className={"buy-button"}> // 立即购买 // </Button> // </div> // ); // } } export default ButtonGroup;<file_sep>import React from 'react'; import {Menu, Layout, Icon, Breadcrumb, Divider, Space} from 'antd'; import '../../css/AdminPage.css'; import { PieChartOutlined, FileOutlined, UserOutlined, ReadOutlined, DashboardOutlined, AccountBookOutlined, } from '@ant-design/icons'; const { Header, Content, Footer, Sider } = Layout; const { SubMenu } = Menu; class SideBar extends React.Component { constructor(props) { super(props); this.state={ collapsed:false, selected:props.selected, } console.log("sidebar:"+props.selected); } onCollapse = collapsed => { console.log(collapsed); this.setState({ collapsed }); }; render() { return ( <Sider theme="light" className="siderAdmin-container" style={{display:"inline-block"}}> <div className="logoAdmin-container"> <Space style={{height:50}} align="center"> <Divider type="vertical" /> <span style={{paddingLeft:30}}> 后台管理系统 </span> </Space> </div> <Menu theme="light" defaultSelectedKeys={[this.state.selected]} mode="inline"> <Menu.Item key="1" icon={<UserOutlined/>} style={{ height: 50, paddingTop: 8, marginTop: 0, marginBottom: 0 }}> <a href="/admin/1"> 用户管理 </a> </Menu.Item> <Menu.Item key="2" icon={<ReadOutlined/>} style={{ height: 50, paddingTop: 8, marginTop: 0, marginBottom: 0 }}> <a href="/admin/2"> 书籍管理 </a> </Menu.Item> <Menu.Item key="4" icon={<FileOutlined/>} style={{ height: 50, paddingTop: 8, marginTop: 0, marginBottom: 0 }}> <a href="/admin/4"> 订单管理 </a> </Menu.Item> <Menu.Item key="5" icon={<DashboardOutlined />} style={{ height: 50, paddingTop: 8, marginTop: 0, marginBottom: 0 }}> <a href="/admin/5"> 销量统计 </a> </Menu.Item> <Menu.Item key="6" icon={<AccountBookOutlined />} style={{ height: 50, paddingTop: 8, marginTop: 0, marginBottom: 0 }}> <a href="/admin/6"> 用户消费统计 </a> </Menu.Item> </Menu> </Sider> ); } } export default SideBar; <file_sep>package com.bookstore.daoimpl; import com.bookstore.dao.BookDao; import com.bookstore.entity.Book; import com.bookstore.repository.BookRepository; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class BookDaoImpl implements BookDao { BookRepository bookRepository; @Autowired void setBookRepository(BookRepository bookRepository) { this.bookRepository = bookRepository; } @Override public List<Book> getBooks() { System.out.println("getBooks dao executed."); List<Book> bookList = bookRepository.getBooks(); return bookList; } @Override public Book getBookByBookId(Integer bookId) { System.out.println("getBookByBookId dao executed."); return bookRepository.getBookByBookId(bookId); } @Override public void deleteBookByBookId(Integer bookId) { bookRepository.deleteBookByBookId(bookId); } @Override public void addBook(Map<String, String> params) { String name = params.get("name"); String author = params.get("author"); String isbn = params.get("isbn"); String description = params.get("description"); String image = params.get("image"); String type = params.get("type"); String brief = params.get("brief"); if (name == null || author == null || isbn == null || description == null || image == null || type == null || brief == null) { return; } if (params.get("price") == null) { return; } BigDecimal price = new BigDecimal(params.get("price")); price = price.setScale(2, BigDecimal.ROUND_HALF_UP); //保留两位,四舍五入 if (params.get("inventory") == null) { return; } Integer inventory = new Integer(params.get("inventory")); bookRepository.addBook(name, author, price, isbn, inventory, description, image, type, brief); } @Override public List<Book> getBookByName(String name) { return bookRepository.getBookByName("%"+name+"%"); } @Override public void updateBook(Map<String,String> params) { Integer bookId= Integer.valueOf(params.get("bookId")); if(bookId==null || bookId<=0) return; String name = params.get("name"); if(name!=null) bookRepository.modifyName(bookId,name); String author = params.get("author"); if(author!=null) bookRepository.modifyAuthor(bookId,author); String isbn = params.get("isbn"); if(isbn!=null) bookRepository.modifyISBN(bookId,isbn); String description = params.get("description"); if(description!=null) bookRepository.modifyDescription(bookId,description); String image = params.get("image"); if(image!=null) bookRepository.modifyImage(bookId,image); String type = params.get("type"); if(type!=null) bookRepository.modifyType(bookId,type); String brief = params.get("brief"); if(brief!=null) bookRepository.modifyBrief(bookId,brief); BigDecimal price = new BigDecimal(params.get("price")); price = price.setScale(2, BigDecimal.ROUND_HALF_UP); //保留两位,四舍五入 if(price.compareTo(BigDecimal.ZERO)>0) bookRepository.modifyPrice(bookId,price); Integer inventory = new Integer(params.get("inventory")); if(inventory>0) bookRepository.modifyInventory(bookId,inventory); } @Override public PageInfo<Book> getBooksByPage(Integer num) { List<Book> books=bookRepository.getBooks(); PageInfo<Book> pageInfo = PageHelper .startPage(num, 5) .doSelectPageInfo(() -> bookRepository.getBooks()); List<Book> result=new ArrayList<>(); int st=Math.max((num-1)*5,0); int en=Math.min(books.size()-1,num*5-1); for(int i=st;i<=en;i++) { result.add(books.get(i)); } pageInfo.setList(result); pageInfo.setTotal(books.size()); return pageInfo; } } <file_sep>package com.bookstore.repository; import com.bookstore.entity.User; import java.math.BigDecimal; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional public interface UserRepository extends JpaRepository<User, String> { @Query(value = "from User where userId = :userId") User getUserById(@Param("userId") Integer userId); @Query(value="from User where name= :name") User getUserByName(@Param("name") String name); @Modifying @Query(value="insert into `user`(name,email) values(?1,?2)",nativeQuery = true) void addUser(String name, String email); @Query(value="select * from `user` where user_id in (select user_id from `user_auth` where user_type=0)",nativeQuery = true) List<User> getAllUsers(); @Modifying @Query(value="update `user` set enabled=?2 where `user_id`=?1",nativeQuery = true) void updateUserStatus(Integer userId,Boolean enabled); } <file_sep>import React from 'react'; import {Card, Col, Row} from 'antd'; import {getBooks} from "../../service/BookService"; const {Meta} = Card; class Book extends React.Component { constructor(props) { super(props); this.state={ books:[], browser:false, pageIndex:1, // need to complete page index } } handleBooks = data => { this.setState({ books: data, }) } componentDidMount() { getBooks(this.handleBooks); } renderBook = () => { let content = []; let now = 0; console.log("renderBook length:",this.state.books.length); for (let i = 0; i < (this.state.books.length); i++) { content.push( <Col span={6}> <Card bordered={false} cover={<img src={this.state.books[i].image}/>} onClick={e => { window.location.href="./detail?id="+this.state.books[i].bookId; }} > <Meta title={this.state.books[i].name} description={"¥" + this.state.books[i].price.toFixed(2)}/> </Card> </Col> ); } return content; }; render() { return ( <div className="book1-wrapper"> <Row gutter={16}> <this.renderBook/> </Row> </div> ); } } export default Book;<file_sep>import React, {useState} from 'react'; import {Form, Input, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete} from 'antd'; import {register,registerCheck} from "../../service/UserService"; import 'antd/dist/antd.css'; import '../../css/RegisterPage.css' import reqwest from 'reqwest'; const {Option} = Select; const formItemLayout = { labelCol: { xs: {span: 24}, sm: {span: 8}, }, wrapperCol: { xs: {span: 24}, sm: {span: 16}, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 16, offset: 8, }, }, }; const RegisterForm = () => { const [form] = Form.useForm(); const onFinishFailed = (errorInfo) => { console.log('Register Failed:', errorInfo); }; const handleSubmit =(values) => { console.log('Register Received values of form:',values); register(values); } let checkUser=false; // // const handleCheck=(value) => { // console.log("handle check called "+value); // checkUser=value; // } // // const checkAccount= async (rule,value,callback) => { // if(!value) { // return Promise.reject("请输入您的用户名。"); // } // let p=new Promise(function(resolve,reject) { // let timer=setTimeout(function() { // registerCheck(value,handleCheck); // resolve(); // },1000); // }); // p.then(function(){ // console.log("checkUser called="+checkUser); // if(checkUser==true) { // return Promise.reject("此用户名已被注册,请更换其他用户名。"); // } else { // return Promise.resolve(); // } // }) // // await registerCheck(value, handleCheck); // // console.log("checkUser called="+checkUser); // // if(checkUser==true) { // // return Promise.reject("此用户名已被注册,请更换其他用户名。"); // // } else { // // return Promise.resolve(); // // } // } const [autoCompleteResult, setAutoCompleteResult] = useState([]); return ( <Form {...formItemLayout} form={form} name="register" onFinish={handleSubmit} onFinishFailed={onFinishFailed} scrollToFirstError > <Form.Item name="username" label="用户名" rules={[ { required: true, whitespace: true, message: '请输入您的用户名。', }, // {validator: checkAccount} ({getFieldValue})=>({ validator(_,value,callback) { console.log("validator called"); if(!value) { callback(""); } reqwest({ url:`http://localhost:8080/registerCheck?username=${value}`, method:'get', type:'json', }).then(data=>{ console.log("get data:"+data); if(data==false) { console.log("yes called"); callback(); } else { console.log("reject called"); // return Promise.reject("此用户名已被注册,请更换其他用户名。"); callback("此用户名已被注册,请更换其他用户名。"); } }) console.log("validator end"); return false; } }), ]} hasFeedback > <Input/> </Form.Item> <Form.Item name="password" label="密码" rules={[ { required: true, message: '请输入您的密码。', }, ({getFieldValue}) => ({ validator(_, value) { if (value.length>=8 || !value) { return Promise.resolve(); } return Promise.reject(new Error('密码长度至少为8位。')); }, }), ]} hasFeedback > <Input.Password/> </Form.Item> <Form.Item name="confirm" label="确认密码" dependencies={['password']} hasFeedback rules={[ { required: true, message: '请确认您的密码。', }, ({getFieldValue}) => ({ validator(_, value) { if (!value || getFieldValue('password') === value) { return Promise.resolve(); } return Promise.reject(new Error('两次输入的密码不相等。')); }, }), ]} > <Input.Password/> </Form.Item> <Form.Item name="name" label="姓名" rules={[ { required: true, message: '请输入您的姓名。', whitespace: true, }, ]} hasFeedback > <Input/> </Form.Item> <Form.Item name="email" label="电子邮箱" rules={[ { type: 'email', message: '输入的邮箱地址不合法。', }, { required: true, message: '请输入您的邮箱地址。', }, ]} hasFeedback > <Input/> </Form.Item> <Form.Item name="agreement" valuePropName="checked" rules={[ { validator: (_, value) => value ? Promise.resolve() : Promise.reject( new Error('请阅读并同意用户协议。')), }, ]} {...tailFormItemLayout} > <Checkbox> 我已阅读并同意 <a href="">以下协议。</a> </Checkbox> </Form.Item> <Form.Item {...tailFormItemLayout}> <Button type="primary" htmlType="submit" block="true"> 完成注册 </Button> </Form.Item> </Form> ); }; export default RegisterForm; <file_sep>import React from 'react'; import {Table, Button} from "antd"; //import {getOrder} from "../../service/orderService"; import {getRealCartItems} from "../../service/CartService"; import "../../css/OrderPage.css"; const columns = [ { title: '商品信息', dataIndex: 'name', }, { title: '价格(元)', dataIndex: 'price', }, { title: '数量', dataIndex: 'number', }, { title: '小计', dataIndex: 'total' }, ]; class OrderTable extends React.Component { state = { selectedRowKeys: [], loading: false, item:[], }; start = () => { this.setState({loading: true}); // ajax request after empty completing setTimeout(() => { this.setState({ selectedRowKeys: [], loading: false, }); }, 1000); }; // onSelectChange = selectedRowKeys => { console.log('selectedRowKeys changed: ', selectedRowKeys); this.setState({ selectedRowKeys }); }; handleCartItems = data => { console.log("handleCartItems:"); console.log(data); let tmp=[]; for(let i in data) { tmp.push( { id: i, // must add id in order to apply rowSelection name: data[i].book.name, price: data[i].book.price.toFixed(2), number: data[i].amount, total: (data[i].book.price*data[i].amount).toFixed(2), bookId: data[i].bookId, } ); } this.setState({ item:tmp, }) } componentDidMount() { getRealCartItems(this.handleCartItems); } render() { const {loading, selectedRowKeys} = this.state; const rowSelection = { selectedRowKeys, onChange: this.onSelectChange, }; selectedRowKeys.length = 1; const hasSelected = selectedRowKeys.length > 0; return ( <div className="ordertable-container"> <Table columns={columns} dataSource={this.state.item}/> </div> ); } } export default OrderTable;<file_sep>import postRequest from "../utils/ajax"; export function getOrder(callback) { const url=`http://localhost:8080/getOrder`; postRequest(url,{},callback); } export function getAllOrder(callback) { const url=`http://localhost:8080/getAllOrder`; postRequest(url,{},callback); } export function getOrderItemById(orderId,callback) { const url=`http://localhost:8080/getOrderItemById?orderId=${orderId}`; postRequest(url,{},callback); } export function getOrderByTime(t1,t2,callback) { const url=`http://localhost:8080/getOrderByTime?t1=${t1}&t2=${t2}`; postRequest(url,{},callback); } export function getAllOrderByTime(t1,t2,callback) { const url=`http://localhost:8080/getAllOrderByTime?t1=${t1}&t2=${t2}`; postRequest(url,{},callback); }<file_sep>package com.bookstore.repository; import com.bookstore.entity.OrderItem; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.math.BigDecimal; import java.util.Date; @Transactional public interface OrderItemRepository extends JpaRepository<OrderItem, Integer> { @Modifying @Query(value="insert into order_item(order_id,book_id,amount,price) values(?1,?2,?3,?4)",nativeQuery = true) void addItem(Integer orderId,Integer bookId,Integer amount, BigDecimal price); @Query(value="select * from order_item where order_id=?1",nativeQuery = true) List<OrderItem> getOrderItemById(Integer orderId); } <file_sep>import postRequest from "../utils/ajax"; export function addCartItem(bookId,amount,active,callback) { const url=`http://localhost:8080/addCartItem?bookId=${Number(bookId)}&amount=${Number(amount)}&active=${Boolean(active)}`; postRequest(url,{},callback); } export function setCartItem(bookId,active,callback) { const url=`http://localhost:8080/setCartItem?bookId=${Number(bookId)}&active=${Boolean(active)}`; postRequest(url,{},callback); } export function deleteCartItem(bookId,callback) { const url=`http://localhost:8080/deleteCartItem?bookId=${Number(bookId)}`; postRequest(url,{},callback); } export function submitCart(callback) { const url=`http://localhost:8080/submitCart`; postRequest(url,{},callback); } export function getCartItems(callback) { const url=`http://localhost:8080/getCartItems`; postRequest(url,{},callback); } export function getRealCartItems(callback) { const url=`http://localhost:8080/getRealCartItems`; postRequest(url,{},callback); }<file_sep>import React from 'react'; import {Layout, Col, Card, Row} from 'antd'; import '../../css/AdminPage.css'; import '../../css/SearchPage.css' import {getBookByName} from "../../service/BookService"; import MyFooter from "../footer"; const {Header, Content, Footer, Sider} = Layout; const {Meta} = Card; class SearchResult extends React.Component { constructor(props) { console.log("name="+props.name); super(props); this.state = { books: null, number: 0, } } handleBooks = data => { console.log("get search data:"); console.log(data); this.setState({ books: data, }); } handleNumber=()=>{ if(!this.state.books) return null; console.log("set number:",this.state.books.length); this.setState({ number:this.state.books.length, }); } renderBook = () => { let content = []; if(!this.state.books) return null; console.log("renderBook length:", this.state.books.length); for (let i = 0; i < (this.state.books.length); i++) { content.push( <Col span={6}> <Card bordered={false} cover={<img src={this.state.books[i].image}/>} onClick={e => { window.location.href = "./detail?id=" + this.state.books[i].bookId; }} > <Meta title={this.state.books[i].name} description={"¥" + this.state.books[i].price}/> </Card> </Col> ); } return content; }; componentDidMount() { getBookByName(this.props.name, this.handleBooks); } render() { return ( <div className="search-container"> <div className="search-breadhead"> <a className="first"> 全部商品 </a> <a className="second">搜索"{this.props.name}"</a> </div> <div className="search-information"> <strong>"{this.props.name}"</strong> 找到以下相关商品 </div> <div className="book1-wrapper" style={{paddingTop:30}}> <Row gutter={16}> <this.renderBook/> </Row> </div> <div className="foot-container" style={{display: "block"}}> <MyFooter/> </div> </div> ); } } export default SearchResult; <file_sep>import React from 'react'; import logo from "../resources/logo.svg"; import SearchBar_HomePage from "./SearchPage/SearchBar"; import UserAvatar from "./UserAvatar"; import {Divider} from "antd" import "../css/HomePage.css" class HeadWrap_HomePage extends React.Component { render() { return ( <div className="headwrap-container"> <div className="logohead-container" style={{display: 'inline-block'}}> <a href="../home"> <img className="logohead-image" src={logo} alt="logo"/> </a> </div> <div style={{display: 'inline-block', left: 100}} className="searchbar_homepage-container"> <SearchBar_HomePage/> </div> <Divider type="vertical"/> <div style={{display: 'inline-block'}}> <UserAvatar/> </div> </div> ); } } export default HeadWrap_HomePage;<file_sep>import React from 'react'; import HeadWrap from "../components/HeadWrap"; import {Layout} from "antd"; import SideBar from "../components/SideBar"; import UserOrderTable from "../components/UserPage/UserOrderTable"; import "../css/UserOrderPage.css"; import MyFooter from "../components/footer"; class UserOrderView extends React.Component { constructor(props) { super(props); } render() { return ( <div className="user-page"> <div className="head-container"> <HeadWrap/> </div> <div className="user-container"> <Layout className="bookview-layout"> <SideBar selected={"4"}/> <div className="userorder-container"> <UserOrderTable isadmin={"0"}/> </div> </Layout> <MyFooter/> </div> </div> ); } } export default UserOrderView; <file_sep>import React from 'react'; import logo from "../../resources/logo.svg"; import UserAvatar from "../UserAvatar"; import {Divider, Steps} from "antd"; import { ShoppingCartOutlined, ShoppingOutlined, SmileOutlined } from '@ant-design/icons'; import "../../css/CartPage.css"; import "../../css/HomePage.css"; const {Step} = Steps; class HeadWrap_CartPage extends React.Component { render() { return ( <div className="headwrap-container"> <div className="logohead-container" style={{display: 'inline-block'}}> <a href="./home"> <img className="logohead-image" src={logo} alt="logo"/> </a> </div> <div style={{display: 'inline-block', left: 100}} className="stepbar-container"> <Steps> <Step status="process" title="我的购物车" icon={<ShoppingCartOutlined/>}/> <Step status="wait" title="填写订单" icon={<ShoppingOutlined/>}/> <Step status="wait" title="完成订单" icon={<SmileOutlined/>}/> </Steps> </div> <div style={{display: 'inline-block'}} className="cartavatar-container"> <UserAvatar/> </div> </div> ); } } export default HeadWrap_CartPage;<file_sep>package com.bookstore.serviceimpl; import com.bookstore.dao.CartDao; import com.bookstore.entity.CartItem; import com.bookstore.service.CartService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CartServiceImpl implements CartService{ CartDao cartDao; @Autowired void setCartDao(CartDao cartDao) {this.cartDao=cartDao;} @Override public List<CartItem> getCartItems() { return cartDao.getCartItems(); } @Override public List<CartItem> getRealCartItems() {return cartDao.getRealCartItems();} @Override public void addCartItem(Integer bookId, Integer amount, Boolean active) { cartDao.addCartItem(bookId,amount,active); } @Override public void setCartItem(Integer bookId,Boolean active) { cartDao.setCartItem(bookId,active); } @Override public void deleteCartItem(Integer bookId){ cartDao.deleteCartItem(bookId); } @Override public void submitCart() { cartDao.submitCart(); } } <file_sep>import React from 'react'; import MyFooter from "../components/footer"; import {Row, Col, Divider, Layout, InputNumber, Button} from 'antd'; import "../css/BookPage.css" import SearchResult from "../components/SearchPage/SearchResult"; import HeadWrap from "../components/HeadWrap"; import SideBar from "../components/SideBar"; const {Header, Content, Footer, Sider} = Layout; class SearchView extends React.Component { constructor(props) { super(props); let search=props.location.search; let params=new URLSearchParams(search); this.state={ name: params.get('name'), } console.log("get name:",this.state.name); } render() { return ( <div className="book-page"> <div className="book-container"> <div className="head-container"> <HeadWrap/> </div> <div className="detail-container"> <Layout className="bookview-layout"> <SideBar/> <SearchResult name={this.state.name}/> </Layout> </div> </div> </div> ) } }; export default (SearchView);<file_sep>import React, { useContext, useState, useEffect, useRef } from 'react'; import { Table, Input, Button, Popconfirm, Form, Space,Image,Typography,InputNumber} from 'antd'; import Highlighter from 'react-highlight-words'; import { SearchOutlined } from '@ant-design/icons'; import "../../css/AdminPage.css"; import {getBookById, getBooks,deleteBookById} from "../../service/BookService.js"; const EditableContext = React.createContext(null); const EditableRow = ({ index, ...props }) => { const [form] = Form.useForm(); return ( <Form form={form} component={false}> <EditableContext.Provider value={form}> <tr {...props} /> </EditableContext.Provider> </Form> ); }; const EditableCell = ({ editing, dataIndex, title, inputType, record, index, children, ...restProps }) => { const inputNode = inputType === 'number' ? <InputNumber /> : <Input />; return ( <td {...restProps}> {editing ? ( <Form.Item name={dataIndex} style={{ margin: 0, }} rules={[ { required: true, message: `Please Input ${title}!`, }, ]} > {inputNode} </Form.Item> ) : ( children )} </td> ); }; class BookTable_Admin extends React.Component { handleModifyDetail=(bookId)=>{ window.location.href = "../admin/7?bookId="+bookId; } getColumnSearchProps = dataIndex => ({ filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => ( <div style={{ padding: 8 }}> <Input ref={node => { this.searchInput = node; }} placeholder={`搜索书名`} value={selectedKeys[0]} onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])} onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)} style={{ width: 188, marginBottom: 8, display: 'block' }} /> <Space> <Button type="primary" onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)} icon={<SearchOutlined />} size="small" style={{ width: 90 }} > 搜索 </Button> <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}> 复位 </Button> </Space> </div> ), filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />, onFilter: (value, record) => record[dataIndex] ? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()) : '', onFilterDropdownVisibleChange: visible => { if (visible) { setTimeout(() => this.searchInput.select(), 100); } }, render: text => this.state.searchedColumn === dataIndex ? ( <Highlighter highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }} searchWords={[this.state.searchText]} autoEscape textToHighlight={text ? text.toString() : ''} /> ) : ( text ), }); constructor(props) { super(props); this.columns = [ { title:'图书编号', dataIndex:'bookId', width:'10%', editable:false, className:'column-book', }, { title: '书名', dataIndex: 'name', width: '15%', editable: true, className:'column-book', ...this.getColumnSearchProps('name'), }, { title: '作者', dataIndex: 'author', width:'15%', editable: true, className:'column-book', }, { title:'封面', dataIndex:'image', editable:true, width:'25%', className:'column-book', render:(record)=> { console.log("render image:"); console.log(record); return <Image className="image-small" src={record}/> }, }, { title: 'ISBN编号', dataIndex: 'isbn', editable: true, width:'5%', className:'column-book', }, { title: '库存量', dataIndex: 'inventory', editable: true, width:'10%', className:'column-book', }, { title: '操作', dataIndex: 'operation', className: 'column-book', width: '20%', render: (_, record) => this.state.dataSource.length >= 1 ? ( <div> <Popconfirm title="是否确定删除?" onConfirm={() => this.handleDelete(record.bookId)}> <a>删除</a> </Popconfirm> <a style={{marginLeft:10}} onClick={()=>this.handleModifyDetail(record.bookId)}>修改详情</a> </div> ) : null, }, ]; this.state = { dataSource: null, count: 0, searchText: '', searchedColumn: '', }; } handleAdd=()=>{ window.location.href="/admin/3"; }; handleDelete = (key) => { console.log("handle delete:"); console.log(key); const dataSource = [...this.state.dataSource]; this.setState({ dataSource: dataSource.filter((item) => item.bookId !== key), }); deleteBookById(key); }; handleSave = (row) => { const newData = [...this.state.dataSource]; const index = newData.findIndex((item) => row.key === item.key); const item = newData[index]; newData.splice(index, 1, { ...item, ...row }); this.setState({ dataSource: newData, }); }; handleBooks =(data) => { console.log("handle books:"); console.log(data); this.setState({ dataSource:data, count:data.length, }) }; handleSearch = (selectedKeys, confirm, dataIndex) => { confirm(); this.setState({ searchText: selectedKeys[0], searchedColumn: dataIndex, }); }; handleReset = clearFilters => { clearFilters(); this.setState({ searchText: '' }); }; componentDidMount() { getBooks(this.handleBooks); } render() { const { dataSource } = this.state; const components = { body: { row: EditableRow, cell: EditableCell, }, }; const columns = this.columns.map((col) => { if (!col.editable) { return col; } return { ...col, onCell: (record) => ({ record, editable: col.editable, dataIndex: col.dataIndex, title: col.title, handleSave: this.handleSave, }), }; }); return ( <div> <Button onClick={this.handleAdd} type="primary" size={"large"} style={{ marginBottom: 16, }} > 添加图书 </Button> <Table components={components} rowClassName={() => 'editable-row'} bordered dataSource={dataSource} columns={columns} pagination={{pageSize:5}} /> </div> ); } } export default BookTable_Admin;<file_sep>import React from 'react'; import LoginForm from '../components/LoginPage/LoginForm.js' import {withRouter} from 'react-router-dom'; import logo from '../resources/logo.svg' import {Layout} from 'antd'; import MyFooter from "../components/footer.js"; import "../css/LoginPage.css"; const {Header, Content, Footer} = Layout; class LoginView extends React.Component { render() { return ( <div className="login-page"> <div className="login-container"> <div className="logo-container"> <img className="logo-image" src={logo} alt="logo"/> <span class="title-text">用户登录</span> </div> <Content className="content-container"> <div className="LoginBox-wrap"> <div className="LoginForm-container"> <LoginForm/> <a className="register-click" href="/register">立即注册</a> </div> </div> </Content> <Footer> <MyFooter/> </Footer> </div> </div> ) } } export default withRouter(LoginView);<file_sep>import React, { useContext, useState, useEffect, useRef } from 'react'; import { Input, Button, Form, } from 'antd'; import "../../css/AdminPage.css"; import {addBook} from "../../service/BookService"; const EditableContext = React.createContext(null); const { TextArea } = Input; const formItemLayout = { labelCol: { xs: {span: 24}, sm: {span: 8}, }, wrapperCol: { xs: {span: 24}, sm: {span: 16}, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 16, offset: 8, }, }, }; const AddBook = () => { const [form] = Form.useForm(); const onFinishFailed = (errorInfo) => { console.log('AddBook Failed:', errorInfo); }; const handleSubmit =(values) => { console.log('AddBook Received values of form:',values); addBook(values); window.location.href = "../admin/2"; } return ( <div> <h3 style={{marginLeft:50}}>添加图书</h3> <div className="addbook-container"> <Form {...formItemLayout} form={form} name="addbook" onFinish={handleSubmit} onFinishFailed={onFinishFailed} scrollToFirstError className="addbook-form" > <Form.Item name="name" label="名称" hasFeedback rules={[ { required: true, message: '请输入图书名称。', whitespace: true, }, ]} > <Input/> </Form.Item> <Form.Item name="author" label="作者" hasFeedback rules={[ { required: true, message: '请输入图书作者。', }, ]} > <Input/> </Form.Item> <Form.Item name="price" label="价格" dependencies={['password']} hasFeedback rules={[ { required: true, pattern: new RegExp(/^(([1-9]\d*)|\d)(\.\d{1,2})?$/, 'g'), message: '请输入正确的图书价格(最多两位小数)。', }, ]} > <Input/> </Form.Item> <Form.Item name="isbn" label="ISBN" hasFeedback rules={[ { required: true, message: '请输入图书的ISBN号(13位数字)。', whitespace: true, pattern:new RegExp(/\d{13}$/,'g'), }, ]} > <Input/> </Form.Item> <Form.Item name="inventory" label="库存量" hasFeedback rules={[ { required: true, message: '请输入正确的库存量(正整数)。', whitespace: true, pattern:new RegExp(/^[1-9]\d*$/,'g'), }, ]} > <Input/> </Form.Item> <Form.Item name="description" label="详情" hasFeedback rules={[ { required: true, message: '请输入书籍详情。', whitespace: true, }, ]} > <TextArea/> </Form.Item> <Form.Item name="image" label="封面地址" hasFeedback rules={[ { required: true, message: '请输入正确的封面地址。', pattern:new RegExp( "^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&amp;%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&amp;%\$#\=~_\-]+))*$"), whitespace: true, }, ]} > <TextArea/> </Form.Item> <Form.Item name="type" label="类别" hasFeedback rules={[ { required: true, message: '请输入书籍类别。', whitespace: true, }, ]} > <Input/> </Form.Item> <Form.Item name="brief" label="简介" hasFeedback rules={[ { required: true, message: '请输入书籍简介。', whitespace: true, }, ]} > <TextArea/> </Form.Item> <Form.Item {...tailFormItemLayout}> <Button type="primary" htmlType="submit" block="true"> 添加图书 </Button> </Form.Item> </Form> </div> </div> ); }; export default AddBook;<file_sep>package com.bookstore.utils.messageUtils; import net.sf.json.JSONObject; public class MessageUtil { public static final String LOGIN_ERROR_MSG = "密码或用户名有误,请重新输入!"; public static final String LOGIN_BAN_MSG ="此用户已被禁用!"; public static final String LOGIN_SUCCESS_MSG = "登陆成功!"; public static final String ALREADY_LOGIN_MSG = "用户已经登陆。"; public static final String NOT_LOGIN_MSG = "用户未登陆!"; public static final String LOGOUT_SUCCESS_MSG = "退出登录成功!"; public static final String LOGOUT_ERROR_MSG = "退出登录失败!"; public static final String REGISTER_ERROR_MSG = "此用户名已注册,请更换其他用户名!"; public static final String REGISTER_SUCCESS_MSG = "注册成功!"; public static final String NOT_ALLOW_MSG="当前用户非管理员,不能访问此页面。"; public static final int LOGIN_ERROR_CODE = -1; public static final int LOGIN_SUCCESS_CODE = 1; public static final int NOT_LOGIN_CODE = -2; public static final int ALREADY_LOGIN_CODE = 0; public static final int LOGOUT_SUCCESS_CODE = 2; public static final int LOGOUT_ERROR_CODE = -3; public static final int REGISTER_ERROR_CODE = -4; public static final int REGISTER_SUCCESS_CODE = 4; public static final int NOT_ALLOW_CODE=5; public static Message createMessage(int statusCode, String message) { return new Message(statusCode, message); } public static Message createMessage(int statusCode, String message, JSONObject data) { return new Message(statusCode, message, data); } } <file_sep>import React, {useContext, useState, useEffect, useRef} from 'react'; import {Table, Input, Button, Space, DatePicker} from 'antd'; import Highlighter from 'react-highlight-words'; import Icon, {SearchOutlined, DownOutlined} from '@ant-design/icons'; import {getOrder,getAllOrder} from "../../service/OrderService"; import 'moment/locale/zh-cn'; import locale from 'antd/es/date-picker/locale/zh_CN'; import "../../css/AdminPage.css"; import moment from 'moment'; const {RangePicker} = DatePicker; const { Search } = Input; class UserOrderTable extends React.Component { renderTime= date => { //转换unix时间戳至指定格式 let dateee = new Date(date).toJSON(); return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '') } constructor(props) { super(props); this.columns = [ { title: '订单编号', dataIndex: 'orderId', width: '20%', align: "center", }, { title: '创建时间', dataIndex: 'time', align: "center", width:'40%', // ...this.getColumnSearchProps('time'), }, { title: '金额', dataIndex: 'price', width: '40%', align: "center", render: (record) => { return "¥" + record.toFixed(2); } }, ]; if(this.props.isadmin=="1") { this.columns.splice(1,0,{ title: '用户名', dataIndex: 'username', width: '20%', align: "center", }) } this.state = { order: null, order_1:null, // searchText: '', // searchedColumn: '', // sortedInfo:null, start_t:'', end_t:'', }; } handleOrder = data => { //处理读来的数据,方便表格对应dataIndex if(data.data!=undefined && data.data==null) return; this.setState({ order: data, }) let len = this.state.order.length; let tmp=this.state.order; for (let i = 0; i < len; i++) { tmp[i].username=tmp[i].user.name; tmp[i].time = this.renderTime(tmp[i].time); let len1 = this.state.order[i].orderItem.length; for (let j = 0; j < len1; j++) { tmp[i].orderItem[j].name = tmp[i].orderItem[j].book.name; tmp[i].orderItem[j].price = tmp[i].orderItem[j].book.price; } } this.setState({ order: tmp, order_1:tmp, }) } componentDidMount() { if(this.props.isadmin=="1") { getAllOrder(this.handleOrder); } else { getOrder(this.handleOrder); } console.log("getOrder:" + this.state.order); } handleSearchName= data=> { console.log(data); if(data==null || data=='' || data==undefined) { return; } let order_2=[]; let len=this.state.order_1.length; console.log("len="+len); for(let i=0;i<len;i++) { let len1=this.state.order_1[i].orderItem.length; let f=false; for(let j=0;j<len1;j++) { if(this.state.order_1[i].orderItem[j].name.includes(data)) { f=true; break; } } if(f) { // console.log(this.state.order_1[i]); order_2.push(this.state.order_1[i]); } } this.setState({ order:order_2, }) } handleResetButton=() => { //处理复位 console.log("reset called"); this.setState({ order:this.state.order_1, }) console.log(this.state.order); } onChange=(data)=>{ if(data==null || data==undefined || data.length<2) { return; } console.log("onChange:",data); let start_t=data[0].format('YYYY-MM-DD HH:mm:ss') let end_t=data[1].format('YYYY-MM-DD HH:mm:ss'); console.log(start_t); console.log(end_t); this.setState({ start_t:start_t, end_t:end_t, }) } onSearchByTime=()=>{ if(this.state.start_t=='' || this.state.end_t=='') { return; } let order_2=[]; let len=this.state.order_1.length; console.log("len="+len); for(let i=0;i<len;i++) { if(this.state.order_1[i].time>=this.state.start_t && this.state.order_1[i].time<=this.state.end_t) { order_2.push(this.state.order_1[i]); } } this.setState({ order:order_2, start_t:'', end_t:'', }) } render() { console.log("want to see"); console.log(this.state.order); const columns = this.columns.map((col) => { if (!col.editable) { return col; } return { ...col, onCell: (record) => ({ record, dataIndex: col.dataIndex, title: col.title, }), }; }); const expandedRowRender = (record) => { const columns = [ { title: '图书编号', dataIndex: 'bookId', key: 'bookId', align: "center", width: '25%', }, { title: '书名', dataIndex: 'name', key: 'name', align: "center", width: '25%', }, { title: '价格', dataIndex: 'price', key: 'price', align: "center", width: '25%', render: (record) => { return "¥" + record.toFixed(2); }, }, { title: '数量', dataIndex: 'amount', key: 'amount', align: "center", width: '25%', }, ]; return <Table columns={columns} dataSource={record.orderItem} pagination={false}/>; } return ( <div className="userorder-table"> <Space size="large" style={{marginBottom:10}}> <div>书籍名称</div> <Search placeholder="根据书籍名称筛选订单" enterButton="搜索" style={{ size:'small'}} style={{width:438}} onSearch={this.handleSearchName} /> </Space> <Space size="large" style={{marginBottom:10,marginTop:20}}> <div>成交时间</div> <RangePicker ranges={{ '今天': [moment().startOf('day'), moment().endOf('day')], '本月': [moment().startOf('month'), moment().endOf('month')], }} showTime format="YYYY-MM-DD HH:mm:ss" style={{ size:'small'}} locale={locale} onChange={this.onChange} /> <Button type="primary" // onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)} icon={<SearchOutlined/>} style={{width: 90}} onClick={this.onSearchByTime} > 搜索 </Button> <Button onClick={this.handleResetButton} style={{width: 90}} > 复位 </Button> </Space> <Table bordered dataSource={this.state.order} expandedRowRender={record => expandedRowRender(record)} columns={columns} rowKey="orderId" //防止全部展开 style={{marginTop:20}} /> </div> ); } } export default UserOrderTable; // getColumnSearchProps = dataIndex => ({ // filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => ( // <div style={{ padding: 8 }}> // <RangePicker // value={selectedKeys[0]} // onChange={dateString => setSelectedKeys(dateString ? [dateString] : [])} // onPressEnter={() => this.handleSearch(selectedKeys, confirm)} // showTime // format="YYYY/MM/DD HH:mm:ss" // style={{ size:'small',marginBottom: 8 }} // locale={locale} // /> // <Space> // <Button // type="primary" // onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)} // icon={<SearchOutlined />} // size="small" // style={{ width: 90 }} // > // 搜索 // </Button> // <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}> // 复位 // </Button> // </Space> // </div> // ), // filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />, // onFilter: (value, record) => // record[dataIndex] // ? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()) // : '', // // onFilterDropdownVisibleChange: visible => { // // if (visible) { // // setTimeout(() => this.searchInput.select(), 100); // // } // // }, // render: text => // this.state.searchedColumn === dataIndex ? ( // <Highlighter // highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }} // searchWords={[this.state.searchText]} // autoEscape // textToHighlight={text ? text.toString() : ''} // /> // ) : ( // text // ), // }); //<file_sep>package com.bookstore.service; import com.bookstore.entity.Book; import com.github.pagehelper.PageInfo; import java.util.List; import java.util.Map; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; public interface BookService { List<Book> getBooks(); PageInfo<Book> getBooksByPage(Integer num); Book getBookByBookId(Integer bookId); void deleteBookByBookId(Integer bookId); void addBook(Map<String, String> params); List<Book> getBookByName(String name); void updateBook(Map<String,String> params); } <file_sep>import React from 'react'; import {Menu, Layout, Divider, Space, Table, Switch} from 'antd'; import '../../css/AdminPage.css'; import {getAllUsers, updateUserStatus} from "../../service/UserService"; const {Header, Content, Footer, Sider} = Layout; class UserTable_Admin extends React.Component { constructor(props) { super(props); this.state = { users: null, } } handleUsers = data => { this.setState({ users: data, }); } handleChange = (checked,userId) => { console.log("UserTable handleChange:"+checked+" "+userId); updateUserStatus(userId,checked); // this.handleUsers(); } handleChange1 = (checked) => { console.log("switch to "+checked); // this.handleUsers(); } componentDidMount() { getAllUsers(this.handleUsers); } render() { const columns = [ { title: '用户ID', dataIndex: 'userId', key: 'userId', }, { title: '姓名', dataIndex: 'name', key: 'name', }, { title: '电子邮箱', dataIndex: 'email', key: 'email', }, { title: '操作', dataIndex: 'enabled', key: 'enabled', render: (text, record) => ( <Space size="middle"> <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked={record.enabled} onChange={(checked)=>this.handleChange(checked,record.userId)} /> </Space> ), }, ]; return ( <Table columns={columns} dataSource={this.state.users}/> ); } } export default UserTable_Admin; <file_sep>package com.bookstore.controller; import com.bookstore.entity.User; import com.bookstore.entity.UserAuth; import com.bookstore.service.UserService; import com.bookstore.utils.messageUtils.Message; import com.bookstore.utils.messageUtils.MessageUtil; import com.bookstore.utils.sessionUtils.SessionUtil; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController public class LoginController { final UserService userService; @Autowired LoginController(UserService userService) { this.userService = userService; } // 【标在构造器上】:如果组件只有一个有参构造器,这个有参构造器的@Autowired可以省略,参数位置的组件还是可以自动从容器中获取;构造器要用的组件,都是从容器中获取 @RequestMapping("/login") public Message login(@RequestBody Map<String, String> params) { String username = params.get("username"); String userPassword = params.get("<PASSWORD>Password"); UserAuth userAuth = userService.checkAuth(username, userPassword); System.out.println("login Auth:"+ userAuth); if (userAuth != null) { User nowUser=userService.getUserById(userAuth.getUserId()); if(nowUser.getEnabled()==false) { return MessageUtil.createMessage(MessageUtil.LOGIN_ERROR_CODE, MessageUtil.LOGIN_BAN_MSG); } JSONObject newSession = new JSONObject(); newSession.put("userId", userAuth.getUserId()); newSession.put("username", userAuth.getUsername()); newSession.put("userType", userAuth.getUserType()); SessionUtil.setSession(newSession); JSONObject responseData = JSONObject.fromObject(userAuth); responseData.remove("userPassword"); return MessageUtil.createMessage(MessageUtil.LOGIN_SUCCESS_CODE, MessageUtil.LOGIN_SUCCESS_MSG, responseData); } else { return MessageUtil.createMessage(MessageUtil.LOGIN_ERROR_CODE, MessageUtil.LOGIN_ERROR_MSG); } } @RequestMapping("/logout") public Message logout() { boolean status = SessionUtil.removeSession(); System.out.println("logout:"+status); if (!status) { return MessageUtil.createMessage(MessageUtil.LOGOUT_ERROR_CODE, MessageUtil.LOGOUT_ERROR_MSG); } else return MessageUtil.createMessage(MessageUtil.LOGOUT_SUCCESS_CODE, MessageUtil.LOGOUT_SUCCESS_MSG); } } <file_sep>import React from 'react'; import MyFooter from "../components/footer"; import {Row, Col, Divider, Layout, InputNumber, Button} from 'antd'; import "@babel/plugin-proposal-class-properties"; import "../css/BookPage.css" import BookDetail from "../components/BookPage/BookDetail"; import HeadWrap from "../components/HeadWrap"; import SideBar from "../components/SideBar"; const {Header, Content, Footer, Sider} = Layout; class BookView extends React.Component { constructor(props) { super(props); let search=props.location.search; let params=new URLSearchParams(search); this.state={ bookId: params.get('id'), } console.log("getid:",this.state.bookId); } onChange_input = () => { console.log('book detail view changed', this); } render() { return ( <div className="book-page"> <div className="book-container"> <div className="head-container"> <HeadWrap/> </div> <div className="detail-container"> <Layout className="bookview-layout"> <SideBar/> <div> <BookDetail bookId={this.state.bookId} style={{height: 500}}/> <div className="foot-container" style={{display: "block"}}> <MyFooter/> </div> </div> </Layout> </div> </div> </div> ) } }; export default (BookView);<file_sep>package com.bookstore.serviceimpl; import com.bookstore.dao.OrderItemDao; import com.bookstore.service.OrderItemService; import com.bookstore.entity.OrderItem; import java.sql.Timestamp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class OrderItemServiceImpl implements OrderItemService { OrderItemDao orderItemDao; @Autowired void setOrderItemDao(OrderItemDao orderItemDao) { this.orderItemDao = orderItemDao; } @Override public List<OrderItem> getOrderItemById(Integer orderId) { return orderItemDao.getOrderItemById(orderId); } } <file_sep>package com.bookstore.repository; import com.bookstore.entity.Book; import com.bookstore.entity.CartItem; import com.bookstore.dao.CartDao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import javax.transaction.Transactional; import java.sql.Timestamp; import java.util.List; import java.util.Map; @Transactional public interface CartRepository extends JpaRepository<CartItem, Integer>{ @Query(value="select * from `cart_item` where `user_id`=?1",nativeQuery=true) List<CartItem> getItems(Integer id); @Query(value="select * from cart_item where user_id=?1 and active=1", nativeQuery=true) List<CartItem> getRealCartItems(Integer id); @Query(value="from CartItem where userId = :userId and bookId = :bookId") CartItem getCartItemById(@Param("userId")Integer userId, @Param("bookId") Integer bookId); @Modifying @Query(value="replace into `cart_item` (user_id,book_id,amount,active) values(?1,?2,?3,?4)",nativeQuery = true) void addCartItem(Integer userId, Integer bookId, Integer amount, Boolean active); @Modifying @Query(value="delete from `cart_item` where `user_id`=?1 and `book_id`=?2",nativeQuery = true) void deleteCartItem(Integer userId, Integer bookId); @Modifying @Query(value="delete from `cart_item` where `user_id`=?1", nativeQuery = true) void submitCart(Integer userId); @Modifying @Query(value="update `cart_item` set `active`=?3 where `user_id`=?1 and `book_id`=?2",nativeQuery = true) void setCartItem(Integer userId,Integer bookId,Boolean active); } <file_sep>package com.bookstore.service; import com.bookstore.entity.CartItem; import java.util.List; import java.util.Map; public interface CartService { List<CartItem> getCartItems(); List<CartItem> getRealCartItems(); void addCartItem(Integer bookId, Integer amount, Boolean active); void setCartItem(Integer bookId,Boolean active); void deleteCartItem(Integer bookId); void submitCart(); } <file_sep>package com.bookstore.repository; import com.bookstore.entity.UserAuth; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; @Transactional public interface UserAuthRepository extends JpaRepository<UserAuth, String> { @Query(value = "from UserAuth where username = :username and userPassword = :user<PASSWORD>") UserAuth checkAuth(@Param("username") String userAccount, @Param("userPassword") String userPassword); @Modifying @Query(value="insert into `user_auth`(user_id,username,user_password,user_type) values(?1,?2,?3,?4)",nativeQuery = true) void addUserAuth(Integer userId, String username, String userPassword, Integer userType); @Query(value="from UserAuth where username= :username") UserAuth getUserAuthByUsername(@Param("username") String username); @Query(value="select count(*) from `user_auth` where `username`=?1",nativeQuery = true) Integer registerCheck(@Param("username") String username); }<file_sep>package com.bookstore.repository; import com.bookstore.entity.Book; import com.bookstore.entity.CartItem; import java.math.BigDecimal; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional public interface BookRepository extends JpaRepository<Book, Integer> { @Query(value="from Book where enabled=true") List<Book> getBooks(); @Query(value="from Book where bookId = :bookId") Book getBookByBookId(@Param("bookId")Integer id); @Modifying @Query(value="update `book` set `inventory`=?2 where `book_id`=?1",nativeQuery = true) void modifyInventory(Integer book_id, Integer amount); @Modifying @Query(value="update `book` set `enabled`=0 where `book_id`=?1",nativeQuery = true) void deleteBookByBookId(Integer book_id); @Modifying @Query(value="insert into `book`(name,author,price,isbn,inventory,description,image,type,brief,enabled) values(?1,?2,?3,?4,?5,?6,?7,?8,?9,1)",nativeQuery = true) void addBook(String name,String Author,BigDecimal Price,String ISBN,Integer Inventory,String Description,String Image,String Type,String Brief); @Query(value="select * from `book` where `name` like ?1 and `enabled`=true",nativeQuery = true) List<Book> getBookByName(String name); @Modifying @Query(value="update `book` set `name`=?2 where `book_id`=?1",nativeQuery = true) void modifyName(Integer book_id, String name); @Modifying @Query(value="update `book` set `author`=?2 where `book_id`=?1",nativeQuery = true) void modifyAuthor(Integer book_id, String author); @Modifying @Query(value="update `book` set `price`=?2 where `book_id`=?1",nativeQuery = true) void modifyPrice(Integer book_id, BigDecimal price); @Modifying @Query(value="update `book` set `isbn`=?2 where `book_id`=?1",nativeQuery = true) void modifyISBN(Integer book_id, String ISBN); @Modifying @Query(value="update `book` set `description`=?2 where `book_id`=?1",nativeQuery = true) void modifyDescription(Integer book_id, String description); @Modifying @Query(value="update `book` set `image`=?2 where `book_id`=?1",nativeQuery = true) void modifyImage(Integer book_id, String image); @Modifying @Query(value="update `book` set `type`=?2 where `book_id`=?1",nativeQuery = true) void modifyType(Integer book_id, String type); @Modifying @Query(value="update `book` set `brief`=?2 where `book_id`=?1",nativeQuery = true) void modifyBrief(Integer book_id, String brief); } <file_sep>DROP SCHEMA IF EXISTS bookstore_project; CREATE SCHEMA bookstore_project; use bookstore_project; SET foreign_key_checks = 0; /* Table structure for book */ DROP TABLE IF EXISTS `book`; CREATE TABLE `book` ( `book_id` int auto_increment, `name` varchar(63) NOT NULL, `author` varchar(255) NOT NULL, `price` decimal(10,2) NOT NULL, `isbn` varchar(31) NOT NULL, `inventory` int NOT NULL, `description` varchar(2000), `image` varchar(255) NOT NULL, `type` varchar(15), `brief` varchar(63), `enabled` boolean DEFAULT true, PRIMARY KEY (`book_id`) ) ENGINE = InnoDB CHARSET = utf8; /* Insert records of books */ INSERT INTO `book`(`name`,`author`,`price`,`isbn`,`inventory`,`description`,`image`,`type`,`brief`,`enabled`) VALUES ('新教伦理与资本主义精神','[德] 马克斯·韦伯','15.00','9787506393102','10','《新教伦理与资本主义精神》是马克斯·韦伯最著名的著作之一。在这部作品中,韦伯提出了一个知名的论点:新教教徒的思想影响了资本主义的发展。宗教教徒往往排斥世俗的事务,尤其是经济成就上的追求,但为什么新教教徒却是例外?韦伯在该书中论述宗教观念(新教伦理)与隐藏在资本主义发展背后的某种心理驱力(资本主义精神)之间的关系。','https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/book_1.4zmxniwd0nsw.jpg','哲学/宗教类','组织理论之父 现代社会学经典','1'), ('深入理解计算机系统','[美] 兰德尔·布莱恩特','90.40','9787111544937','22','本书是一本将计算机软件和硬件理论结合讲述的经典教程,内容覆盖计算机导论、体系结构和处理器设计等夺门课程。本书的最大优点是从程序员的角度描述计算机系统的实现细节,通过描述程序是如何映射到系统上,以及程序是如何执行的,使读者更好地理解程序的行为,以及程序效率。','https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/book_2.qxotjmzuqww.jpg','计算机/网络类','程序员必读经典著作!理解计算机系统书目,10万程序员共同选择。','1'), ('货币的非国家化','[英] 弗里德里希·冯·哈耶克','27.20','9787544385435','5','《货币的非国家化——对多元货币的理论与实践的分析》是哈耶克晚年最后一本经济学专著。他在书中颠覆了正统的货币制度观念:既然在一般商品、服务市场上自由竞争最有效率,那为什么不能在货币领域引入自由竞争?哈耶克提出了一个革命性建议:废除中央银行制度,允许私人发行货币,并自由竞争,这个竞争过程将会发现最好的货币。','https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/book_3.7kcgy17p6buo.jpg','经济类','只有真正对人、社会、经济与自由有深刻认知,才有如此洞见。','1'), ('恶意','[日] 东野圭吾','25.30','9787544285148','11','作为一部手记体杰作,《恶意》多年来在票选中始终名列前茅,同时被评论界和众多读者视为东野圭吾的巅峰之作,与《白夜行》同享光辉与荣耀:环环相扣的侦破进展百转千回,将手记体叙事的无限可能发挥得淋漓尽致;对复杂人性抽丝剥茧的深刻描画,令人眼花缭乱、哑口无言。','https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/book_4.7bn25h2vfb0g.jpg','小说类','读完《恶意》,才算真正认识东野圭吾!','1'), ('三体','刘慈欣','55.80','9787536692930','15','文化大革命如火如荼进行的同时。军方探寻外星文明的绝秘计划“红岸工程”取得了突破性进展。但在按下发射键的那一刻,历经劫难的叶文洁没有意识到,她彻底改变了人类的命运。地球文明向宇宙发出的第一声啼鸣,以太阳为中心,以光速向宇宙深处飞驰……四光年外,“三体文明”正苦苦挣扎——三颗无规则运行的太阳主导下的百余次毁灭与重生逼迫他们逃离母星。人类的末日悄然来临。','https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/book_5.cd9q5ewbalc.jpg','小说类','刘慈欣代表作,亚洲首部“雨果奖”获奖作品!','1'), ('道德情操论','[英] 亚当·斯密','29.10','9787100028264','17','《道德情操论》是斯密的伦理学著作,首次出版于1759年,斯密去世前共出版过六次。全书共有七卷构成,主要阐释的是道德情感的本质和道德评价的性质。斯密在该书中继承了哈奇森的道德感学说和休谟的同情论思想,形成了自己的道德情感理论。他反对神学家用天启 来说明道德的根源,而把他认为是人的本性中所有的同情的情感作为阐释道德的基础。','https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/book_6.4phqcg4ggikg.jpg','哲学/宗教类','世界思想史上的经典之作','1'), ('经济学原理','[美] 格里高利·曼昆','153.90','9787301312971','29','曼昆的《经济学原理》是国内外市场上广受欢迎的经济学经典教材之一。与同类书相比,本书的特点在于,更多地强调经济学原理的应用和思维方式的培养,而不是经济学模型。书中包含了大量贴近生活的案例研究和政策讨论,适合经济学专业本科生的宏观经济学课程以及对经济学感兴趣的普通读者使用。','https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/book_7.663zd41s21hc.jpg','教材类','哈佛大学曼昆教授扛鼎之作,广受欢迎的经济学入门读物,带你迈进经济学的殿堂!','1'), ('沉默的大多数','王小波','28.90','9787500627098','5','这本杂文随笔集包括思想文化方面的文章,涉及知识分子的处境及思考,社会道德伦理,文化论争,国学与新儒家,民族主义等问题;包括从日常生活中发掘出来的各种真知灼见,涉及科学与邪道,女权主义等;包括对社会科学研究的评论,涉及性问题,生育问题,同性恋问题,社会研究的伦理问题和方法问题等艺术的看法。','https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/book_8.151rhse3cosg.jpg','文学类','用沉默影响世界!','1'), ('笑傲江湖','金庸','76.80','9787108006639','20','名门正派的华山派大弟子令狐冲只因心性自由、不受羁勒,喜欢结交左道人士,被逐出师门,遭到正宗门派武林人士的唾弃而流落江湖。令狐冲依然率性而为,只因正义良知自在心中。后来他认识了魔教圣姑任盈盈,两个不喜权势、向往自由的年轻人几经生死患难,笑傲江湖,终成知心情侣。本书处处渗透着追求个性解放与人格独立的精神,对人性的刻画殊为深刻。','https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/bedd2327820c3b2eee3835822a665055.3d1u39vazvuo.jpeg','小说类','一曲《笑傲江湖》,传一段天荒地老。','1'), ('无人生还','[英] 阿加莎·克里斯蒂','35.00','9787513322331','23','十个相互陌生、身份各异的人受邀前往德文郡海岸边一座孤岛上的豪宅。客人到齐后,主人却没有出现。当晚,一个神秘的声音发出指控,分别说出每个人心中罪恶的秘密。接着,一位客人离奇死亡。暴风雨让小岛与世隔绝,《十个小士兵》——这首古老的童谣成了死亡咒语。如同歌谣中所预言的,客人一个接一个死去……杀人游戏结束后,竟无一人生还!','https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/book_10.3zkoq93b616o.jpg','小说类','无可争议的侦探小说女王','1'), ('金阁寺','[日] 三岛由纪夫','24.00','9787532744565','7','《金阁寺》取材于1950年金阁寺僧徒林养贤放火烧掉金阁寺的真实事件。据林养贤说他的犯罪动机是对金阁寺的美的嫉妒。《金阁寺》发表后大受好评,获第八届读卖文学奖。','http://img3m3.ddimg.cn/50/28/29220593-1_u_9.jpg','小说类','文学大师三岛由纪夫集大成之作,一个人走向毁灭的心理独白。','1'), ('万历十五年','[美] 黄仁宇','18.00','9787108009821','9','《万历十五年》是黄仁宇的成名之作,也是他的代表作之一。这本书融会了他数十年人生经历与治学体会,首次以“大历史观”分析明代社会之症结,观察现代中国之来路,给人启发良多。英文原本推出后,被美国多所大学采用为教科书,并两次获得美国书卷奖历史类好书的提名。','http://img3m3.ddimg.cn/4/23/25251043-1_u_195378.jpg','历史类','入选改革开放40年的40本好书。','1'); /* Table structure for carousel */ DROP TABLE IF EXISTS `home`; CREATE TABLE `home`( `image_id` int auto_increment, `image` varchar(255) NOT NULL, PRIMARY KEY (`image_id`) ) ENGINE = InnoDB CHARSET = utf8; /* Insert records of carousels */ INSERT INTO `home`(`image`) VALUES ('https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/carousel_4.1nilc4okk7z4.jpg'), ('https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/carousel_5.64boo7yrm6f4.jpg'), ('https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/carousel_6.2zqpk6gl2se8.png'), ('https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/carousel_7.30k8yzfndim8.jpg'), ('https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/1.5dlgo0nxnwg.jpg'), ('https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/2.4iml4zt78hds.jpg'), ('https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/3.7g29xt16e000.jpg'); /* Table structure for user */ DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `user_id` int auto_increment, `name` varchar(31) NOT NULL, `email` varchar(63) NOT NULL, `enabled` boolean DEFAULT true, PRIMARY KEY (`user_id`) ) ENGINE = InnoDB CHARSET = utf8; /* Insert records of user */ INSERT INTO `user`(`name`,`email`) VALUES ('<NAME>','<EMAIL>'); INSERT INTO `user`(`name`,`email`) VALUES ('Admin','<EMAIL>'); INSERT INTO `user`(`name`,`email`) VALUES ('Admin2','<EMAIL>'); INSERT INTO `user`(`name`,`email`) VALUES ('demo user','<EMAIL>'); /* Table structure for user_auth */ DROP TABLE IF EXISTS `user_auth`; CREATE TABLE `user_auth` ( `user_id` int NOT NULL, `username` varchar(31) NOT NULL, `user_password` varchar(31) NOT NULL, `user_type` int(11) NOT NULL, /* 0: user 1: admin */ PRIMARY KEY (`user_id`), FOREIGN KEY (`user_id`) REFERENCES `user`(`user_id`) ON DELETE CASCADE ) ENGINE=InnoDB CHARSET=utf8; /* Insert records of user_auth */ INSERT INTO `user_auth` VALUES ('1','xtommy','123','0'); INSERT INTO `user_auth` VALUES ('2','admin','admin','1'); INSERT INTO `user_auth` VALUES ('3','admin2','admin2','1'); INSERT INTO `user_auth` VALUES ('4','demo user','123','0'); /* Table structure for cart_item */ DROP TABLE IF EXISTS `cart_item`; CREATE TABLE `cart_item` ( `user_id` int NOT NULL, `book_id` int NOT NULL, `amount` int NOT NULL, `active` bool NOT NULL, -- PRIMARY KEY ('cart_id'), PRIMARY KEY (`user_id`,`book_id`), -- FOREIGN KEY (`cart_id`) REFERENCES `cart`(`cart_id`) ON DELETE CASCADE FOREIGN KEY (`user_id`) REFERENCES `user`(`user_id`) ON DELETE CASCADE, FOREIGN KEY (`book_id`) REFERENCES `book`(`book_id`) ON DELETE CASCADE ) ENGINE=InnoDB CHARSET=utf8; DROP TABLE IF EXISTS `order`; CREATE TABLE `order` ( `order_id` int auto_increment, `user_id` int NOT NULL, `time` timestamp NOT NULL, `price` decimal(10,2), primary key (`order_id`), foreign key (`user_id`) references `user`(`user_id`) ON DELETE CASCADE ) ENGINE=InnoDB CHARSET=utf8; DROP TABLE IF EXISTS `order_item`; CREATE TABLE `order_item` ( `order_id` int NOT NULL, `book_id` int NOT NULL, `amount` int NOT NULL, `price` decimal(10,2), primary key (`order_id`,`book_id`), foreign key (`order_id`) references `order`(`order_id`) ON DELETE CASCADE, foreign key (`book_id`) references `book`(`book_id`) ON DELETE RESTRICT ) ENGINE=InnoDB CHARSET=utf8; 巴黎圣母院 [法]雨果 36.00 9787020104215 100 人文类 《巴黎圣母院》艺术地再现了四百多年前法王路易十一统治时期的历史真实,宫廷与教会如何狼狈为奸压迫人民群众,人民群众怎样同两股势力英勇斗争。本书以1482年的法国为背景,以吉普赛姑娘爱丝美拉达与年轻英俊的卫队长,道貌岸然的副主教以及畸形、丑陋的敲钟人之间的关系为主线,热情呕歌了吉普赛姑娘与敲钟人高尚的品格,深刻鞭挞了卫队长与副主教的虚伪与卑下。 https://cdn.jsdelivr.net/gh/xtommy-1/Images@master/2daeea1d202dfd335f7e50c4956c11a9.3xrsrqiqkm4g.jpeg 名著名译丛书 <file_sep>import React from 'react'; import {Router, Route, Switch, Redirect} from 'react-router-dom'; import LoginView from "../view/LoginView"; import HomeView from "../view/HomeView"; import RegisterView from "../view/RegisterView"; import BookView from "../view/BookView"; import BooksView from "../view/BooksView"; import AdminView from "../view/AdminView"; import CartView from "../view/CartView"; import OrderView from "../view/OrderView"; import SuccessView from "../view/SuccessView"; import UserOrderView from "../view/UserOrderView"; import SearchView from "../view/SearchView"; import UserView from "../view/UserView"; import {history} from "../utils/history"; import PrivateRoute from "./PrivateRoute"; import LoginRoute from "./LoginRoute"; class BasicRoute extends React.Component { constructor(props) { super(props); history.listen((location, action) => { console.log(location, action); }); } render() { return ( <Router history={history}> <Switch> {/*<Route exact path="/" component={HomeView} />*/} <LoginRoute exact path={"/login"} component={LoginView}/> <Route exact path="/" component={HomeView}/> <Route exact path="/home" component={HomeView}/> <Route exact path="/register" component={RegisterView}/> <Route exact path="/detail" component={BookView}/> <Route exact path="/book_all" component={BooksView}/> <PrivateRoute exact path="/admin/:id" component={AdminView}/> <Route exact path="/search" component={SearchView}/> <Route exact path="/cart" component={CartView}/> <Route exact path="/order" component={OrderView}/> <Route exact path="/success" component={SuccessView}/> <Route exact path="/user_order" component={UserOrderView}/> <Route exact path="/user" component={UserView}/> <Redirect from={'/*'} to={{pathname: "/home"}}/> </Switch> </Router> ) } } export default BasicRoute; // 需要写private route<file_sep>import React from 'react'; import 'antd/dist/antd.css'; import '../css/bootstrap.min.css'; import "../css/LoginPage.css" class MyFooter extends React.Component { render() { return ( <nav class="navbar navbar-bottom navbar-default"> <div> <p class="navbar-text">Copyright © 2021-2021 Designed and built by <NAME>.</p> </div> </nav> ) } } export default MyFooter; <file_sep>import React from 'react'; import {Table, Input, Button, Space, DatePicker,Divider} from 'antd'; import {SearchOutlined} from '@ant-design/icons'; import {getOrder, getAllOrder, getAllOrderByTime, getOrderByTime} from "../../service/OrderService"; import 'moment/locale/zh-cn'; import locale from 'antd/es/date-picker/locale/zh_CN'; import "../../css/AdminPage.css"; import moment from 'moment'; import bigDecimal from "js-big-decimal"; import * as echarts from 'echarts'; const {RangePicker} = DatePicker; const { Search } = Input; class BookStats extends React.Component { renderTime= date => { //转换unix时间戳至指定格式 let dateee = new Date(date).toJSON(); return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '') } constructor(props) { super(props); this.columns = [ { title: '图书编号', dataIndex: 'bookId', width: '20%', align: "center", }, { title: '名称', dataIndex: 'name', align: "center", width:'40%', }, { title: '数量', dataIndex: 'amount', align: "center", width:'40%', }, ]; if(this.props.isadmin=="1") { this.state = { order:[], result:null, start_t:'0', end_t:'5000000000000', total_price:new bigDecimal(0.0), total_amount:0, myChart:null, text:"图书热销榜", }; } else { this.state = { order:[], result:null, start_t:'0', end_t:'5000000000000', total_price:new bigDecimal(0.0), total_amount:0, myChart:null, text:"消费统计", }; } } handleOrder = data => { //处理读来的数据,方便表格对应dataIndex let tmp=data; let len=tmp.length; let price=new bigDecimal(tmp[len-1].price); let amount=tmp[len-1].amount; this.setState({ order: tmp, total_price:price, total_amount:amount, // start_t:'0', // end_t:'5000000000', }); this.onSearchByTime(); } componentDidMount() { this.setState({ myChart:echarts.init(document.getElementById('echart-item')), }); if(this.props.isadmin=="1") { getAllOrderByTime(this.state.start_t,this.state.end_t,this.handleOrder); } else { getOrderByTime(this.state.start_t,this.state.end_t,this.handleOrder); } } handleResetButton=() => { //处理复位 console.log("reset called"); this.setState({ start_t:'0', end_t:'5000000000000', }) this.handle(); } onChange=(data)=>{ //修改起始时间 if(data==null || data==undefined || data.length<2) { return; } console.log("onChange:",data); let start_t=data[0].format('YYYY-MM-DD HH:mm:ss') let end_t=data[1].format('YYYY-MM-DD HH:mm:ss'); console.log("start_t:"); console.log(Date.parse(data[0]._d)); console.log("end_t:"); console.log(Date.parse(data[1]._d)); this.setState({ start_t:Date.parse(data[0]._d).toString(), end_t:Date.parse(data[1]._d).toString(), }) } onSearchByTime=()=>{ if(this.state.start_t=='' || this.state.end_t=='') { return; } let tmp=this.state.order; let len=tmp.length; let obj=[]; for(let i=0;i<len-1;i++) { obj.push({ bookId:tmp[i].bookId, amount:tmp[i].amount, name:tmp[i].name, }) } this.state.myChart.clear(); let result1=[]; let tmp_len=Math.min(obj.length,10); for(let i=0;i<tmp_len;++i) { result1.push({ value:obj[i].amount, name:obj[i].name, }) } console.log("result1:"); console.log(result1); // 绘制图表 this.state.myChart.setOption({ title: { text: this.state.text }, legend: { top: '5%', left: 'center' }, grid:{ x:'0%', y:'0%', bottom: '3%', containLabel: true }, series: [{ name: '销量', type: 'pie', radius:[20,140], center:['50%','50%'], // roseType:'area', itemStyle:{ borderRadius:5 }, data: result1 }] }); this.state.myChart.resize(); this.setState({ start_t:'', end_t:'', result:obj, total_price:new bigDecimal(tmp[len-1].price), total_amount:tmp[len-1].amount, }) } handle=()=>{ if(this.props.isadmin=="1") { getAllOrderByTime(this.state.start_t,this.state.end_t,this.handleOrder); } else { getOrderByTime(this.state.start_t,this.state.end_t,this.handleOrder); } } render() { console.log("want to see"); console.log(this.state.order); const columns = this.columns.map((col) => { if (!col.editable) { return col; } return { ...col, onCell: (record) => ({ record, dataIndex: col.dataIndex, title: col.title, }), }; }); return ( <div className="userorder-table"> <Space size="large" style={{marginBottom:10}}> <div>成交时间</div> <RangePicker ranges={{ '今天': [moment().startOf('day'), moment().endOf('day')], '本月': [moment().startOf('month'), moment().endOf('month')], }} showTime format="YYYY-MM-DD HH:mm:ss" style={{ size:'small'}} locale={locale} onChange={this.onChange} /> <Button type="primary" // onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)} icon={<SearchOutlined/>} style={{width: 90}} onClick={()=>this.handle()} > 搜索 </Button> <Button onClick={this.handleResetButton} style={{width: 90}} > 复位 </Button> </Space> <Table bordered dataSource={this.state.result} columns={columns} rowKey="orderId" //防止全部展开 style={{marginTop:20}} /> {/*<Divider/>*/} <div> <div style={{fontSize:20,float:"left"}}>购书总本数:</div> <div className="statsprice-container" style={{marginLeft:10,float:"left"}}> {this.state.total_amount} </div> <div style={{fontSize:20,marginLeft:10,marginTop:5}}>本</div> </div> <div style={{marginTop:20}}> <div style={{fontSize:20,marginTop:5,float:"left"}}>购书总金额:</div> <div className="statsprice-container" style={{marginLeft:10,float:"left"}}> ¥{this.state.total_price.round(2,bigDecimal.RoundingModes.HALF_EVEN).getValue()} </div> </div> <Divider style={{marginTop:20}}/> <div id="echart-item" style={{minHeight:500}}></div> </div> ); } } export default BookStats; <file_sep>import React from 'react'; import {Form, Input, Button, Checkbox} from 'antd'; import {login} from "../../service/UserService"; import 'antd/dist/antd.css'; import '../../css/LoginPage.css' const layout = { labelCol: { span: 8, }, wrapperCol: { span: 16, }, }; const tailLayout = { wrapperCol: { offset: 8, span: 16, }, }; class LoginForm extends React.Component { onFinishFailed = (errorInfo) => { console.log('Login Failed:', errorInfo); }; handleSubmit =(values) => { console.log('Login Received values of form:',values); login(values); } render() { return ( <Form {...layout} name="basic" initialValues={{remember: true}} onFinish={this.handleSubmit} // onFinishFailed={this.onFinishFailed} > <div className="LoginInput" align="center"> <Form.Item label="用户名" name="username" rules={[{required: true, message: '请输入用户名。'}]} > <Input/> </Form.Item> </div> <div className="LoginInput" align="center"> <Form.Item label="密码" name="userPassword" rules={[{required: true, message: '请输入密码。'}]} > <Input.Password/> </Form.Item> </div> <div className="LoginRemember" align="center"> <Form.Item {...tailLayout} name="remember" valuePropName="checked" > <Checkbox> 记住用户名和密码 </Checkbox> </Form.Item> </div> <div className="LoginSubmit" align="center"> <Form.Item {...tailLayout}> <Button type="primary" htmlType="submit" className="SubmitButton" style={{right: 43}}> 登录 </Button> </Form.Item> </div> </Form> ); }; }; export default LoginForm; <file_sep>package com.bookstore.service; import com.bookstore.entity.HomeItem; import java.util.List; public interface HomeService { List<HomeItem> getHomeContent(); } <file_sep>import React from 'react'; import MyFooter from "../components/footer"; import {Layout} from 'antd'; import {withRouter} from 'react-router-dom'; import "../css/HomePage.css"; import HeadWrap from "../components/HeadWrap"; import SideBar from "../components/SideBar"; import BooksTable from "../components/BooksPage/BooksTable"; class BooksView extends React.Component { constructor(props) { super(props); } render() { return ( <div className="book-page"> <div className="book-container"> <div className="head-container"> <HeadWrap/> </div> <div className="detail-container"> <Layout className="bookview-layout"> <SideBar selected={'2'}/> <div className="home-layout"> <div className="booktable-wrapper"> <div className="booktable-container" > <BooksTable/> </div> </div> <div className="foot-container" style={{display: "block"}}> <MyFooter/> </div> </div> </Layout> </div> </div> </div> ) } }; export default withRouter(BooksView);<file_sep>import postRequest from "../utils/ajax"; import {message} from "antd"; import {history} from "../utils/history"; import request from "request"; export function login(data) { const callback = data => { if (data.status > 0) { localStorage.setItem('user', JSON.stringify(data.data)); history.push("/"); history.go(0); message.success(data.message); } else { message.error(data.message); } }; const url = `http://localhost:8080/login`; postRequest(url, data, callback); } export function checkSession(callback) { const url = `http://localhost:8080/checkSession`; postRequest(url, {}, callback); } export function logout() { const url = `http://localhost:8080/logout`; const callback = data => { if (data.status > 0) { localStorage.removeItem('user'); history.push("/login"); message.success(data.message); } else { history.push("login"); message.error(data.message); } }; postRequest(url, {}, callback); } export function getUser(callback) { const url = `http://localhost:8080/getUser`; postRequest(url, {}, callback); } export function getAllUsers(callback) { const url=`http://localhost:8080/getAllUsers`; postRequest(url,{},callback); } export function getUserById(userId, callback) { const url = `http://localhost:8080/getUserById?userId=${Number(userId)}`; postRequest(url, {}, callback); } export function updateUserStatus(userId,enabled,callback) { const url=`http://localhost:8080/updateUserStatus?userId=${Number(userId)}&enabled=${Boolean(enabled)}`; postRequest(url,{},callback); } export function register(data) { const callback = data => { if (data.status > 0) { localStorage.setItem('user', JSON.stringify(data.data)); history.push("/login"); history.go(0); message.success(data.message); } else { message.error(data.message); } }; const url = `http://localhost:8080/register`; postRequest(url, data, callback); } export async function registerCheck(username, callback) { const url = `http://localhost:8080/registerCheck?username=${username}`; return new Promise(resolve => { postRequest(url, {}, callback)}); //return true; // return request(url); }<file_sep>package com.bookstore.serviceimpl; import com.bookstore.dao.BookDao; import com.bookstore.entity.Book; import com.bookstore.service.BookService; import com.github.pagehelper.PageInfo; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class BookServiceImpl implements BookService { BookDao bookDao; @Autowired void setBookDao(BookDao bookDao) { this.bookDao = bookDao; } @Override public List<Book> getBooks() { return bookDao.getBooks(); } @Override public Book getBookByBookId(Integer bookId) { return bookDao.getBookByBookId(bookId); } @Override public void deleteBookByBookId(Integer bookId) { bookDao.deleteBookByBookId(bookId); } @Override public void addBook(Map<String, String> params) { bookDao.addBook(params); } @Override public List<Book> getBookByName(String name) {return bookDao.getBookByName(name);} @Override public void updateBook(Map<String,String> params) {bookDao.updateBook(params);} @Override public PageInfo<Book> getBooksByPage(Integer num) {return bookDao.getBooksByPage(num);} } <file_sep>import React from 'react'; import {Route, Redirect} from 'react-router-dom' import {checkSession} from "../service/UserService"; import {Button, Modal} from 'antd'; export class PrivateRoute extends React.Component { constructor(props) { super(props); this.state = { isAuthorized: false, hasChecked: false, showModal: false, redirect: false, message: null, } } handleAccept = () => { this.setState({ showModal: false, redirect: true, }) }; checkAuthority = data => { console.log("PrivateRoute check:"); console.log(data); this.setState({ message:data.message, }) let isAuthorized = (data.status === 0); //非管理员,显示modal if (!isAuthorized) { this.setState({showModal: true}); } this.setState({ isAuthorized: isAuthorized, hasChecked: true, }) }; renderRedirect = () => { return this.state.redirect ? ( <Redirect to={{ pathname: '/home', state: {from: this.props.location} }}/> ) : null; }; renderModalButton = () => { return ( <Button key="submit" type="primary" onClick={this.handleAccept}> 确认 </Button> ) }; renderModal = () => { if (this.state.showModal) return ( <Modal title="提示" visible={true} footer={this.renderModalButton()}> <p>{this.state.message}</p> </Modal> ); else return null; }; componentDidMount() { checkSession(this.checkAuthority); } render() { const {component: Component, path = "/", exact = false, strict = false} = this.props; if (!this.state.hasChecked) return null; return <Route path={path} exact={exact} strict={strict} render={props => ( this.state.isAuthorized ? ( <Component {...props}/> ) : <div> {this.renderModal()} {this.renderRedirect()} </div> )}/> } } export default PrivateRoute;<file_sep>export default function postRequest(url, json, callback) { console.log(JSON.stringify(json)); let opts = { method: "POST", body: JSON.stringify(json), headers: { 'Content-Type': 'application/json' }, credentials: "include" //to upload cookies from client //credentials 是Request接口的只读属性,用于表示用户代理是否应该在跨域请求的情况下从其他域发送cookies。 }; fetch(url, opts) .then(response => response.json()) .then(data => { callback(data); }) .catch(error => { console.log(error); }) }<file_sep>package com.bookstore.dao; import com.bookstore.entity.OrderItem; import java.util.List; public interface OrderItemDao { List<OrderItem> getOrderItemById(Integer orderId); // List<MySales> getOrderItemById(Timestamp time1,Timestamp time2); }
66975d76e679139852465444eb7f6b9c554a166e
[ "JavaScript", "Java", "SQL" ]
55
JavaScript
xtommy-1/bookstore
88190850ca00aed5cef797b7f65d21b68f2dd8be
345997b6e5aed3473f4e11a8078a10e4b60fd3ad
refs/heads/master
<repo_name>georgia-mackey/WFD<file_sep>/WFD/Class1.cs using System; namespace WFD { public class Class1 { } }
e0d990ee4440967eb424d49f220bd0b863979089
[ "C#" ]
1
C#
georgia-mackey/WFD
5ec811523a6ced21dc809b0b572a1ef2bb8ff626
808b001fb1a55785f1dc58edb6b6c6fe7d5a544e
refs/heads/master
<file_sep>package com.flags.dao; import java.util.List; import com.flags.controller.model.PersonsFormData; import com.flags.dao.entity.PersonDataPaginationEntity; import com.flags.dao.entity.PersonsDataEntity; /** * Created by <NAME> on 12/17/2015. * * Taking the data from the entity class especially created for the database */ public interface PersonsDao { public String addPerson(PersonsDataEntity entity); List<PersonsDataEntity> findPersons(); byte[] findImageByUID(String uId); String deletePersonByUID(String uId); PersonsDataEntity findPersonByUID(String uId); List<PersonsDataEntity> findData(String columnName, String searchString); PersonDataPaginationEntity findPersonsWithPagination(int offset, int noOfRecords); int getNoOfRecords(); } <file_sep>package com.flags.rest.webservice; import com.flags.controller.model.PersonsFormData; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; /** * Created by <NAME> on 1/3/2016. * * Wrapper Class */ // Done in order to have the XML Response on the Postman @XmlRootElement public class PersonsList { private List<PersonsFormData> personsFormData; public List<PersonsFormData> getPersonsFormData() { return personsFormData; } public void setPersonsFormData(List<PersonsFormData> personsFormData) { this.personsFormData = personsFormData; } } <file_sep>package com.flags.controller.model; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Time; import java.sql.Date; /** * * Created by <NAME> on 12/17/2015. */ // Done in order to have the XML Response on the Postman @XmlRootElement public class PersonsFormData { /* UID and TimeStamp to be generated from the database */ private int UID; private String email; private String password; private String dob; private String tob; private String country; private String ethinicity ; private String isHappy; private byte[] image; @Override public String toString() { String ret = "From PersonsDataEntiry : [email: " + email + ", password: " + <PASSWORD> + ", Date Of Birth: " + dob + ", Time of Birth: " + tob + ", Country: " + country + ", ethnicity: " + ethinicity + ", isHappy? " + isHappy; return ret; } public PersonsFormData() { // System.out.println("###### DEBUG ######: Person Form Data initiated"); } // Name Constructor public PersonsFormData(String email, String password, String dob, String tob, String country, String ethnicity, String isHappy, byte[] image) { this.email = email; this.password = <PASSWORD>; this.dob = dob; this.tob = tob; this.country = country; this.ethinicity = ethnicity; this.isHappy = isHappy; this.setImage(image); } // ACCESSORS AND MUTATORS public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getDob() { return dob; } public void setDob(String dob) { this.dob = dob; } public String getTob() { return tob; } public void setTob(String tob) { this.tob = tob; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getEthinicity() { return ethinicity; } public void setEthinicity(String ethinicity) { this.ethinicity = ethinicity; } public String getIsHappy() { return isHappy; } public void setIsHappy(String isHappy) { this.isHappy = isHappy; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } public int getUID() { return UID; } public void setUID(int uID) { UID = uID; } } <file_sep>package com.flags.dao.entity; import java.util.List; public class PersonDataPaginationEntity { private int noOfRecords; private List<PersonsDataEntity> personList; public int getNoOfRecords() { return noOfRecords; } public void setNoOfRecords(int noOfRecords) { this.noOfRecords = noOfRecords; } public List<PersonsDataEntity> getPersonList() { return personList; } public void setPersonList(List<PersonsDataEntity> personList) { this.personList = personList; } @Override public String toString() { return "PersonDataPaginationEntity [noOfRecords=" + noOfRecords + ", personList=" + personList + "]"; } } <file_sep>package com.flags.rest.webservice; import com.flags.controller.model.PersonDataPaginationForm; import com.flags.controller.model.PersonsFormData; import com.flags.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Scope; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /** * Created by <NAME> on 1/3/2016. * This is going to have the Rest Controllers implemented */ @Controller // 5 types of in Spring Core - 1. Singleton, 2. Prototype, 3. Request, 4. Session, 5. Global Sesssion // 4 in JSP/Servlet - Request, Session, application, page @Scope("request") public class PersonRestController { @Autowired @Qualifier("IPersonService") protected PersonService personService; //Narrowing the Resource @RequestMapping(value = "persons/all", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public PersonsList showPersons(Model model) { // For XML PersonsList personsList = new PersonsList(); // List of Java Objects cannot be converted into JSON // Solution is the use of Wrapper Class List<PersonsFormData> personForms = personService.findPersons(); personsList.setPersonsFormData(personForms); return personsList; } @RequestMapping(value = "testMessage", method = RequestMethod.GET) //This this make the "return" return the String as the text to the response!! @ResponseBody public String message(){ return "TEST_SUCCESSFULLY"; } @RequestMapping(value = "personsPaginationWithAJAX", method = RequestMethod.GET, produces={MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public PersonDataPaginationForm showPersonInPaginationWithAjax(@RequestParam(value="page",required=false)String page,Model model){ int recordsPerPage=3; int currentPage=0; if(page==null) { currentPage=1; }else{ currentPage=Integer.parseInt(page); } System.out.println(currentPage); PersonDataPaginationForm personDataPaginationForm = personService.findPersonsWithPagination((currentPage-1)*recordsPerPage, recordsPerPage); personDataPaginationForm.setCurrentPage(currentPage); personDataPaginationForm.initPagination(); return personDataPaginationForm; } } <file_sep>#MVC Explored <file_sep>package com.flags.service; import org.springframework.stereotype.Service; @Service("reverseNameService") public class CountryNameReverseService { public String nameReverse(String country){ String ret=""; for (int i = country.length() - 1; i >= 0 ; i--) { ret = ret + country.charAt(i); } return ret; } } <file_sep>package com.flags.soap.webservice; public class Welcome { private String mCode; private String message; public String getmCode() { return mCode; } public void setmCode(String mCode) { this.mCode = mCode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "Welcome [mCode=" + mCode + ", message=" + message + "]"; } } <file_sep>package com.flags.controller.model; import java.util.List; /** * Created by <NAME> on 1/4/2016. */ public class PersonDataPaginationForm { private int currentPage; private int noOfRecords; private List<PersonsFormData> personsFormDataList; private int recordsPerPage = 7; private int noOfPages; public void initPagination(){ noOfPages=(int) Math.ceil(noOfRecords * 1.0 / recordsPerPage); } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getNoOfRecords() { return noOfRecords; } public void setNoOfRecords(int noOfRecords) { this.noOfRecords = noOfRecords; } public List<PersonsFormData> getPersonsFormDataList() { return personsFormDataList; } public void setPersonsFormDataList(List<PersonsFormData> personsFormDataList) { this.personsFormDataList = personsFormDataList; } public int getRecordsPerPage() { return recordsPerPage; } public void setRecordsPerPage(int recordsPerPage) { this.recordsPerPage = recordsPerPage; } public int getNoOfPages() { return noOfPages; } public void setNoOfPages(int noOfPages) { this.noOfPages = noOfPages; } }
05fda55464eac5199c07f88b149646672efbb64d
[ "Markdown", "Java" ]
9
Java
nitinkc/SpringMVCTraining
28569200388dddcf4cfa3a7b7c798f634a45d4f3
7d980c2be8565f4367fb117508b2ba83999ecc3d
refs/heads/master
<repo_name>anyks/misprint<file_sep>/dpa.cpp #include "dpa.hpp" // Устанавливаем пространство имен using namespace std; // Устанавливаем шаблон функции template <typename C, typename T, typename A> /** * trim Функция удаления начальных и конечных пробелов * @param str строка для обработки * @param loc локаль * @return результат работы функции */ basic_string <C, T, A> trim(const basic_string <C, T, A> & str, const locale & loc = locale::classic()){ // Запоминаем итератор на первый левый символ auto begin = str.begin(); // Переходим по всем символам в слове и проверяем является ли символ - символом пробела, если нашли то смещаем итератор while((begin != str.end()) && isspace(* begin, loc)) ++begin; // Если прошли все слово целиком значит пробелов нет и мы выходим if(begin == str.end()) return {}; // Запоминаем итератор на первый правый символ auto rbegin = str.rbegin(); // Переходим по всем символам в слове и проверяем является ли символ - символом пробела, если нашли то смещаем итератор while(rbegin != str.rend() && isspace(* rbegin, loc)) ++rbegin; // Выводим результат return {begin, rbegin.base()}; } /** * cbegin Метод итератор начала списка * @return итератор */ const set <u_int>::iterator morph::DPA::Alphabet::cbegin() const { // Выводим итератор return this->letters.cbegin(); } /** * cend Метод итератор конца списка * @return итератор */ const set <u_int>::iterator morph::DPA::Alphabet::cend() const { // Выводим итератор return this->letters.cend(); } /** * crbegin Метод обратный итератор начала списка * @return итератор */ const set <u_int>::reverse_iterator morph::DPA::Alphabet::crbegin() const { // Выводим итератор return this->letters.crbegin(); } /** * crend Метод обратный итератор конца списка * @return итератор */ const set <u_int>::reverse_iterator morph::DPA::Alphabet::crend() const { // Выводим итератор return this->letters.crend(); } /** * Метод получения списка альтернативных букв * return список альтернативных букв */ const map <u_int, u_int> morph::DPA::Alphabet::getAlternatives() const { // Результат работы функции map <u_int, u_int> result; // Если список альтернативных букв существует if(!alternatives.empty()) result.insert(alternatives.begin(), alternatives.end()); // Выводим результат return move(result); } /** * lettersByText Метод получения списка букв в слове * @param word слово для обработки * @return список букв */ const list <wstring> morph::DPA::Alphabet::lettersByText(const wstring & word) const { // Реузльтат работы функции list <wstring> result; // Если слово не пустое if(!word.empty()){ // Смещение в тексте size_t offset = 0; // Буква в тексте wstring letter; // Размер текста const size_t length = word.length(); // Выполняем перебор букв while(offset < length){ // Ищем дефиз const wstring & letter = word.substr(offset, 1); // Добавляем в список букву result.push_back(letter); // Увеличиваем смещение offset += letter.length(); } } // Выводим результат return move(result); } /** * replace Метод замены в тексте слово на другое слово * @param text текст в котором нужно произвести поиск * @param word слово для поиска * @param alt слово на которое нужно произвести замену * @return результирующий текст */ const wstring morph::DPA::Alphabet::replace(const wstring text, const wstring word, const wstring alt) const { // Результат работы функции wstring result = text; // Если текст передан и искомое слово не равно слову для замены if(!result.empty() && !word.empty() && (this->toLower(word).compare(this->toLower(alt)) != 0)){ // Позиция искомого текста size_t pos = 0; // Определяем текст на который нужно произвести замену const wstring & alternative = (!alt.empty() ? alt : L""); // Выполняем поиск всех слов while((pos = this->toLower(result).find(this->toLower(word))) != wstring::npos){ // Выполняем замену текста result.replace(pos, word.length(), alt); } } // Выводим результат return move(result); } /** * lidToLetter Метод перевода цифрового идентификатора буквы в букву * @param lid идентификатор буквы * @return буква в текстовом виде */ const wstring morph::DPA::Alphabet::lidToLetter(const u_int lid) const { // Результат работы функции wstring result = L""; // Если идентификатор передан, получаем из него строку if(lid > 0) result = wstring(1, wchar_t(lid)); // Выводим результат return move(result); } /** * getAlternative Метод получения альтернативной буквы * @param letter буква для проверки * @return альтернативная буква */ const wstring morph::DPA::Alphabet::getAlternative(const wstring & letter) const { // Резузльтат работы функции wstring result = L""; // Если буква передана if(!letter.empty()){ // Получаем идентификатор буквы const u_int lid = this->letterToLid(letter); // Получаем данные буквы auto data = this->alternatives.find(lid); // Запоминаем результат result = this->lidToLetter(data->second); } // Выводим в результат return move(result); } /** * getRealLetter Метод получения реальной буквы из альтернативной * @param alternative альтернативная буква * @return реальная буква */ const wstring morph::DPA::Alphabet::getRealLetter(const wstring & alternative) const { // Резузльтат работы функции wstring result = L""; // Если альтернативная буква передана if(!alternative.empty()){ // Получаем идентификатор буквы const u_int aid = this->letterToLid(alternative); // Переходим по всему списку альтернативных букв for(auto it = this->alternatives.cbegin(); it != this->alternatives.cend(); ++it){ // Если буква найдена if(aid == it->second){ // Запоминаем результат result = this->lidToLetter(it->first); // Выходим из цикла break; } } } // Выводим в результат return move(result); } /** * toString Метод конвертирования строки utf-8 в строку * @param str строка utf-8 для конвертирования * @return обычная строка */ const string morph::DPA::Alphabet::toString(const wstring & str) const { // Результат работы функции string result; // Если строка передана if(!str.empty()){ // Объявляем конвертер wstring_convert <codecvt_utf8 <wchar_t>> conv; // Выполняем конвертирование в utf-8 строку result = conv.to_bytes(str); } // Выводим результат return move(result); } /** * toWstring Метод конвертирования строки в строку utf-8 * @param str строка для конвертирования * @return строка в utf-8 */ const wstring morph::DPA::Alphabet::toWstring(const string & str) const { // Результат работы функции wstring result; // Если строка передана if(!str.empty()){ // Объявляем конвертер wstring_convert <codecvt_utf8 <wchar_t>> conv; // Выполняем конвертирование в utf-8 строку result = conv.from_bytes(str); } // Выводим результат return move(result); } /** * toLower Метод перевода русских букв в нижний регистр * @param str строка для перевода * @return строка в нижнем регистре */ const wstring morph::DPA::Alphabet::toLower(const wstring & str) const { // Результат работы функции wstring result = str; // Если строка передана if(!str.empty()){ // Объявляем локаль const locale utf8("en_US.UTF-8"); // Переходим по всем символам for(auto & c : result) c = std::tolower(c, utf8); } // Выводим результат return move(result); } /** * toUpper Метод перевода русских букв в верхний регистр * @param str строка для перевода * @return строка в верхнем регистре */ const wstring morph::DPA::Alphabet::toUpper(const wstring & str) const { // Результат работы функции wstring result = str; // Если строка передана if(!str.empty()){ // Объявляем локаль const locale utf8("en_US.UTF-8"); // Переходим по всем символам for(auto & c : result) c = std::toupper(c, utf8); } // Выводим результат return move(result); } /** * isNumber Метод проверки является ли строка числом * @param str строка для проверки * @return результат проверки */ const bool morph::DPA::Alphabet::isNumber(const wstring & str) const { return !str.empty() && find_if(str.begin(), str.end(), [](wchar_t c){ return !iswdigit(c); }) == str.end(); } /** * letterToLid Метод перевода буквы в цифровой идентификатор * @param letter буква для конвертации * @return идентификатор буквы */ const u_int morph::DPA::Alphabet::letterToLid(const wstring & letter) const { // Результат работы функции u_int result = 0; // Если буква передана, выполняем приведение типов if(!letter.empty()) result = u_int(letter[0]); // Выводим результат return move(result); } /** * count Метод получения количества букв в словаре * @return количество букв в словаре */ const size_t morph::DPA::Alphabet::count() const { // Выводим результат return this->letters.size(); } /** * find Метод поиска текста без учета регистра * @param text1 текст в котором нужно найти другой текст * @param text2 текст который нужно найти * @return позиция первого символа найденного текста */ const size_t morph::DPA::Alphabet::find(const wstring & text1, const wstring & text2) const { // Результат работы функции size_t result = wstring::npos; // Если оба текста переданы if(!text1.empty() && !text2.empty()){ // Приводим к нижней строке оба текста const wstring & str1 = this->toLower(text1); const wstring & str2 = this->toLower(text2); // Выполняем поиск текста result = str1.find(str2); } // Выводим результат return move(result); } /** * similarity Метод проверки схожести двух текстов * @param text1 первый текст для проверки * @param text2 второй текст для проверки * @return результат проверки */ const bool morph::DPA::Alphabet::similarity(const wstring & text1, const wstring & text2) const { // Результат работы функции bool result = false; // Если оба текста переданы if(!text1.empty() && !text2.empty()){ // Объявляем объект дистанции Левенштейна LD ld; // Получаем сабтокен const u_short stl = SUBTOKEN_LENGTH; // Получаем коэффициент танимото const float tm = ld.tanimoto(text1, text2, stl), threshold = THRESHOLD_WORD; // Получаем результат result = (threshold <= tm); } // Выводим результат return move(result); } /** * check Метод проверки соответствии буквы * @param letter буква для проверки * @return результат проверки */ const bool morph::DPA::Alphabet::check(const wstring & letter) const { // Результат работы функции bool result = false; // Результат проверки if(!letter.empty()){ // Переводим букву в нижний регистр const wstring & str = this->toLower(letter); // Получаем идентификатор буквы const u_int lid = this->letterToLid(str); // Выполняем проверку буквы result = (this->letters.count(lid) != 0); } // Выводим результат return move(result); } /** * isCase Метод определения регистра первого символа в строке * @param str строка для проверки * @return регистр символов (true - верхний, false - нижний) */ const bool morph::DPA::Alphabet::isCase(const wstring & str) const { // Результат работы функции bool result = false; // Если данные переданы if(!str.empty()){ // Получаем первую букву слова const wstring & letter1 = str.substr(0, 1); // Переводим букву в верхний регистр const wstring & letter2 = this->toUpper(letter1); // Проверяем на регистр символа result = (letter1.compare(letter2) == 0); } // Выводим результат return move(result); } /** * isAlternative Метод проверки существования альтернативной буквы * @param letter буква для проверки * @return результат проверки */ const bool morph::DPA::Alphabet::isAlternative(const wstring & letter) const { // Результат работы функции bool result = false; // Если буква передана if(!letter.empty()){ // Получаем идентификатор буквы const u_int lid = this->letterToLid(letter); // Выполняем проверку result = (this->alternatives.count(lid) > 0); } // Выводим результат return move(result); } /** * split Метод разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void morph::DPA::Alphabet::split(const wstring & str, const wstring delim, list <wstring> & v) const { size_t i = 0; size_t j = str.find(delim); size_t len = delim.length(); // Выполняем разбиение строк while(j != wstring::npos){ v.push_back(str.substr(i, j - i)); i = ++j + (len - 1); j = str.find(delim, j); if(j == wstring::npos) v.push_back(str.substr(i, str.length())); } // Если слово передано а вектор пустой, тогда создаем вектори из 1-го элемента if(!str.empty() && v.empty()) v.push_back(str); } /** * uppLetterWord Метод перевода первого символа в строке в верхний регистр * @param str строка для перевода */ void morph::DPA::Alphabet::uppLetterWord(wstring & str) const { // Если строка передана if(!str.empty()){ // Переводим букву в верхний регистр const wstring & letter = this->toUpper(str.substr(0, 1)); // Заменяем букву в тексте str.replace(0, letter.length(), letter); } } /** * clearBadChar Метод очистки текста от всех символов кроме русских * @param str строка для очистки */ void morph::DPA::Alphabet::clearBadChar(wstring & str){ // Если строка передана if(!str.empty()){ // Результирующая строка wstring result = L""; // Переходим по всей строке for(size_t i = 0; i < str.length(); i++){ // Получаем букву для сравнения const wstring & letter = str.substr(i, 1); // Если строка текста соответствует if((letter.compare(L"-") == 0) || (letter.compare(L" ") == 0) || (letter.compare(L"\r") == 0) || (letter.compare(L"\n") == 0) || (this->check(letter))) result.append(letter); } // Если строка получена тогда заменяем ей исходную строку if(!result.empty()) str = result; } } /** * add Метод добавления буквы в алфавит * @param letter буква для добавления */ void morph::DPA::Alphabet::add(const wstring & letter){ // Если буква передана if(!letter.empty()){ // Получаем идентификатор буквы const u_int lid = this->letterToLid(letter); // Если такой буквы в алфавите нет if(this->letters.count(lid) < 1){ // Добавляем букву в список this->letters.insert(lid); } } } /** * clearAlternative Метод удаления альтернативной буквы * @param letter буква у которой есть альтернативная буква */ void morph::DPA::Alphabet::clearAlternative(const wstring letter){ // Получаем идентификатор буквы const u_int lid = this->letterToLid(letter); // Если буква передана if(!letter.empty()){ // Удаляем выбранную букву из списка if(this->alternatives.count(lid) > 0) this->alternatives.erase(lid); // Если буква не передана то удаляем все альтернативные буквы } else this->alternatives.clear(); } /** * addAlternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void morph::DPA::Alphabet::addAlternative(const wstring & letter, const wstring & alternative){ // Если буквы переданы if(!letter.empty() && !alternative.empty()){ // Получаем идентификатор буквы const u_int lid = this->letterToLid(letter); // Получаем идентификатор альтернативной буквы const u_int aid = this->letterToLid(alternative); // Если альтернативная буква не найдена в списке if(this->alternatives.count(lid) < 1){ // Добавляем букву в список this->alternatives.insert({move(lid), move(aid)}); } } } /** * compress Метод сжатия данных * @param buffer буфер данных для сжатия * @return результат сжатия */ const vector <char> morph::DPA::Df::compress(const vector <char> & buffer) const { // Результат работы функции vector <char> result; // Если буфер передан if(!buffer.empty()){ // Создаем поток zip z_stream zs; // Результирующий размер данных int ret = 0; // Заполняем его нулями memset(&zs, 0, sizeof(zs)); // Если поток инициализировать не удалось, выходим if(deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, MOD_GZIP_ZLIB_WINDOWSIZE + 16, MOD_GZIP_ZLIB_CFACTOR, Z_DEFAULT_STRATEGY) == Z_OK){ try { // Заполняем входные данные буфера zs.next_in = (Bytef *) buffer.data(); // Указываем размер входного буфера zs.avail_in = buffer.size(); // Создаем буфер с сжатыми данными char * zbuff = new char[(const size_t) zs.avail_in]; // Выполняем сжатие данных do { // Устанавливаем максимальный размер буфера zs.avail_out = zs.avail_in; // Устанавливаем буфер для получения результата zs.next_out = reinterpret_cast<Bytef *> (zbuff); // Выполняем сжатие ret = deflate(&zs, Z_FINISH); // Если данные добавлены не полностью if(result.size() < zs.total_out) // Добавляем оставшиеся данные result.insert(result.end(), zbuff, zbuff + (zs.total_out - result.size())); } while(ret == Z_OK); // Удаляем буфер данных delete [] zbuff; // Если происходит ошибка то игнорируем её } catch(const bad_alloc&) {} } // Завершаем сжатие deflateEnd(&zs); // Если сжатие не удалось то очищаем выходные данные if(ret != Z_STREAM_END) result.clear(); } // Выводим результат return move(result); } /** * decompress Метод рассжатия данных * @param buffer буфер данных для расжатия * @return результат расжатия */ const vector <char> morph::DPA::Df::decompress(const vector <char> & buffer) const { // Результат работы функции vector <char> result; // Если буфер передан if(!buffer.empty()){ // Создаем поток zip z_stream zs; // Результирующий размер данных int ret = 0; // Заполняем его нулями memset(&zs, 0, sizeof(zs)); // Если поток инициализировать не удалось, выходим if(inflateInit2(&zs, MOD_GZIP_ZLIB_WINDOWSIZE + 16) == Z_OK){ try { // Заполняем входные данные буфера zs.next_in = (Bytef *) buffer.data(); // Указываем размер входного буфера zs.avail_in = buffer.size(); // Получаем размер выходных данных const size_t size = (zs.avail_in * 10); // Создаем буфер с результирующими данными char * zbuff = new char[size]; // Выполняем расжатие данных do { // Устанавливаем буфер для получения результата zs.next_out = reinterpret_cast<Bytef *> (zbuff); // Устанавливаем максимальный размер буфера zs.avail_out = size; // Выполняем расжатие ret = inflate(&zs, 0); // Если данные добавлены не полностью if(result.size() < zs.total_out) // Добавляем оставшиеся данные result.insert(result.end(), zbuff, zbuff + (zs.total_out - result.size())); } while(ret == Z_OK); // Удаляем буфер данных delete [] zbuff; // Если происходит ошибка то игнорируем её } catch(const bad_alloc&) {} } // Завершаем расжатие inflateEnd(&zs); // Если сжатие не удалось то очищаем выходные данные if(ret != Z_STREAM_END) result.clear(); } // Выводим результат return move(result); } /** * read Метод чтения данных из файла * @param filename адрес файла * @param buffer буфер данных для чтения */ void morph::DPA::Df::read(const string & filename, vector <char> & buffer) const { // Если адрес файла передан if(!filename.empty()){ // Структура проверка статистики struct stat info; // Проверяем переданный нам адрес bool isFile = (stat(filename.c_str(), &info) == 0); // Если это файл if(isFile) isFile = ((info.st_mode & S_IFMT) != 0); // Если путь существует if(isFile){ // Размер файла size_t size = 0; // Открываем файл на чтение ifstream file(filename.c_str(), ios::binary); // Если файл открыт if(file.is_open()){ // Количество обработанных байт size_t osize = 0, lsize = 0; // Перемещаемся в конец файла file.seekg(0, file.end); // Определяем размер файла size = file.tellg(); // Перемещаемся в начало файла file.seekg(0, file.beg); /* // Создаем буфер для чтения данных char bytes[BUFFER_CHUNK]; // Очищаем буфер данных buffer.clear(); // Считываем до тех пор пока все удачно while(file.good()){ // Зануляем буфер данных memset(bytes, 0, BUFFER_CHUNK); // Выполняем чтение данных в буфер file.read(bytes, BUFFER_CHUNK); // Добавляем полученные данные buffer.insert(buffer.end(), bytes, bytes + BUFFER_CHUNK); } */ // Закрываем файл file.close(); } // Если файл не нулевого размера if(size > 0){ // Устанавливаем размер чанка const u_int chunk = (size > (BUFFER_CHUNK * 2) ? (BUFFER_CHUNK * 2) : size); // Устанавливаем размер смещения size_t offset = 0, difference = 0; // Считываемые данные void * data = nullptr; // Открываем файл на чтение const int fd = open(filename.c_str(), O_RDONLY); // Если файловый дескриптор открыт if(fd > -1){ // Выделяем память для буфера данных vector <char> bytes; // Выполняем чтение пока все не прочитаем while(offset < size){ // Определяем разницу размеров difference = (size - offset); // Определяем реальный размер чанка const u_int rhunk = (offset < size ? (difference > chunk ? chunk : difference) : 0); // Выполняем чтение данных data = mmap(nullptr, rhunk, PROT_READ, MAP_SHARED, fd, offset); // Копируем в буфер прочитанные данные bytes.insert(bytes.end(), (char *) data, (char *) data + rhunk); // Выполняем синхронизацию с файловой системой // msync(data, chunk, MS_ASYNC); // Очищаем полученные данные munmap(data, rhunk); // Увеличиваем смещение offset += rhunk; } // Очищаем буфер данных buffer.clear(); // Добавляем полученные данные buffer.insert(buffer.end(), bytes.begin(), bytes.end()); // Закрываем файловый дескриптор close(fd); } } } } } /** * write Метод записи данных в файл * @param filename адрес файла * @param buffer буфер данных для записи */ void morph::DPA::Df::write(const string & filename, vector <char> & buffer) const { // Если адрес файла и буфер переданы if(!filename.empty() && !buffer.empty()){ // Открываем файл на запись ofstream file(filename.c_str(), ios::binary); // Если файл открыт if(file.is_open()){ // Выполняем запись в файл file.write((char *) buffer.data(), buffer.size()); // Закрываем файл file.close(); } } } /** * mkdir Метод рекурсивного создания каталогов * @param path адрес каталогов */ void morph::DPA::Df::mkdir(const string & path) const { // Если путь передан if(!path.empty()){ // Буфер с названием каталога char tmp[256]; // Указатель на сепаратор char * p = nullptr; // Копируем переданный адрес в буфер snprintf(tmp, sizeof(tmp), "%s", path.c_str()); // Определяем размер адреса size_t len = strlen(tmp); // Если последний символ является сепаратором тогда удаляем его if(tmp[len - 1] == '/') tmp[len - 1] = 0; // Переходим по всем символам for(p = tmp + 1; * p; p++){ // Если найден сепаратор if(* p == '/'){ // Сбрасываем указатель * p = 0; // Создаем каталог ::mkdir(tmp, S_IRWXU); // Запоминаем сепаратор * p = '/'; } } // Создаем последний каталог ::mkdir(tmp, S_IRWXU); } } /** * checkCount Метод получения количества потомков * @param ref эталон для проверки * @param word слово для поиска * @return результат проверки */ const size_t morph::DPA::Stk::checkCount(const wstring & ref, wstring word) const { // Результат работы функции size_t result = 0; // Если есть продолжение тогда извлекаем остальные if(!this->children.empty()){ // Буква для поиска wstring letter = L""; // Запоминаем длину слова const size_t size = word.length(); // Если реферал больше чем слово для перебора if(ref.length() > size){ // Копируем реферала wstring referal = ref; // Выполняем поиск подстроки в строке const size_t pos = ref.find(word); // Если подстрока найдена if(pos != wstring::npos){ // Удаляем из реферала первые буквы referal.replace(pos, size, L""); // Получаем букву letter = referal.substr(0, 1); // Выполняем приведение типа const u_int lid = this->alphabet->letterToLid(letter); // Если такая буква есть в списке if(this->children.count(lid) > 0){ // Запрашиваем данные буквы auto it = this->children.find(lid); // Проверяем следующие элементы result = this->count(ref, it->second, word); } } } } // Выводим результат return move(result); } /** * count Метод получения количества потомков * @param ref эталон для проверки * @param ctx объект структуры для поиска * @param word слово для поиска * @return результат проверки */ const size_t morph::DPA::Stk::count(const wstring & ref, void * ctx, wstring word) const { // Результат работы функции size_t result = 0; // Если родительский объект передан if(ctx != nullptr){ // Получаем родительский объект Stk * parent = reinterpret_cast <Stk *> (ctx); // Получаем букву const wstring & letter = parent->getLetter(); // Если буква существует if(letter.length() == 1){ // Добавляем букву к слову word.append(letter); // Поиск на совпадение слова bool fnd = true; // Если эталонное слово указано if(!ref.empty()) fnd = (ref.compare(word) == 0); // Если поисковое слово уже найдено if(fnd || (word.length() <= ref.length())){ // Если это конец слова тогда запоминаем результат if(fnd) result = parent->count(); // Выполняем поиск дальше else result = parent->checkCount(ref, word); } } } // Выводим результат return move(result); } /** * checkNext Метод проверки следующего слова * @param ref эталон для проверки * @param word слово для поиска * @return результат проверки */ const bool morph::DPA::Stk::checkNext(const wstring & ref, wstring word) const { // Результат работы функции bool result = false; // Если есть продолжение тогда извлекаем остальные if(!this->children.empty()){ // Буква для поиска wstring letter = L""; // Запоминаем длину слова const size_t size = word.length(); // Если реферал больше чем слово для перебора if(ref.length() > size){ // Копируем реферала wstring referal = ref; // Выполняем поиск подстроки в строке const size_t pos = ref.find(word); // Если подстрока найдена if(pos != wstring::npos){ // Удаляем из реферала первые буквы referal.replace(pos, size, L""); // Получаем букву letter = referal.substr(0, 1); // Выполняем приведение типа const u_int lid = this->alphabet->letterToLid(letter); // Если такая буква есть в списке if(this->children.count(lid) > 0){ // Запрашиваем данные буквы auto it = this->children.find(lid); // Проверяем следующие элементы result = this->check(ref, it->second, word); } } } } // Выводим результат return move(result); } /** * check Метод проверки существования слова * @param ref эталон для проверки * @param ctx объект структуры для поиска * @param word слово для поиска * @return результат проверки */ const bool morph::DPA::Stk::check(const wstring & ref, void * ctx, wstring word) const { // Результат работы функции bool result = false; // Если родительский объект передан if(ctx != nullptr){ // Получаем родительский объект Stk * parent = reinterpret_cast <Stk *> (ctx); // Получаем букву const wstring & letter = parent->getLetter(); // Если буква существует if(letter.length() == 1){ // Добавляем букву к слову word.append(letter); // Поиск на совпадение слова bool fnd = true; // Если эталонное слово указано if(!ref.empty()) fnd = (word.find(ref, 0) != wstring::npos); // Если поисковое слово уже найдено if(fnd || (word.length() <= ref.length())){ // Если это конец слова тогда запоминаем результат result = (fnd && parent->isEnd()); // Выполняем поиск дальше if(!result) result = parent->checkNext(ref, word); } } } // Выводим результат return move(result); } /** * add Метод добавления букв в базу * @param word часть слова для добавления * @param ctx объект на следующий элемент структуры */ void morph::DPA::Stk::add(queue <wstring> & word, void * ctx){ // Если данные переданы if(!word.empty() && (ctx != nullptr)){ // Получаем первый элемент в списке const wstring & letter = word.front(); // Получаем родительский объект Stk * parent = reinterpret_cast <Stk *> (ctx); // Добавляем букву parent->setLetter(letter, word.size() == 1); // Удаляем текущий элемент из списка word.pop(); // Добавляем букву в список if(!word.empty()){ // Запрашиваем объект данных Stk * stk = reinterpret_cast <Stk *> (parent->getStkByLetter(word.front())); // Добавляем слово в список if(stk != nullptr) parent->add(word, stk); } } } /** * removeNext Метод удаления следующего слова * @param ref эталон для проверки * @param word слово для удаления */ void morph::DPA::Stk::removeNext(const wstring & ref, wstring word){ // Если есть продолжение тогда извлекаем остальные if(!this->children.empty()){ // Буква для поиска wstring letter = L""; // Запоминаем длину слова const size_t size = word.length(); // Если реферал больше чем слово для перебора if(ref.length() > size){ // Копируем реферала wstring referal = ref; // Выполняем поиск подстроки в строке const size_t pos = ref.find(word); // Если подстрока найдена if(pos != wstring::npos){ // Удаляем из реферала первые буквы referal.replace(pos, size, L""); // Получаем букву letter = referal.substr(0, 1); // Выполняем приведение типа const u_int lid = this->alphabet->letterToLid(letter); // Если такая буква есть в списке if(this->children.count(lid) > 0){ // Запрашиваем данные буквы auto it = this->children.find(lid); // Получаем родительский объект Stk * children = reinterpret_cast <Stk *> (it->second); // Уменьшаем количество потомков this->descendants -= children->count(); // Ищем и удаляем следующие элементы this->remove(ref, it->second, word); } } // Выполняем перебор оставшихся букв } else { // Переходим по всему алфавиту букв for(auto it = this->children.cbegin(); it != this->children.cend(); ++it){ // Получаем родительский объект Stk * children = reinterpret_cast <Stk *> (it->second); // Уменьшаем количество потомков this->descendants -= children->count(); // Ищем и удаляем следующие элементы this->remove(ref, it->second, word); } } } } /** * findNext Метод поиска следующего слова * @param ref эталон для проверки * @param words список результат поиска * @param depth глубина поиска (количество букв которые отличаются) * @param max максимальное количество слов для отдачи * @param word слово для поиска */ void morph::DPA::Stk::findNext(const wstring & ref, list <wstring> & words, const u_short depth, const size_t max, wstring word) const { // Если есть продолжение тогда извлекаем остальные if(!this->children.empty()){ // Буква для поиска wstring letter = L""; // Запоминаем длину слова const size_t size = word.length(); // Если реферал больше чем слово для перебора if(ref.length() > size){ // Копируем реферала wstring referal = ref; // Выполняем поиск подстроки в строке const size_t pos = ref.find(word); // Если подстрока найдена if(pos != wstring::npos){ // Удаляем из реферала первые буквы referal.replace(pos, size, L""); // Получаем букву letter = referal.substr(0, 1); // Выполняем приведение типа const u_int lid = this->alphabet->letterToLid(letter); // Если такая буква есть в списке if(this->children.count(lid) > 0){ // Запрашиваем данные буквы auto it = this->children.find(lid); // Ищем следующие элементы this->find(ref, words, it->second, depth, max, word); } } // Выполняем перебор оставшихся букв } else { // Переходим по всему алфавиту букв for(auto it = this->children.cbegin(); it != this->children.cend(); ++it){ // Ищем следующие элементы this->find(ref, words, it->second, depth, max, word); } } } } /** * remove Метод удаления подходящих слов * @param ref эталон для проверки * @param ctx объект структуры для поиска * @param word слово для поиска */ void morph::DPA::Stk::remove(const wstring & ref, void * ctx, wstring word){ // Если объект существует if(ctx != nullptr){ // Получаем родительский объект Stk * parent = reinterpret_cast <Stk *> (ctx); // Получаем букву структуры const wstring & letter = parent->getLetter(); // Если буква существует if(letter.length() == 1){ // Добавляем букву к слову word.append(letter); // Поиск на совпадение слова bool fnd = true; // Если эталонное слово указано if(!ref.empty()) fnd = (word.find(ref, 0) != wstring::npos); // Выполняем удаление дальше parent->removeNext(ref, word); // Удаляем родительский объект if(fnd && (ref.compare(letter) != 0) && !letter.empty()) parent->clear(); } } } /** * find Метод поиска подходящих слов * @param ref эталон для проверки * @param words список результат поиска * @param ctx объект структуры для поиска * @param depth глубина поиска (количество букв которые отличаются) * @param max максимальное количество слов для отдачи * @param word слово для поиска */ void morph::DPA::Stk::find(const wstring & ref, list <wstring> & words, void * ctx, const u_short depth, const size_t max, wstring word) const { // Если объект существует if(ctx != nullptr){ // Если размер списка уже превышен тогда завершаем работу if((words.size() < max) || (max == 0)){ // Получаем родительский объект Stk * parent = reinterpret_cast <Stk *> (ctx); // Получаем букву const wstring & letter = parent->getLetter(); // Если буква существует if(letter.length() == 1){ // Добавляем букву к слову word.append(letter); // Поиск на совпадение слова bool fnd = true; // Если эталонное слово указано if(!ref.empty()) fnd = (word.find(ref, 0) != wstring::npos); // Если поисковое слово уже найдено if(fnd || (word.length() <= ref.length())){ // Если глубина поиска еще не достигнута if((depth == 0) || (word.length() <= (ref.length() + depth))){ // Если это конец слова тогда добавляем в список if(fnd && parent->isEnd()) words.push_back(word); // Выполняем поиск дальше parent->findNext(ref, words, depth, max, word); } } } } } } /** * count Метод получения количество дочерних элементов * @return количество дочерних элементов */ const size_t morph::DPA::Stk::count() const { // Выводим количество потомков return this->descendants; } /** * countWord Метод получения количество потомков * @param word слово для проверки * @return результат проверки */ const size_t morph::DPA::Stk::countWord(const wstring & word){ // Результат работы функции size_t result = 0; // Если слово передано if(!word.empty()){ // Переводим слово в нижний регистр const wstring & str = this->alphabet->toLower(word); // Выполняем проверку слова result = this->count(str, this); } // Выводим результат return move(result); } /** * getLetter Метод получения буквы * @return хранимая буква */ const wstring morph::DPA::Stk::getLetter() const { // Выводим букву return this->alphabet->lidToLetter(this->letter); } /** * findWords Метод поиска подходящих слов * @param word эталон для проверки * @param depth глубина поиска (количество букв которые отличаются) * @param max максимальное количество слов для отдачи * @param parent родительский объект * @return список результат поиска */ const list <wstring> morph::DPA::Stk::findWords(const wstring & word, const u_short depth, const size_t max, void * parent){ // Создаем результирующий список list <wstring> result; // Слово передано if(!word.empty()){ // Переводим слово в нижний регистр const wstring & str = this->alphabet->toLower(word); // Выполняем поиск слова this->find(str, result, this, depth, max); // Если корректировка альтернативной буквы включена if(this->isalter && (parent != nullptr)){ // Переходим по всему списку и ищем слово замены for(auto it = result.begin(); it != result.end(); ++it){ // Получаем текст для обработки const wstring & text = (* it); // Переходим по всем буквам for(size_t i = 0; i < text.length(); i++){ // Получаем строку const wstring & letter = text.substr(i, 1); // Если для буквы существует альтернативная буква if(this->alphabet->isAlternative(letter)){ // Получаем временное слово wstring word = text; // Получаем альтернативную букву const wstring & alternative = this->alphabet->getAlternative(letter); // Выполняем замену буквы в тексте word.replace(i, 1, alternative); // Если слово найдено if((reinterpret_cast <DPA *> (parent))->check(word)){ // Запоминаем полученное слово * it = word; // Выходим из цикла break; } } } } } // Выполняем сортировку списка result.sort(); // Удаляем все повторяющиеся элементы в списке result.erase(unique(result.begin(), result.end()), result.end()); } // Выводим результат return move(result); } /** * getStkByLetter Метод получения объекта * @param letter буква для поиска * @return результат работы метода */ void * morph::DPA::Stk::getStkByLetter(const wstring & letter){ // Указатель на объект void * stk = nullptr; // Если буква передана if(!letter.empty()){ // Выполняем копирование слова const u_int lid = this->alphabet->letterToLid(letter); // Если такой ключ существует if(this->children.count(lid) > 0){ // Выполняем поиск буквы stk = this->children.find(lid)->second; // Если буква не найдена } else { try { // Выделяем память под объект stk = new Stk(this->alphabet); // Добавляем в список новую структуру this->children.insert({lid, stk}); // Если происходит ошибка то игнорируем её } catch(const bad_alloc&) {} } } // Выводим результат return stk; } /** * isEnd Метод проверки на конец слова * @return результат проверки */ const bool morph::DPA::Stk::isEnd() const { // Выводим результат return this->end; } /** * checkLetter Метод проверки на существование буквы * @param letter буква * @return результат проверки */ const bool morph::DPA::Stk::checkLetter(const wstring & letter) const { // Результат работы функции bool result = false; // Если буква передана if(!letter.empty()){ // Выполняем приведение типа const u_int lid = this->alphabet->letterToLid(letter); // Запоминаем результат result = (lid == this->letter); } // Выводим результат return move(result); } /** * checkWord Метод проверки существования слова * @param word слово для проверки * @return результат проверки */ const bool morph::DPA::Stk::checkWord(const wstring & word){ // Результат работы функции bool result = false; // Если слово передано if(!word.empty()){ // Переводим слово в нижний регистр const wstring & str = this->alphabet->toLower(word); // Выполняем проверку слова result = this->check(str, this); } // Выводим результат return move(result); } /** * clear Метод очистки структуры */ void morph::DPA::Stk::clear(){ // Очищаем букву this->letter = 0; // Обнуляем конец слова this->end = false; // Деактивируем корректор this->isalter = false; // Очищаем количество потомков this->descendants = 0; // Переходим по всему списку дочерних обхектов for(auto it = this->children.begin(); it != this->children.end(); ++it){ // Получаем объект для удаления Stk * stk = reinterpret_cast <Stk *> (it->second); // Удаляем выделенную ранее память delete stk; // Запоминаем что объект удален it->second = nullptr; } // Очищаем список дочерних объектов this->children.clear(); } /** * delAlternative Метод деактивации корректора буквы альтернативной буквы */ void morph::DPA::Stk::delAlternative(){ // Деактивируем корректор this->isalter = false; } /** * setCorrector Метод активации корректора буквы альтернативной буквы */ void morph::DPA::Stk::setAlternative(){ // Активируем корректор this->isalter = true; } /** * setLetter Метод добавления буквы * @param letter буква для добавления * @param end завершение работы */ void morph::DPA::Stk::setLetter(const wstring & letter, const bool end){ // Если буква передана if(!letter.empty()){ // Добавляем букву в список this->alphabet->add(letter); // Если это конец тогда запоминаем if(!this->end) this->end = end; // Увеличиваем количество потомков this->descendants++; // Устанавливаем букву this->letter = this->alphabet->letterToLid(letter); } } /** * addWord Метод добавления слова * @param word строка без пробелов (слово должно быть без опечаток) */ void morph::DPA::Stk::addWord(const wstring & word){ // Если строка передана if(!word.empty()){ // Создаем слово в виде структуры queue <wstring> typesetting; // Переводим слово в нижний регистр const wstring & letters = this->alphabet->toLower(word); // Переходим по всему списку букв for(size_t i = 0; i < letters.length(); i++) typesetting.push(letters.substr(i, 1)); // Добавляем слово в список if(!typesetting.empty()) this->add(typesetting, this); } } /** * deleteWords Метод удаления похожих слов * @param word слово для поиска */ void morph::DPA::Stk::deleteWords(const wstring & word){ // Переводим слово в нижний регистр wstring str = this->alphabet->toLower(word); // Выполняем удаление слова this->remove(str, this); } /** * Stk Конструктор * @param alphabet объект алфавита */ morph::DPA::Stk::Stk(Alphabet * alphabet){ // Если объект передан this->alphabet = alphabet; } /** * ~Stk Деструктор */ morph::DPA::Stk::~Stk(){ // Строка начала удаления const wstring & word = this->getLetter(); // Выполняем удаление всех данных this->remove(word, this); } /** * count Метод получения количества потомков * @param word слово для удаления */ const size_t morph::DPA::count(const wstring & word) const { // Результат работы функции size_t result = 0; // Если слово передано if(!word.empty()){ // Получаем копию текста const wstring & wword = word; // Переводим букву в нижний регистр const wstring & letter = this->alphabet->toLower(wword.substr(0, 1)); // Получаем идентификатор буквы const u_int lid = this->alphabet->letterToLid(letter); // Извлекаем данные буквы if(this->letters.count(lid) > 0){ // Выполняем поиск auto obj = this->letters.find(lid); // Удаляем слово result = obj->second->countWord(wword); } } // Выводим результат return move(result); } /** * check Метод проверки существования слова * @param word слово для проверки * @return результат проверки */ const bool morph::DPA::check(const wstring & word) const { // Результат проверки bool result = false; // Если слово передано if(!word.empty()){ // Получаем копию текста const wstring & wword = word; // Переводим букву в нижний регистр const wstring & letter = this->alphabet->toLower(wword.substr(0, 1)); // Получаем идентификатор буквы const u_int lid = this->alphabet->letterToLid(letter); // Извлекаем данные буквы if(this->letters.count(lid) > 0){ // Выполняем поиск auto obj = this->letters.find(lid); // Ищем слова return obj->second->checkWord(wword); } } // Выводим результат return move(result); } /** * checkLevel Метод проверки уровня проверок * @param level уровень проверки * @return результат проверки */ const bool morph::DPA::checkLevel(const u_short level) const { // Результат работы функции bool result = false; // Если уровень для проверки передан if(level != OPT_NULL) result = (level & this->level); // Выводим результат return move(result); } /** * test Метод проверки текста на соответствие словарю * @param text текст для проверки * @return результат проверки */ const bool morph::DPA::test(const wstring & text) const { // Результат проверки bool result = false; // Если текст передан if(!text.empty()){ // Запоминаем текст данных wstring wtext = text; // Удаляем пробелы, переносы строк и табуляцию wtext = regex_replace(wtext, wregex(wstring(L"[\\r\\n\\t\\s]")), wstring(L"")); // Выполняем удаление запрещенных символов this->alphabet->clearBadChar(wtext); // Запоминаем результат result = !wtext.empty(); } // Выводим результат return move(result); } /** * directException Метод прямого исключения * @param word слово для поиска * @return результат работы функции */ const wstring morph::DPA::directException(const wstring & word){ // Результат работы функции wstring result = L""; // Если слово передано if(!word.empty()){ // Запоминаем слово wstring tmp = L""; // Смещение size_t offset = word.length(); // Выполняем поиск оставшихся символов while(offset > 0){ // Получаем фразу для поиска tmp = word.substr(0, offset); // Выполняем проверку const wstring & word = this->find(tmp); // Если результат найден if(!word.empty()){ // Запоминаем искомую фразу result = word; // Выходим из цикла break; } // Уменьшаем смещение offset--; } } // Выводим результат return move(result); } /** * bruteCompare Метод поиска наиболее подходящего слова в списке вариантов * @param word оригинальное слово * @param words список вариантов слов * @return наиболее подходящее слово */ const wstring morph::DPA::bruteCompare(const wstring & word, const list <wstring> & words){ // Результат работы функции wstring result = L""; // Если слово передано if(!word.empty() && !words.empty() && this->checkLevel(OPT_SEVERALLETTER)){ // Получаем размер оригинального текста const size_t size = word.length(); // Дистанция size_t length = size; // Переходим по всему списку вариантов for(auto it = words.cbegin(); it != words.cend(); ++it){ // Получаем длину варианта слова const size_t count = it->length(); // Если размер исходного слова длинше полученного if(size >= count){ // Выполняем проверку содержит ли исходное слово, найденное слово const size_t pos = word.find(* it); // Если слово найдено if(pos != wstring::npos){ // Запоминаем найденную фразу result = (* it); // Выходим из цикла break; } } // Если слова совпадают if(this->alphabet->similarity(word, * it)){ // Запоминаем найденную фразу result = (* it); // Выходим из цикла break; // Если слова не совпадают } else { // Объявляем объект дистанции Левенштейна LD ld; // Определяем дистанцию const size_t distance = ld.distance(word, * it); // Если дистанция минимальная if(distance < length){ // Запоминаем найденную фразу result = (* it); // Запоминаем дистанцию length = distance; // Если дистанция одинаковая то сравниваем размеры текста } else if(length == distance) { // Если размеры совпадают if(size == count) result = (* it); } } } } // Выводим результат return move(result); } /** * brutePicking Метод поиска слова методом подстановки * @param word слово для поиска * @param depth глубина поиска * @return искомое слово */ const wstring morph::DPA::brutePicking(const wstring & word, const size_t depth){ // Результат работы функции wstring result = L""; // Если слово передано if(!word.empty() && (word.length() > 1) && this->checkLevel(OPT_SEVERALLETTER)){ // Смещение в слове int offset = 0; // Копируем слово wstring tmp = word; // Результат проверки bool check = false; // Определяем длину слова const size_t size = word.length(); // Выполняем поиск фразы while(true){ // Переходим по всему алфавиту for(auto it = this->alphabet->cbegin(); it != this->alphabet->cend(); ++it){ // Список слов для поиска list <wstring> words; // Получаем идентификатор буквы const wstring & letter = this->alphabet->lidToLetter(* it); // Заменяем букву tmp.replace(offset, 1, letter); // Выполняем поиск слова this->get(tmp, words, depth); // Если варианты найдены if(!words.empty()){ // Выполняем поиск наилучшего подходящего варианта из списка result = this->bruteCompare(word, words); // Выходим из цикла break; } } // Если слово не найдено if(result.empty()){ // Копируем слово заново tmp = word; // Выполняем смещение offset++; } // Если все возможные варианты перебрали или слово найдено, выходим if(offset > (size - 1) || !result.empty()) break; } } // Выводим результат return move(result); } /** * bruteForce Метод поиска слова методом перебора * @param word слово для поиска * @return найденное слово */ const wstring morph::DPA::bruteForce(const wstring & word){ // Результат работы функции wstring result = L""; // Если слово передано if(!word.empty() && (word.length() > 1) && this->checkLevel(OPT_ONELETTER)){ // Смещение в слове int offset = 1; // Копируем слово wstring tmp = word; // Результат проверки bool check = false; // Определяем длину слова const size_t size = tmp.length(); /** * trust Функция проверки на соотвествие подобранной фразы * @param word слово для проверки * @param offset номер буквы для перебора */ auto trust = [&result, this](const wstring & word, const size_t offset){ // Результат проверки bool check = false; // Если слово передано if(!word.empty()){ // Копируем слово wstring tmp = word; // Переходим по всему алфавиту for(auto it = this->alphabet->cbegin(); it != this->alphabet->cend(); ++it){ // Получаем идентификатор буквы const wstring & letter = this->alphabet->lidToLetter(* it); // Заменяем букву tmp.replace(offset, 1, letter); // Выполняем проверку check = this->check(tmp); // Если слово найдено тогда выходим из цикла if(check){ // Запоминаем найденный результат result = tmp; // Выходим из цикла break; } } } // Выводим результат return check; }; // Выполняем поиск фразы while(true){ // Выполняем проверку на совпадение слова check = trust(tmp, offset); // Если слово не найдено if(!check){ // Копируем слово заново tmp = word; // Выполняем смещение offset++; } // Если все возможные варианты перебрали или слово найдено, выходим if((offset > (size - 1)) || check) break; } // Если слово не найдено проверяем первую букву if(result.empty()) trust(tmp, 0); } // Выводим результат return move(result); } /** * bruteHyphen Метод поиска слова методом переноса дефиза * @param word слово для поиска * @return результат поиска */ const wstring morph::DPA::bruteHyphen(const wstring & word){ // Результат работы функции wstring result = L""; // Если слово передано if(!word.empty() && this->checkLevel(OPT_HYPHENTRUE)){ // Получаем временное слово wstring letters = word; // Если количество букв больше 3 if(letters.size() > 3){ // Переходим по всем буквам слова for(u_int i = letters.length() - 1; i > 0; i--){ // Получаем букву в виде UTF-8 const wstring letter = letters.substr(i, 1); // Заменяем букву на пробел letters.replace(i, 1, L"-" + letter); // Выполняем проверку слова if(this->check(letters)){ // Запоминаем результат result = letters; // Выходим из цикла break; // Если проверка не удачная, выполняем поиск среди исправленного слова } else if(this->checkLevel(OPT_HYPHENFALSE)) { // Выполняем поиск перебором result = this->bruteForce(letters); // Выполняем проверку слова if(!result.empty()) break; } // Заменяем букву обратно letters.replace(i, 2, letter); } } } // Выводим результат return move(result); } /** * find Метод поиска подходящего слова * @param word слово для поиска * @param brute выполнять предварительную проверку перебором вариантов * @result результат работы функции */ const wstring morph::DPA::find(const wstring & word, const bool brute){ // Результат работы функции wstring result = L""; // Если слово передано if(!word.empty() && (word.length() > 1) && this->checkLevel(OPT_SEVERALLETTER)){ // Выполняем поиск перебором if(brute) result = this->bruteForce(word); // Если результат не получен if(result.empty()){ // Запоминаем слово wstring tmp = word; // Длина слова const size_t size = tmp.length(); // Смещение в тексте size_t offset = size; // Выполняем поиск оставшихся символов while(offset > 0){ // Уменьшаем смещение offset--; // Выполняем получение оставшегося текста tmp = tmp.substr(0, offset); // Если слово пустое тогд выходим if(!tmp.empty()){ // Выполняем проверку существует ли слово в базе if(this->check(tmp)) result = tmp; // Если слово в базе не найдено else { // Получаем размер глубины const size_t depth = ((size + 1) - offset); // Список вариантов list <wstring> words; // Выполняем поиск слова this->get(tmp, words, depth); // Выполняем получение наиболее подходящего слова if(!words.empty()) result = this->bruteCompare(tmp, words); // Если списка вариантов нет, пытаемся подобрать вариант else result = this->brutePicking(tmp, depth); } // Выходим из цикла if(!result.empty()) break; // Выходим из цикла } else break; } } } // Выводим результат return move(result); } /** * search Метод поиска наиболее подходящего слова * @param etalon слово для поиска * @param first первое слово для поиска * @return ископоме слово */ const wstring morph::DPA::search(const wstring & etalon, const wstring & first){ // Результат работы функции wstring result = L""; // Если слово передано if(!etalon.empty() && (etalon.length() > 1) && this->checkLevel(OPT_SEVERALLETTER)){ /** * findSecond Функция поиска только второго слова * @param word слово для обработки * @param first первое найденное слово * @return результат поиска */ auto findSecond = [this](const wstring & word, const wstring first){ // Результат работы функции pair <wstring, wstring> result; // Если слово передано if(!word.empty() && !first.empty()){ // Получаем размер слова const size_t size = first.length(); // Копируем первое слово result = make_pair(move(first), L""); // Если длина эталонного слова на много больше if((word.length() >= size) && (size > 0)){ // Получаем данные второго слова wstring second = word; // Получаем последнюю часть слова second.replace(0, size, L""); /** * Выполняем поиск второго слова: * Стоит тут отметить что приходится использовать именно find а не correct * Так как если использовать метод correct и слово будет с ошибкой то, он и его изковеркает * Да с помощью метода find мы получим наилучший результат и потеряем третье слово если оно там есть */ second = this->find(second, true); // Если второе слово найдено if(!second.empty()) result.second = second; } } // Выводим результат return move(result); }; /** * getResult Функция формирования результата из плученных данных * @param etalon эталонное слово * @param first первое слово * @param second второе слово * @return выводим полученный результат */ auto getResult = [](const wstring & etalon, const wstring & first, const wstring & second){ // Результат работы функции wstring result = L""; // Если данные переданы if(!etalon.empty()){ // Если и первое и второе слово переданы if(!first.empty() && !second.empty()){ // Запоминаем первое слово result = first; // Добавляем пробел result.append(L" "); // Добавляем второе слово result.append(second); // Если же первое слово передано а второе нет } else if(!first.empty() && second.empty()) result = first; // Если же второе слово передано а первое нет else if(first.empty() && !second.empty()) result = second; // Иначе выводим эталонное слово else result = etalon; } // Выводим результат return move(result); }; // Результат поиска слов pair <wstring, wstring> res1, res2; // Выполняем поиск слова методом перебора const wstring & word = this->find(etalon, true); // Если слово найдено, выполняем поиск слов if(!word.empty()) res1 = findSecond(etalon, word); // Если первое слово не равно второму if(!first.empty() && (word.compare(first) != 0)){ // Выполняем поиск слов res2 = findSecond(etalon, first); // Если в результате первого поиска не найдено второе слово то выводим второй вариант if(res1.second.empty()) result = getResult(etalon, res2.first, res2.second); // Если же второе слово найдено тогда сравниваем результаты else { // Определяем схожесть первого результата const bool similarity1 = this->alphabet->similarity(etalon, res1.first + res1.second); // Определяем схожесть второго результата const bool similarity2 = this->alphabet->similarity(etalon, res2.first + res2.second); // Если первый вариант совпадает if(similarity1) result = getResult(etalon, res1.first, res1.second); // Если второй вариант совпадает else if(similarity2) result = getResult(etalon, res2.first, res2.second); // Если ни один из вариантов не совпадает else { // Объявляем объект дистанции Левенштейна LD ld; // Выполняем сравнение первого результата const size_t distance1 = ld.distance(etalon, res1.first + res1.second); // Выполняем сравнение второго результата const size_t distance2 = ld.distance(etalon, res2.first + res2.second); // Если первое слово больше подходит if(distance1 < distance2) result = getResult(etalon, res1.first, res1.second); // Иначе запоминаем второй вариант else result = getResult(etalon, res2.first, res2.second); } } // Если варианты равны тогда запоминаем первый результат } else result = getResult(etalon, res1.first, res1.second); } // Выводим результат return move(result); } /** * bruteNotSpace Метод разделения текста на слова * @param text текст для разбора * @return слово полученное при разборе */ const pair <wstring, wstring> morph::DPA::bruteNotSpace(const wstring & text){ // Результат работы функции pair <wstring, wstring> result; // Если текст передан if(!text.empty() && (text.size() > 2) && this->checkLevel(OPT_UNIONTRUE)){ /** * getWords Прототип функции получения списка слов из текста * @param text текст для обработки * @return список слов полученных из текста */ function <list <wstring> (const wstring &)> getWords; /** * getWords Функция получения списка слов из текста * @param text текст для обработки * @return список слов полученных из текста */ getWords = [&getWords, this](const wstring & text){ // Результат работы функции list <wstring> result; // Если текст передан if(!text.empty()){ // Получаем временное слово wstring letters = text; // Получаем размер текста const size_t size = letters.length(); // Если количество букв больше 3 if(size > 2){ // Список вариантов list <wstring> variants; // Первое и второе слово wstring first = L"", second = L""; // Переходим по всем буквам слова for(u_int i = 1; i < size - 1; i++){ // Очищаем список вариантов variants.clear(); // Получаем букву в виде UTF-8 const wstring & letter = letters.substr(i, 1); // Заменяем букву на пробел letters.replace(i, 1, letter + L" "); // Выполняем разделение на два элемента this->alphabet->split(letters, L" ", variants); // Заменяем букву обратно letters.replace(i, 2, letter); // Если список существует if(!variants.empty()){ // Если первое слово не определено if(first.empty()){ // Первое слово first = variants.front(); // Второе слово second = variants.back(); // Выполняем проверку существования первого слова const bool checkFirst = this->check(first); // Выполняем проверку существования второго слова const bool checkSecond = this->check(second); // Если оба слова найдены if(checkFirst && checkSecond && (second.length() > 1)){ // Добавляем первое слово result.push_back(move(first)); // Добавляем второе слово result.push_back(move(second)); // Выходим из цикла break; // Стираем первое слово если не найдено } else if(!checkFirst) first = L""; // Если первое слово уже найдено } else { // Первое слово const wstring & word = variants.front(); // Выполняем проверку существования первого слова if((word.length() > first.length()) && this->check(word)) first = word; // Если слово не найдено тогда продолжаем if(i == (size - 2)){ // Получаем размер первого слова const size_t length = first.length(); // Получаем второе слово second = letters.substr(length, size - length); // Если второе слово найдено тогда добавляем оба слова в список if(this->check(second)){ // Добавляем в список первое слово result.push_back(move(first)); // Добавляем второе слово result.push_back(move(second)); // Если второе слово не найдено то продолжаем поиск } else { // Добавляем в список первое слово result.push_back(move(first)); // Выполняем поиск остальных слов auto words = getWords(second); // Если слова получены if(!words.empty()) result.insert(result.end(), words.begin(), words.end()); } } } } } } } // Выводим результат return move(result); }; // Запрашиваем список слов из текста auto words = getWords(text); // Если слова переданы if(!words.empty()){ // Итоговое слово wstring word1 = L"", word2 = words.front(); // Собираем итоговое слово for(auto it = words.cbegin(); it != words.cend(); ++it){ // Собираем первое слово для сравнения word1.append(* it); // Если это не первое слово if(it != words.cbegin()){ // Если это не конец то добавляем пробелы word2.append(L" "); // Собираем второе слово word2.append(* it); } } // Если итоговое слово соответствует тогда выводим результат if(word1.compare(text) == 0) // Создаем результат с полученным словом result = make_pair(words.front(), move(word2)); // Создаем результат только с первым словом else result = make_pair(words.front(), L""); } } // Выводим результат return move(result); } /** * bruteSpace Метод проверки разделенных слов * @param text текст для обработки * @return список обнаруженных слов */ const unordered_map <wstring, morph::DPA::Rdata> morph::DPA::bruteSpace(const wstring & text){ // Результат работы функции unordered_map <wstring, Rdata> result; // Если слово передано if(!text.empty() && (text.size() > 2) && this->checkLevel(OPT_CHECKSPACES)){ // Ищем в тексте пробел const size_t pos = text.find(L" "); // Если буква в слове найдена if(pos != wstring::npos){ // Результат поиска bool find = false; // Получаем текст wstring str = text; // Выполняем очистку текста this->alphabet->clearBadChar(str); // Получаем временное слово wstring text = this->alphabet->replace(str, L"\n", L" "), wtext = str; // Позиция пробела size_t space = 0, offset = 0; // Получаем длину символов в слове const size_t size = text.length(); /** * check Функция проверки данных текста * @param word слово для обработки * @param pos начальная позиция текста * @param len длина текста */ auto check = [&result, &wtext, this](const wstring & text, const size_t pos, const size_t len){ // Если данные переданы верные if(len > 1){ // Список вариантов list <wstring> variants; // Получаем временное слово const wstring & word = text.substr(pos, len); // Выполняем разделение на два элемента this->alphabet->split(word, L" ", variants); // Если варианты найдены if(!variants.empty()){ // Получаем первое слово const wstring & first = variants.front(); // Получаем второе слово const wstring & second = variants.back(); // Если какое-то из слов не существует if(!this->check(first) || !this->check(second)){ // Получаем слово для проверки const wstring & tmp = (first + second); // Если слово найдено if(this->check(tmp)){ // Регистр второго слова const bool iscase = this->alphabet->isCase(tmp); // Выполняем удаление слов из текста wtext = this->alphabet->replace(wtext, word); // Запоминаем найденное слово result.insert({move(word), {iscase, {move(tmp)}}}); } } } } }; // Переходим по всем буквам слова for(u_int i = 0; i < size; i++){ // Получаем букву в виде UTF-8 const wstring letter = text.substr(i, 1); // Получаем длину слова const size_t length = ((i - offset) + ((i == (size - 1)) ? 1 : 0)); // Если это пробел, удаляем его if((letter.compare(L" ") == 0) || (i == (size - 1))){ // Если слово не найдено if(!find){ // Если смещение установлено if(offset > 0) check(text, offset, length); // Запоминаем что слово найдено find = true; // Если слово найдено } else { // Выполняем проверку слова check(text, offset, length); // Обнуляем результат поиска find = false; } // Запоминаем смещение offset = (space > 0 ? space + 1 : space); // Запоминаем позицию пробела space = i; } } } } // Выводим результат return move(result); } /** * checkSpace Метод проверки слова на наличие пробела * @param word текст для обработки * @return список обнаруженных вариантов слов */ const list <wstring> morph::DPA::checkSpace(const wstring & word){ // Результат работы функции list <wstring> result; // Если слово передано if(!word.empty() && (word.size() > 2) && this->checkLevel(OPT_UNIONTRUE)){ // Выполняем очистку символов wstring etalon = word; // Получаем размер текста const size_t size = etalon.length(); // Если количество букв больше 3 if(size > 2){ // Список вариантов list <wstring> variants; // Первое и второе слово wstring first = L"", second = L""; // Переходим по всем буквам слова for(u_int i = 0; i < size - 1; i++){ // Очищаем список вариантов variants.clear(); // Получаем букву в виде UTF-8 const wstring & letter = etalon.substr(i, 1); // Заменяем букву на пробел etalon.replace(i, 1, letter + L" "); // Выполняем разделение на два элемента this->alphabet->split(etalon, L" ", variants); // Заменяем букву обратно etalon.replace(i, 2, letter); // Если список существует if(!variants.empty()){ // Получаем первое слово first = variants.front(); // Получаем второе слово second = variants.back(); // Если оба слова найдены if(this->check(first) && this->check(second)){ // Если второе слово больше 1-й буквы if((second.length() > 1) && !this->check(first + second)){ // Создаем фразу wstring word = first; // Добавляем пробел word.append(L" "); // Добавляем второе слово word.append(second); // Добавляем найденные варианты слов в список result.push_back(word); } } } } } } // Выводим результат return move(result); } /** * bruteForce Метод поиска вариантов слова методом перебора * @param word слово для поиска * @param limit количество вариантов * @return найденные варианты слов */ const list <wstring> morph::DPA::bruteForce(const wstring & word, const u_int limit){ // Результат работы функции list <wstring> result; // Если слово передано if(!word.empty() && (word.length() > 1) && this->checkLevel(OPT_ONELETTER)){ // Смещение в слове int offset = 0; // Копируем слово wstring tmp = word; // Определяем длину слова const size_t size = tmp.length(), max = (limit < 100 ? (limit > 0 ? limit : 1) : 100); /** * trust Функция проверки на соотвествие подобранной фразы * @param word слово для проверки * @param offset номер буквы для перебора */ auto trust = [&result, &max, this](const wstring & word, const size_t offset){ // Результат проверки bool check = false; // Если слово передано if(!word.empty()){ // Копируем слово wstring tmp = word; // Переходим по всему алфавиту for(auto it = this->alphabet->cbegin(); it != this->alphabet->cend(); ++it){ // Получаем идентификатор буквы const wstring & letter = this->alphabet->lidToLetter(* it); // Заменяем букву tmp.replace(offset, 1, letter); // Если слово найдено тогда добавляем найденный результат в список if(this->check(tmp)){ // Если лимит результатов еще не превышен if(result.size() < max) result.push_back(tmp); // Если же лимит превышен else { // Сообщаем что лимит превышен check = true; // Выходим из цикла break; } } } } // Выводим результат return move(check); }; // Выполняем поиск фразы while(true){ // Выполняем проверку на совпадение слова if(trust(tmp, offset)) break; // Иначе продолжаем поиск else { // Копируем слово заново tmp = word; // Выполняем смещение offset++; // Если все возможные варианты перебрали или слово найдено, выходим if(offset > (size - 1)) break; } } // Если размер больше лимита тогда удаляем лишние слова if(result.size() > max){ // Получаем начало итератора auto it = result.begin(); // Выполняем смещение итератора на нужную позицию for(size_t i = 0; i < max; i++) it++; // Выполняем удаление лишних элементов в списке result.erase(it, result.end()); } } // Выводим результат return move(result); } /** * brutePicking Метод поиска слова методом подстановки * @param word слово для поиска * @param depth глубина поиска * @return искомое слово */ const list <wstring> morph::DPA::brutePicking(const wstring & word, const u_int limit, const size_t depth){ // Результат работы функции list <wstring> result; // Если слово передано if(!word.empty() && (word.length() > 1) && this->checkLevel(OPT_SEVERALLETTER)){ // Смещение в слове int offset = 0; // Копируем слово wstring tmp = word; // Определяем длину слова const size_t size = word.length(), max = (limit < 100 ? (limit > 0 ? limit : 1) : 100); // Выполняем поиск фразы while(true){ // Если лимит не достигнут if(result.size() < max){ // Переходим по всему алфавиту for(auto it = this->alphabet->cbegin(); it != this->alphabet->cend(); ++it){ // Список слов для поиска list <wstring> words; // Получаем идентификатор буквы const wstring & letter = this->alphabet->lidToLetter(* it); // Заменяем букву tmp.replace(offset, 1, letter); // Выполняем поиск слова this->get(tmp, words, depth); // Если варианты найдены if(!words.empty()) result.insert(result.end(), words.begin(), words.end()); } // Копируем слово заново tmp = word; // Выполняем смещение offset++; // Если все возможные варианты перебрали или слово найдено, выходим if(offset > (size - 1)) break; // Выходим из цикла } else break; } // Если размер больше лимита тогда удаляем лишние слова if(result.size() > max){ // Получаем начало итератора auto it = result.begin(); // Выполняем смещение итератора на нужную позицию for(size_t i = 0; i < max; i++) it++; // Выполняем удаление лишних элементов в списке result.erase(it, result.end()); } // Выполняем сортировку списка result.sort(); // Удаляем все повторяющиеся элементы в списке result.erase(unique(result.begin(), result.end()), result.end()); } // Выводим результат return move(result); } /** * getBlock Метод получения бинарного блока слов из списка слов * @param letter буква на которую нужно получить бинарный блок данных * @param список слов из которых нужно получить бинарный блок * @return бинарный блок данных */ const vector <char> morph::DPA::getBlock(const wstring & letter, const vector <string> & words){ // Результат работы функции vector <char> result; // Если буква передана if(!letter.empty() && !words.empty()){ // Если список получен if(!words.empty()){ // Объявляем модуль работы с файловой системой Df df; // Данные всех слов vector <char> data; // Размеры всех слов vector <size_t> sizes; // Получаем количество слов const size_t count = words.size(); // Выполняем получение идентификатора буквы const u_int lid = this->alphabet->letterToLid(this->alphabet->toLower(letter)); // Получаем размеры каждого слова for(auto it = words.cbegin(); it != words.cend(); ++it){ // Получаем слово const string & str = (* it); // Получаем размер слова const size_t size = str.size(); // Получаем данные слова const char * word = str.data(); // Заполняем список данных data.insert(data.end(), word, word + size); // Заполняем список размеров sizes.push_back(size); } // Получаем бинарные данные идентификатора буквы const char * clid = reinterpret_cast <const char *> (&lid); // Получаем бинарные данные количества слов const char * ccount = reinterpret_cast <const char *> (&count); // Добавляем в результирующий массив идентификатор буквы result.insert(result.end(), clid, clid + sizeof(lid)); // Добавляем в результирующий массив количество букв result.insert(result.end(), ccount, ccount + sizeof(count)); // Переходим по всем размерам блока for(size_t i = 0; i < sizes.size(); i++){ // Получаем размер блока const char * size = reinterpret_cast <const char *> (&sizes[i]); // Добавляем в буфер размеры блоков result.insert(result.end(), size, size + sizeof(size_t)); } // Добавляем в результирующий массив - все данные слов result.insert(result.end(), data.begin(), data.end()); // Выполняем сжатие блока данных result = df.compress(result); // Очищаем данные слов vector <char> ().swap(data); // Очищаем размеры всех слов vector <size_t> ().swap(sizes); } } // Выводим результат return move(result); } /** * getBlock Метод получения бинарного блока слов из базы данных * @param letter буква на которую нужно получить бинарный блок данных * @return бинарный блок данных */ const vector <char> morph::DPA::getBlock(const wstring & letter){ // Результат работы функции vector <char> result; // Если буква передана if(!letter.empty()){ // Объявляем модуль работы с файловой системой Df df; // Список слов list <wstring> words; // Запрашиваем список слов this->get(letter, words, 0, 0); // Если список получен if(!words.empty()){ // Данные всех слов vector <char> data; // Размеры всех слов vector <size_t> sizes; // Получаем количество слов const size_t count = words.size(); // Выполняем получение идентификатора буквы const u_int lid = this->alphabet->letterToLid(this->alphabet->toLower(letter)); // Получаем размеры каждого слова for(auto it = words.cbegin(); it != words.cend(); ++it){ // Получаем слово const string & str = this->alphabet->toString(* it); // Получаем размер слова const size_t size = str.size(); // Получаем данные слова const char * word = str.data(); // Заполняем список данных data.insert(data.end(), word, word + size); // Заполняем список размеров sizes.push_back(size); } // Получаем бинарные данные идентификатора буквы const char * clid = reinterpret_cast <const char *> (&lid); // Получаем бинарные данные количества слов const char * ccount = reinterpret_cast <const char *> (&count); // Добавляем в результирующий массив идентификатор буквы result.insert(result.end(), clid, clid + sizeof(lid)); // Добавляем в результирующий массив количество букв result.insert(result.end(), ccount, ccount + sizeof(count)); // Переходим по всем размерам блока for(size_t i = 0; i < sizes.size(); i++){ // Получаем размер блока const char * size = reinterpret_cast <const char *> (&sizes[i]); // Добавляем в буфер размеры блоков result.insert(result.end(), size, size + sizeof(size_t)); } // Добавляем в результирующий массив - все данные слов result.insert(result.end(), data.begin(), data.end()); // Выполняем сжатие блока данных result = df.compress(result); // Очищаем данные слов vector <char> ().swap(data); // Очищаем размеры всех слов vector <size_t> ().swap(sizes); } } // Выводим результат return move(result); } /** * split Метод разделения текст на слова * @param text текст для разделения * @return список слов */ const list <wstring> morph::DPA::split(const wstring & text) const { // Результат работы функции list <wstring> result; // Если текст передан if(!text.empty()){ // Список слов list <wstring> row, col; // Получаем текст wstring str = text; // Выполняем очистку текста this->alphabet->clearBadChar(str); // Разбиваем слова на строки this->alphabet->split(str, L"\n", row); // Если список получен if(!row.empty()){ // Переходим по всем строкам for(auto it = row.cbegin(); it != row.cend(); ++it){ // Очищаем список слов col.clear(); // Разбиваем слова на слова this->alphabet->split(* it, L" ", col); // Если список получен if(!col.empty()) result.insert(result.end(), col.begin(), col.end()); } } } // Выводим результат return move(result); } /** * search Метод поиска наиболее подходящих слов * @param word слово для поиска * @param limit количество вариантов на слово с ошибкой * @return список найденных вариантов */ const list <wstring> morph::DPA::search(const wstring & word, const u_int limit){ // Результат работы функции list <wstring> result; // Если слово передано if(!word.empty() && (word.length() > 1) && this->checkLevel(OPT_SEVERALLETTER)){ // Длина слова const size_t max = (limit < 100 ? (limit > 0 ? limit : 1) : 100); // Выполняем поиск слова методом перебора result = this->find(word, max, true); // Если слово найдено if(!result.empty()){ // Список вариантов слов list <wstring> words; /** * add Функция добавления результатов в список вариантов * @param word1 первая часть слова * @param word2 вторая часть слова * @param etalon исходное эталонное слово */ auto add = [&words, this](const wstring & word1, const wstring & word2, const wstring etalon){ // Если все данные переданы if(!word1.empty() && !word2.empty() && !etalon.empty()){ // Формируем результат wstring result = word1; // Добавляем пробел result.append(L" "); // Добавляем второе слово result.append(word2); // Если текст найден тогда добавляем в список if(this->alphabet->similarity(word1 + word2, etalon)) words.push_back(result); // Иначе определяем с помощью дистанции Левенштейна else { // Объект дистанции Левенштейна LD ld; // Определяем дистанцию const size_t distance = ld.distance(word1 + word2, etalon); // Если дистанция минимальная if(float(distance) <= (float(etalon.length()) / 2.5)) words.push_back(result); } } }; // Переходим по всему списку вариантов for(auto it = result.cbegin(); it != result.cend(); ++it){ // Получаем размер слова const size_t size = it->length(); // Если длина эталонного слова на много больше if(word.length() > size){ // Получаем второе слово wstring second = word; // Получаем последнюю часть слова second.replace(0, size, L""); // Выполняем поиск второго слова auto seconds = this->find(second, max, true); // Если слова получены if(!seconds.empty()){ // Переходим по всему списку вариантов for(auto jt = seconds.cbegin(); jt != seconds.cend(); ++jt){ // Формируем вариант слова if(words.size() < 5) add(* it, * jt, word); // Иначе выходим из цикла else break; } // Добавляем слово так как оно есть } else words.push_back(* it); // Добавляем слово так как оно есть } else words.push_back(* it); } // Если список слов не пустой тогда заменяем им предыдущий результат if(!words.empty()) result = words; } } // Выводим результат return move(result); } /** * find Метод поиска подходящего слова * @param word слово для поиска * @param limit количество вариантов на слово с ошибкой * @param brute выполнять предварительную проверку перебором вариантов * @return результат работы функции */ const list <wstring> morph::DPA::find(const wstring & word, const u_int limit, const bool brute){ // Результат работы функции list <wstring> result; // Если слово передано if(!word.empty() && (word.length() > 1) && this->checkLevel(OPT_SEVERALLETTER)){ // Выполняем поиск перебором if(brute) result = this->bruteForce(word, limit); // Если результат не получен if(result.empty()){ // Запоминаем слово wstring tmp = word; // Длина слова const size_t size = tmp.length(), max = (limit < 100 ? (limit > 0 ? limit : 1) : 100); // Смещение в тексте size_t offset = size; // Выполняем поиск оставшихся символов while(offset > 0){ // Уменьшаем смещение offset--; // Выполняем получение оставшегося текста tmp = tmp.substr(0, offset); // Если слово пустое тогд выходим if(!tmp.empty()){ // Если лимит по словам не достигнут if(result.size() < max){ // Выполняем проверку существует ли слово в базе if(this->check(tmp)) result.push_back(tmp); // Если слово в базе не найдено else { // Получаем размер глубины const size_t depth = ((size + 1) - offset); // Получаем список слов auto words = this->brutePicking(tmp, max, depth); // Если слова получены if(!words.empty()) result.insert(result.end(), words.begin(), words.end()); } // Выходим из цикла } else break; // Выходим из цикла } else break; } // Если размер больше лимита тогда удаляем лишние слова if(result.size() > max){ // Получаем начало итератора auto it = result.begin(); // Выполняем смещение итератора на нужную позицию for(size_t i = 0; i < max; i++) it++; // Выполняем удаление лишних элементов в списке result.erase(it, result.end()); } // Выполняем сортировку списка result.sort(); // Удаляем все повторяющиеся элементы в списке result.erase(unique(result.begin(), result.end()), result.end()); } } // Выводим результат return move(result); } /** * revalt Метод подстановку альтернативной буквы * @param word слово для корректировки */ void morph::DPA::revalt(wstring & word){ // Если текст передан if(!word.empty() && this->checkLevel(OPT_ALTERNATIVE)){ // Получаем текст для обработки const wstring & text = word; // Переходим по всем буквам for(size_t i = 0; i < text.length(); i++){ // Получаем строку const wstring & letter = text.substr(i, 1); // Если для буквы существует альтернативная буква if(this->alphabet->isAlternative(letter)){ // Получаем временное слово wstring result = text; // Получаем альтернативную букву const wstring & alternative = this->alphabet->getAlternative(letter); // Выполняем замену буквы в тексте result.replace(i, 1, alternative); // Если слово найдено if(this->check(result)){ // Запоминаем полученное слово word = result; // Выходим из цикла break; } } } } } /** * setId Метод установки идентификатора словаря * @param id идентификатор словаря */ void morph::DPA::setId(const wstring & id){ // Если идентификатор передан, сохраняем его if(!id.empty()) this->id = id; } /** * clause Метод добавления целых предложений (слова должны быть истинными) * @param clause текст на русском языке (не отформатированный) */ void morph::DPA::clause(const wstring & clause){ // Если предложение передано if(!clause.empty()){ // Выполняем копирование текста wstring wtext = clause; // Выполняем очистку текста this->alphabet->clearBadChar(wtext); // Разделяем текст на слова auto words = this->split(wtext); // Если слова получены if(!words.empty()){ // Переходим по всему списку for(auto it = words.cbegin(); it != words.cend(); ++it){ // Добавляем слово и обнуляем старое слово if(!it->empty()) this->set(* it); } } } } /** * del Метод удаления слова * @param word слово для удаления */ void morph::DPA::del(const wstring & word){ // Если слово передано if(!word.empty()){ // Получаем копию слова const wstring & wword = word; // Переводим букву в нижний регистр const wstring & letter = this->alphabet->toLower(wword.substr(0, 1)); // Получаем идентификатор буквы const u_int lid = this->alphabet->letterToLid(letter); // Извлекаем данные буквы if(this->letters.count(lid) > 0){ // Выполняем поиск auto obj = this->letters.find(lid); // Удаляем слово obj->second->deleteWords(wword); } } } /** * set Метод вставки слова * @param word слово для вставки */ void morph::DPA::set(const wstring & word){ // Если слово передано if(!word.empty()){ // Получаем копию слова const wstring & wword = trim(word); // Выполняем поиск пробела const size_t pos = wword.find(L" "); // Если пробел не найден, продолжаем if(pos == wstring::npos){ // Переводим букву в нижний регистр const wstring & letter = this->alphabet->toLower(wword.substr(0, 1)); // Получаем идентификатор буквы const u_int lid = this->alphabet->letterToLid(letter); // Извлекаем данные буквы if(this->letters.count(lid) > 0){ // Выполняем поиск auto obj = this->letters.find(lid); // Устанавливаем корректор в каждой букве if(this->checkLevel(OPT_ALTERNATIVE)) obj->second->setAlternative(); // Добавляем новое слово obj->second->addWord(wword); // Если буква не найдено то создаем новую } else { try { // Выделяем память под объект Stk * stk = new Stk(this->alphabet); // Устанавливаем корректор в каждой букве if(this->checkLevel(OPT_ALTERNATIVE)) stk->setAlternative(); // Добавляем новое слово stk->addWord(wword); // Добавляем в список букв структуры данных this->letters.insert({move(lid), move(stk)}); // Если происходит ошибка то игнорируем её } catch(const bad_alloc&) {} } // Если корректировка альтернативной буквы включена if(this->checkLevel(OPT_ALTERNATIVE)){ // Создаем альтернативное слово wstring tmp = wword; // Переходим по всему тексту for(size_t i = 0; i < tmp.length(); i++){ // Получаем альтернативную букву const wstring & letter = tmp.substr(i, 1); // Получаем реальную букву const wstring & real = this->alphabet->getRealLetter(letter); // Если реальная буква получена то заменяем её на альтернативную if(!real.empty()){ // Выполняем замену быкву tmp.replace(i, 1, real); // Добавляем исправленное слово this->set(tmp); // Заменяем слово исходным tmp = wword; } } } } } } /** * get Метод чтения слова * @param word слово для поиска * @param words список результат поиска * @param offset дистанция поиска (количество букв которые отличаются) * @param limit максимальное количество слов для отдачи */ void morph::DPA::get(const wstring & word, list <wstring> & words, const u_short offset, const size_t limit){ // Если слово передано if(!word.empty()){ // Получаем копию слова const wstring & wword = word; // Переводим букву в нижний регистр const wstring & letter = this->alphabet->toLower(wword.substr(0, 1)); // Получаем идентификатор буквы const u_int lid = this->alphabet->letterToLid(letter); // Извлекаем данные буквы if(this->letters.count(lid) > 0){ // Выполняем поиск auto obj = this->letters.find(lid); // Ищем слова auto result = obj->second->findWords(wword, offset, limit, this); // Если результат получен тогда формируем результат if(!result.empty()){ // Переходим по всему списку и формируем другой список слов for(auto it = result.cbegin(); it != result.cend(); ++it){ // Добавляем в список найденные слова words.push_back(* it); } } } } } /** * alternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void morph::DPA::alternative(const wstring & letter, const wstring & alternative){ // Если данные переданы if(!letter.empty() && !alternative.empty()){ // Добавляем альтернативную букву в алфавит this->alphabet->addAlternative(letter, alternative); } } /** * setBlock Метод добавления блока слов в базу данных * @param frame блок слов в бинарном виде * @param info информировать о добавлении слов */ void morph::DPA::setBlock(const vector <char> * frame, const bool info){ // Если блок передан if(frame != nullptr){ // Объявляем модуль работы с файловой системой Df df; // Размеры всех слов vector <size_t> sizes; // Идентификатор буквы u_int lid = 0; // Смещение в буфере size_t count = 0, offset = 0, length = 0; // Выполняем декомпрессию буфера данных auto data = df.decompress(* frame); // Получаем размер данных const size_t size = data.size(); // Получаем буфер данных const char * buffer = data.data(); // Получаем размер данных length = sizeof(lid); // Получаем идентификатор буквы memcpy(&lid, buffer + offset, length); // Запоминаем смещение offset += length; // Получаем размер данных length = sizeof(count); // Получаем количество слов в блоке memcpy(&count, buffer + offset, length); // Запоминаем смещение offset += length; // Смещение в буфере размеров блоков size_t i = count; // Получаем размер данных length = sizeof(size); // Переходим по всем блокам размеров while(i > 0){ // Размер блока size_t size = 0; // Копируем размер блока memcpy(&size, buffer + offset, length); // Добавляем в массив размер блока sizes.push_back(size); // Запоминаем смещение offset += length; // Уменьшаем внутреннее смещение i--; } // Переходим по всему списку размеров for(auto it = sizes.cbegin(); it != sizes.cend(); ++it){ // Буфер слова char word[256]; // Заполняем буфер слова memset(word, 0, sizeof(word)); // Получаем размер слова const size_t wsize = (* it); // Выполняем копирование слова в буфер memcpy(word, buffer + offset, wsize); // Запоминаем смещение offset += wsize; // Если нужно отобразить список загруженных слов if(info) printf("Добавление слова: %s\r\n", word); // Добавляем слово в базу this->set(word); } } } /** * correct Метод корректировки текста * @param text текст для корректировки * @param info список слов для которых выполнена коррекция */ void morph::DPA::correct(wstring & text, list <pair <wstring, wstring>> * info){ // Если текст передан if(!text.empty()){ // Получаем копию текста wstring wtext = text, wntext; // Очищаем текст от символа возврата каретки wtext = this->alphabet->replace(wtext, L"\r"); // Текст после обработки wntext = wtext; /** * restoreText Функция установки полученного текста * @param words список слов для корректировки */ auto restoreText = [&wtext, &wntext, &text, info, this](const unordered_map <wstring, Rdata> & words){ // Если список получен if(!words.empty()){ // Переходим по всему списку for(auto it = words.cbegin(); it != words.cend(); ++it){ // Копируем слово wstring word = this->alphabet->toLower(it->second.words.front()); // Удаляем из текста исправленные слова wntext = this->alphabet->replace(wntext, it->first); // Выполняем корректировку слова this->revalt(word); // Если нужно перевести символ в верхний регистр if(it->second.icase) this->alphabet->uppLetterWord(word); // Выполняем замену слов в тексте wtext = this->alphabet->replace(wtext, it->first, word); // Если требуется вывести информацию о замене if((info != nullptr) && (this->alphabet->toLower(it->first) .compare(this->alphabet->toLower(word)) != 0)){ // Запоминаем первое слово wstring first = it->first; // Если нужно перевести символ в верхний регистр if(it->second.icase) this->alphabet->uppLetterWord(first); // Добавляем текст в информационный список info->push_back({first, word}); } } } }; // Выполняем проверку на корректность пробелов auto result = this->bruteSpace(wtext); // Выполняем корректировку текста restoreText(result); // Разделяем текст на слова auto words = this->split(wntext); // Если слова получены if(!words.empty()){ // Очищаем список слов result.clear(); // Переходим по всему списку for(auto it = words.cbegin(); it != words.cend(); ++it){ // Выполняем очистку символов wstring etalon = (* it); // Выполняем очистку текста this->alphabet->clearBadChar(etalon); // Добавляем слово и обнуляем старое слово if(!etalon.empty()){ // Результирующее слово wstring word = L""; // Регистр первой буквы const bool iscase = this->alphabet->isCase(etalon); // Переводим в нижний регистр слово для поиска etalon = this->alphabet->toLower(etalon); // Если слово не найдено if(!this->check(etalon)){ // Выполняем поиск перебором дефизов word = this->bruteHyphen(etalon); // Если слово не найдено if(word.empty()){ // Выполняем поиск перебором word = this->bruteForce(etalon); // Если слово не найдено if(word.empty()){ // Получаем слово из эталонного auto space = this->bruteNotSpace(etalon); // Получаем второе слово word = space.second; // Если слово не найдено if(word.empty()) word = this->search(etalon, space.first); } } // Если слово не найдено if(word.empty()) word = etalon; // Иначе просто корректируем слово } else word = etalon; // Добавляем результирующее слово result.insert({etalon, {iscase, {word}}}); } } // Выполняем корректировку текста restoreText(result); // Выводим результат text = wtext; } } } /** * analyze Метод проведения анализа текста * @param text текст для проведения анализа * @param limit количество вариантов на слово с ошибкой * @param info список слов для которых выполнена коррекция */ void morph::DPA::analyze(const wstring & text, const u_int limit, list <pair <wstring, list <wstring>>> * info){ // Если текст передан if(!text.empty() && (limit > 0) && (info != nullptr)){ // Определяем длину слова const size_t max = (limit < 100 ? (limit > 0 ? limit : 1) : 100); // Получаем копию текста wstring wtext = text, wntext; // Очищаем текст от символа возврата каретки wtext = this->alphabet->replace(wtext, L"\r"); // Текст после обработки wntext = wtext; /** * restoreText Функция установки полученного текста * @param words список слов для корректировки */ auto restoreText = [&wtext, &wntext, &text, &max, info, this](const unordered_map <wstring, Rdata> & words){ // Если список получен if(!words.empty()){ // Переходим по всему списку for(auto it = words.cbegin(); it != words.cend(); ++it){ // Список слов list <wstring> words = it->second.words; // Удаляем из текста исправленные слова wntext = this->alphabet->replace(wntext, it->first); // Переходим по всему списку слов for(auto jt = words.begin(); jt != words.end(); ++jt){ // Переводим слово в нижний регистр * jt = this->alphabet->toLower(* jt); // Если количество вариантов меньше лимита if(words.size() < max){ // Запоминаем слово wstring word = (* jt); // Выполняем корректировку слова this->revalt(word); // Если слово изменилось тогда добавляем в список if(jt->compare(word) != 0){ // Если нужно перевести символ в верхний регистр if(it->second.icase) this->alphabet->uppLetterWord(word); // Добавляем в список новое слово * jt = word; // Если нужно перевести символ в верхний регистр } else if(it->second.icase) this->alphabet->uppLetterWord(* jt); // Если нужно перевести символ в верхний регистр } else if(it->second.icase) this->alphabet->uppLetterWord(* jt); } // Если требуется вывести информацию о замене if(this->alphabet->toLower(it->first) .compare(this->alphabet->toLower(words.front())) != 0){ // Запоминаем первое слово wstring word = it->first; // Если нужно перевести символ в верхний регистр if(it->second.icase) this->alphabet->uppLetterWord(word); // Удаляем все повторяющиеся элементы в списке words.erase(unique(words.begin(), words.end()), words.end()); // Выполняем сортировку списка words.sort([](const wstring & first, const wstring & second){ // Выполняем сортировку по размеру return first.size() > second.size(); }); // Если размер больше лимита тогда удаляем лишние слова if(words.size() > max){ // Получаем начало итератора auto it = words.begin(); // Выполняем смещение итератора на нужную позицию for(size_t i = 0; i < max; i++) it++; // Выполняем удаление лишних элементов в списке words.erase(it, words.end()); } // Добавляем текст в информационный список info->push_back({word, words}); } } } }; // Выполняем проверку на корректность пробелов auto result = this->bruteSpace(wtext); // Выполняем корректировку текста restoreText(result); // Разделяем текст на слова auto words = this->split(wntext); // Если слова получены if(!words.empty()){ // Очищаем список слов result.clear(); // Переходим по всему списку for(auto it = words.cbegin(); it != words.cend(); ++it){ // Выполняем очистку символов wstring etalon = (* it); // Выполняем очистку текста this->alphabet->clearBadChar(etalon); // Добавляем слово и обнуляем старое слово if(!etalon.empty()){ // Список вариантов слов list <wstring> words; // Регистр первой буквы const bool iscase = this->alphabet->isCase(etalon); // Переводим в нижний регистр слово для поиска etalon = this->alphabet->toLower(etalon); // Если слово не найдено if(!this->check(etalon)){ // Выполняем поиск перебором дефизов wstring word = this->bruteHyphen(etalon); // Если слово не найдено if(word.empty()){ // Выполняем поиск перебором words = this->bruteForce(etalon, max); // Если слово не найдено if(words.empty()){ // Получаем слово из эталонного auto space = this->bruteNotSpace(etalon); // Получаем второе слово word = space.second; // Если слово не найдено if(word.empty()) words = this->search(etalon, max); // Добавляем вариант слова else words.push_back(word); // Если слово найдено, ищем возможность появления в нем пробела } else { // Получаем список вариантов с пробелами auto spaces = this->checkSpace(etalon); // Если спиоск не пустой if(!spaces.empty()) words.insert(words.end(), spaces.begin(), spaces.end()); } // Если слово не найдено if(words.empty()) words.push_back(etalon); // Добавляем вариант слова } else words.push_back(word); // Иначе просто корректируем слово } else words.push_back(etalon); // Добавляем результирующие данные result.insert({etalon, {iscase, words}}); } } // Выполняем корректировку текста restoreText(result); } } } /** * getId Метод получения идентификатора словаря * @return идентификатор словаря */ const string morph::DPA::getId() const { // Выводрим результат return this->alphabet->toString(this->id); } /** * count Метод получения количества потомков * @param word слово для удаления */ const size_t morph::DPA::count(const string word) const { // Результат работы функции size_t result = 0; // Если слово передано if(!word.empty()) result = this->count(this->alphabet->toWstring(word)); // Выводим результат return move(result); } /** * check Метод проверки существования слова * @param word слово для проверки * @return результат проверки */ const bool morph::DPA::check(const string word) const { // Результат проверки bool result = false; // Если слово передано if(!word.empty()) result = this->check(this->alphabet->toWstring(word)); // Выводим результат return move(result); } /** * test Метод проверки текста на соответствие словарю * @param text текст для проверки * @return результат проверки */ const bool morph::DPA::test(const string & text) const { // Результат работы функции bool result = false; // Если текст передан if(!text.empty()) result = this->test(this->alphabet->toWstring(text)); // Выводим результат return move(result); } /** * setId Метод установки идентификатора словаря * @param id идентификатор словаря */ void morph::DPA::setId(const string id){ // Если идентификатор передан то устанавливаем его if(!id.empty()) this->setId(this->alphabet->toWstring(id)); } /** * clause Метод добавления целых предложений (слова должны быть истинными) * @param clause текст на русском языке (не отформатированный) */ void morph::DPA::clause(const string clause){ // Если предложение передано if(!clause.empty()) this->clause(this->alphabet->toWstring(clause)); } /** * del Метод удаления слова * @param word слово для удаления */ void morph::DPA::del(const string word){ // Если слово передано if(!word.empty()) this->del(this->alphabet->toWstring(word)); } /** * set Метод вставки слова * @param word слово для вставки */ void morph::DPA::set(const string word){ // Если слово передано if(!word.empty()) this->set(this->alphabet->toWstring(word)); } /** * get Метод чтения слова * @param word слово для поиска * @param words список результат поиска * @param offset дистанция поиска (количество букв которые отличаются) * @param limit максимальное количество слов для отдачи */ void morph::DPA::get(const string word, list <string> & words, const u_short offset, const size_t limit){ // Если слово передано if(!word.empty()){ // Создаем список для получения вариантов ответа list <wstring> result; // Запрашиваем данные this->get(this->alphabet->toWstring(word), result, offset, limit); // Если список ответа не пустой if(!result.empty()){ // Выполняем конвертацию полученных слов for(auto it = result.cbegin(); it != result.cend(); ++it){ // Добавляем в список полученные слова words.push_back(this->alphabet->toString(* it)); } } } } /** * alternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void morph::DPA::alternative(const string letter, const string alternative){ // Если данные переданы if(!letter.empty() && !alternative.empty()){ // Добавляем альтернативную букву в алфавит this->alternative( this->alphabet->toWstring(letter), this->alphabet->toWstring(alternative) ); } } /** * correct Метод корректировки текста * @param text текст для корректировки * @param info список слов для которых выполнена коррекция */ void morph::DPA::correct(string & text, list <pair <string, string>> * info){ // Если текст передан if(!text.empty() && (text.find("\x9") == string::npos)){ // Получаем копию текста wstring wtext = this->alphabet->toWstring(text); // Создаем объект отладки list <pair <wstring, wstring>> winfo; // Выполняем корректировку текста this->correct(wtext, (info == nullptr ? nullptr : &winfo)); // Если объект с текстом получен if(!winfo.empty()){ // Выполняем переконвертацию for(auto it = winfo.cbegin(); it != winfo.cend(); ++it){ // Добавляем в список переконвертированные данные info->push_back({this->alphabet->toString(it->first), this->alphabet->toString(it->second)}); } } // Выводим результат text = this->alphabet->toString(wtext); } } /** * analyze Метод проведения анализа текста * @param text текст для проведения анализа * @param limit количество вариантов на слово с ошибкой * @param info список слов для которых выполнена коррекция */ void morph::DPA::analyze(const string & text, const u_int limit, list <pair <string, list <string>>> * info){ // Если текст передан if(!text.empty() && (limit > 0) && (text.find("\x9") == string::npos) && (info != nullptr)){ // Получаем копию текста const wstring & wtext = this->alphabet->toWstring(text); // Создаем объект отладки list <pair <wstring, list <wstring>>> winfo; // Выполняем анализирование текста this->analyze(wtext, limit, (info == nullptr ? nullptr : &winfo)); // Если объект с текстом получен if(!winfo.empty()){ // Выполняем переконвертацию for(auto it = winfo.cbegin(); it != winfo.cend(); ++it){ // Создаем список слов list <string> words; // Переходим по всему списку полученных слов for(auto jt = it->second.cbegin(); jt != it->second.cend(); ++jt){ // Заполняем список слов words.push_back(this->alphabet->toString(* jt)); } // Добавляем в список переконвертированные данные info->push_back({this->alphabet->toString(it->first), words}); } } } } /** * read Метод чтения корпуса * @param file файл корпуса без расширения */ void morph::DPA::read(const string file){ // Если путь передан и буквы существуют if(!file.empty()){ // Структура проверка статистики struct stat info; // Создаем имя файла string filename = file; // Добавляем расширение файла filename.append(".dpa"); // Проверяем переданный нам адрес bool isFile = (stat(filename.c_str(), &info) == 0); // Если это файл if(isFile) isFile = ((info.st_mode & S_IFMT) != 0); // Если путь существует if(isFile){ // Объявляем модуль работы с файловой системой Df df; // Буфер данных vector <char> data; // Буфер слова char word[256]; // Смещение в буфере size_t offset = 0, length = 0, count = 0; // Определяем начальное время const time_t start = time(nullptr); // Строка заголовка const char * caption = "Загрузка корпуса русского языка"; // Пишем процент загрузки printf("\r\n\x1B[34m\x1B[1m%s:\x1B[0m \x1B[32m\x1B[1m%u%%\x1B[0m\r\n", caption, 0); // Отображаем оставшиеся знаки загрузки for(u_int i = 0; i < 100; i++) cout << "\x1B[36m\x1B[1m#\x1B[0m"; // Завершаем переход printf("\r\n"); // Выполняем чтение данных из файла df.read(filename, data); // Если буфер не пустой if(!data.empty()){ // Получаем даныне буфера const char * buffer = data.data(); // Получаем размер буфера const size_t size = data.size(); // Размер идентификатора словаря size_t sizeId = 0; // Получаем размер данных length = sizeof(sizeId); // Считываем размер идентификатора словаря memcpy(&sizeId, buffer + offset, length); // Увеличиваем смещение offset += length; // Если размер идентификатора словаря существует if(sizeId > 0){ // Заполняем буфер слова нулями memset(word, 0, sizeof(word)); // Считываем данные идентификатора memcpy(word, buffer + offset, sizeId); // Увеличиваем смещение offset += sizeId; // Устанавливаем идентификатор словаря this->setId(word); } // Количество альтернативных букв size_t sizeAlternative = 0; // Считываем количество альтернативных букв memcpy(&sizeAlternative, buffer + offset, length); // Увеличиваем смещение offset += length; // Если количество альтернативных букв больше 0 if(sizeAlternative > 0){ // Буква и альтернативная буква u_int letter = 0, aletter = 0, ptr = 0; // Запоминаем размер буквы length = sizeof(letter); // Смещение в буфере альтернативных букв size_t i = (sizeAlternative * 2); // Очищаем список альтернативных букв this->alphabet->clearAlternative(); // Считываем альтернативные буквы до тех пор пока все не будут прочитаны while(i > 0){ // Увеличиваем смещение букв ptr++; // Считываем идентификатор буквы if(ptr % 2) memcpy(&letter, buffer + offset, length); // Считываем альтернативный идентификатор буквы else memcpy(&aletter, buffer + offset, length); // Увеличиваем смещение offset += length; // Если обе буквы получены if((letter > 0) && (aletter > 0)){ // Добавляем альтернативные слова в список this->alphabet->addAlternative(this->alphabet->lidToLetter(letter), this->alphabet->lidToLetter(aletter)); // Очищаем обе буквы letter = 0; aletter = 0; } // Уменьшаем внутреннее смещение i--; } } // Получаем размер данных length = sizeof(count); // Считываем количество блоков memcpy(&count, buffer + offset, length); // Увеличиваем смещение offset += length; // Если количество блоков получено if(count > 0){ // Смещение в буфере размеров блоков size_t i = count; // Размер всех блоков vector <size_t> sizes; // Получаем размер данных length = sizeof(sizeId); // Переходим по всем блокам размеров while(i > 0){ // Размер блока size_t size = 0; // Копируем размер блока memcpy(&size, buffer + offset, length); // Добавляем в массив размер блока sizes.push_back(size); // Запоминаем смещение offset += length; // Уменьшаем внутреннее смещение i--; } // Сбрасываем итератор i = 0; // Блок данных vector <char> frame; // Переходим по всем размерам и считываем блоки данных for(auto it = sizes.cbegin(); it != sizes.cend(); ++it){ // Очищаем блок данных frame.clear(); // Размер блока const size_t size = (* it); // Выполняем чтение данных блока frame.insert(frame.end(), buffer + offset, buffer + (offset + size)); // Добавляем блок данных this->setBlock(&frame); // Запоминаем смещение offset += size; // Выполняем смещение i++; // Выполняем расчет процентов const u_int p = u_int(ceil((float(i) / float(count)) * 100)); // Выполняем очистку консоли printf("\033c"); // Пишем процент загрузки printf("\r\n\x1B[34m\x1B[1m%s:\x1B[0m \x1B[32m\x1B[1m%u%%\x1B[0m\r\n", caption, (p <= 100 ? p : 100)); // Отображаем индикатор загрузки for(u_int i = 0; i < p; i++) cout << "\x1B[31m\x1B[1m#\x1B[0m"; // Отображаем оставшиеся знаки загрузки for(u_int i = 0; i < (100 - p); i++) cout << "\x1B[36m\x1B[1m#\x1B[0m"; // Завершаем переход printf("\r\n"); } // Определяем конечное время const time_t end = time(nullptr); // Выводим информацию о времени загрузки printf("\r\nВремя загрузки корпуса: %ld минут\r\n\r\n", ((end - start) / 60)); } } } } } /** * write Метод записи корпуса * @param path адрес где будет хранится файл корпуса */ void morph::DPA::write(const string path){ // Если список слов не пустой if(!path.empty()){ // Объявляем модуль работы с файловой системой Df df; // Структура проверка статистики struct stat info; // Проверяем переданный нам адрес bool isDir = (stat(path.c_str(), &info) == 0); // Если это файл if(isDir) isDir = ((info.st_mode & S_IFDIR) != 0); // Если путь не существует if(!isDir) df.mkdir(path.c_str()); // Получаем идентификатор словаря const string & id = this->getId(); // Адрес файла string filename = path; // Добавляем разделитель filename.append("/"); // Добавляем идентификатор буквы filename.append(id); // Добавляем расширение файла filename.append(".dpa"); // Удаляем файл если существует remove(filename.c_str()); // Размер всех блоков vector <size_t> sizes; // Данные всех слов vector <char> data, buffer; // Получаем размер идентификатора const size_t sizeId = id.size(); // Получаем список альтернативных букв auto alternative = this->alphabet->getAlternatives(); // Получаем количество альтернативных букв const size_t sizeAlternative = alternative.size(); // Переходим по всему списку букв for(auto it = this->alphabet->cbegin(); it != this->alphabet->cend(); ++it){ // Получаем идентификатор буквы const u_int lid = (* it); // Получаем букву const wstring & letter = this->alphabet->lidToLetter(lid); // Если буква получена if(!letter.empty()){ // Запрашиваем блок auto frame = this->getBlock(letter); // Если блок не пустой if(!frame.empty()){ // Запоминаем размер каждого блока sizes.push_back(frame.size()); // Заполняем список данных data.insert(data.end(), frame.begin(), frame.end()); } } } // Получаем количество блоков const size_t count = sizes.size(); // Получаем бинарные данные количества полученных блоков const char * sbcb = reinterpret_cast <const char *> (&count); // Получаем бинарные данные идентификатора буквы const char * sbid = reinterpret_cast <const char *> (&sizeId); // Получаем бинарные данные количества альтернативных букв const char * sbalt = reinterpret_cast <const char *> (&sizeAlternative); // Добавляем буфер размер идентификатора словаря buffer.insert(buffer.end(), sbid, sbid + sizeof(size_t)); // Добавляем в буфер сам идентификатор словаря buffer.insert(buffer.end(), id.begin(), id.end()); // Добавляем в буфер количество альтернативных букв buffer.insert(buffer.end(), sbalt, sbalt + sizeof(size_t)); // Если список альтернативных букв не пустой if(!alternative.empty()){ // Переходим по всему списку альтернативных букв for(auto it = alternative.cbegin(); it != alternative.cend(); ++it){ // Получаем первую букву const char * first = reinterpret_cast <const char *> (&it->first); // Получаем вторую букву const char * second = reinterpret_cast <const char *> (&it->second); // Добавляем в буфер первую букву buffer.insert(buffer.end(), first, first + sizeof(u_int)); // Добавляем в буфер вторую букву buffer.insert(buffer.end(), second, second + sizeof(u_int)); } } // Добавляем в буфер количество блоков buffer.insert(buffer.end(), sbcb, sbcb + sizeof(size_t)); // Переходим по всем размерам блока for(size_t i = 0; i < sizes.size(); i++){ // Получаем размер блока const char * size = reinterpret_cast <const char *> (&sizes[i]); // Добавляем в буфер размеры блоков buffer.insert(buffer.end(), size, size + sizeof(size_t)); } // Добавляем в буфер сами данные блоков buffer.insert(buffer.end(), data.begin(), data.end()); // Выполняем запись в файл df.write(filename, buffer); } } /** * delLevel Метод удаления уровня * @param level уровень проверки */ void morph::DPA::delLevel(const u_short level){ // Если уровень передан if((level != OPT_NULL) && (this->level != OPT_NULL)){ // Формируем параметры u_int levels = this->level; // Убираем настройку levels = levels ^ level; // Если параметры больше стали чем были значит ошибка if(levels > this->level) levels = this->level; // Устанавливаем новые параметры this->level = levels; // Устанавливаем корректор в каждой букве if((level & OPT_ALTERNATIVE) && !this->letters.empty()){ // Переходим по всем буквам и активируем корректор for(auto it = this->letters.begin(); it != this->letters.end(); ++it){ // Деактивируем корректор it->second->delAlternative(); } } } } /** * setLevel Метод установки уровня проверки * @param level уровень проверки */ void morph::DPA::setLevel(const u_short level){ // Если уровень передан if(level != OPT_NULL){ // Добавляем наличие уровня проверки одной неправильной буквы if(level & OPT_ONELETTER) this->level = (this->level | OPT_ONELETTER); // Добавляем наличие уровня проверки слитых верных слов if(level & OPT_UNIONTRUE) this->level = (this->level | OPT_UNIONTRUE); // Добавляем наличие уровня проверки наличия дефиза в правильном слове if(level & OPT_HYPHENTRUE) this->level = (this->level | OPT_HYPHENTRUE); // Добавляем наличие уровня проверки слов разделенных пробелом if(level & OPT_CHECKSPACES) this->level = (this->level | OPT_CHECKSPACES); // Добавляем наличие уровня проверки альтернативной буквы if(level & OPT_ALTERNATIVE) this->level = (this->level | OPT_ALTERNATIVE); // Добавляем наличие уровня проверки наличия дефиза в неправильном слове if(level & OPT_HYPHENFALSE) this->level = (this->level | OPT_ONELETTER | OPT_HYPHENTRUE); // Добавляем наличие уровня проверки нескольких неправильных букв if(level & OPT_SEVERALLETTER) this->level = (this->level | OPT_ONELETTER | OPT_SEVERALLETTER); // Добавляем наличие уровня проверки слитых неправильных слов if(level & OPT_UNIONFALSE) this->level = (this->level | OPT_ONELETTER | OPT_SEVERALLETTER | OPT_UNIONTRUE | OPT_UNIONFALSE); // Устанавливаем корректор в каждой букве if((level & OPT_ALTERNATIVE) && !this->letters.empty()){ // Переходим по всем буквам и активируем корректор for(auto it = this->letters.begin(); it != this->letters.end(); ++it){ // Активируем корректор it->second->setAlternative(); } } } } /** * DPA Конструктор * @param level уровень проверки */ morph::DPA::DPA(const u_short level){ try { // Объявляем алфавит this->alphabet = new Alphabet; // Устанавливаем указанный уровень this->setLevel(level); // Если происходит ошибка то игнорируем её } catch(const bad_alloc&) { // Выходим из приложения exit(SIGSEGV); } } /** * ~DPA Деструктор */ morph::DPA::~DPA(){ // Переходим по всем объектам и удаляем их for(auto it = this->letters.begin(); it != this->letters.end(); ++it) delete it->second; // Если алфавит создан тогда удаляем его if(this->alphabet != nullptr) delete this->alphabet; } <file_sep>/README.md # Исправление опечаток в русском языке (C++11) Исправление всех опечаток в тексте, не только в одиночных словах. Расстановка пробелов в слитых словах, причем слова могут содержать ошибки. Например слово **"ХорошистСпасибо"** будет исправлено как **"Хорошист Спасибо"** а слово **"ХорушистСпусибом"** будет исправлено на **"Хорошист Спасибо"**.<br> Исправление слов которые должны содержать букву **Ё** если они её не содержат. Например слово **"Ее"** будет исправлено как **"Её"** а слово **"Ежик"** будет исправлено на **"Ёжик"**.<br> Модуль использует корпус русского языка от **[OpenCorpora](http://opencorpora.org)** - dict.opcorpora.xml. Данный корпус довольно большого размера и для работы с ним, необходимо полностью загрузить его в память. В связи с чем, активация модуля происходит длительное время, например на процессоре Intel i7, SSD и 8Гб ОЗУ, полная загрузка занимает **~30 минут**.<br> ## Сборка и запуск: ### MacOS X: ``` # make # make start ``` ### Linux: ``` # make # make start ``` ### FreeBSD: ``` # gmake # gmake start ``` > Для работы "demo" необходимо установить пакет **[Zlib](http://www.zlib.net)** ![Загрузка корпуса русского языка](https://github.com/anyks/misprint/raw/master/img/loading.png "Загрузка корпуса русского языка") ![Работа приложения](https://github.com/anyks/misprint/raw/master/img/work.png "Работа приложения") ## Документация: ### Флаги корректировки опечаток ``` OPT_ONELETTER - Флаг разрешающий проверять только одну неправильную букву OPT_SEVERALLETTER - Флаг разрешающий проверять несколько неправильных букв OPT_ALTERNATIVE - Флаг разрешающий проверку наличия буквы Ё OPT_HYPHENTRUE - Флаг разрешающий проверку наличия дефиза в правильном слове OPT_HYPHENFALSE - Флаг разрешающий проверку наличия дефиза в неправильном слове OPT_UNIONTRUE - Флаг разрешающий проверку слитых правильных слов OPT_UNIONFALSE - Флаг разрешающий проверку слитых неправильных слов OPT_CHECKSPACES - Флаг разрешающий проверку слов разделенных пробелом ``` ### Основные методы * **setLevel** - Установка флага уровня корректировки опечаток.<br><br> * **delLevel** - Удаление флага уровня корректировки опечаток.<br><br> * **write** - Запись из базы данных ОЗУ в бинарный корпус для работы модуля.<br><br> * **read** - Чтение из бинарного корпуса для работы модуля в базу данных ОЗУ.<br><br> * **set** - Добавление слова в базу данных ОЗУ.<br><br> * **get** - Чтение вариантов подходящих слов из базы данных ОЗУ. Можно указать дистанцию поиска (по умолчанию 2) и количество данных для выдачи (по умолчанию 10).<br><br> * **del** - Удаление вариантов подходящих слов из базы данных ОЗУ.<br><br> * **check** - Проверка существования слова в базе данных ОЗУ.<br><br> * **count** - Получение количества слов на указанную фразу.<br><br> * **clause** - Добавление слов из неотформатированного текста в базу данных ОЗУ.<br><br> * **correct** - Корректировка ошибок и опечаток в неотформатированном тексте.<br><br> * **analyze** - Анализирование текста и подбор вариантов на неправильные слова в тексте.<br><br> <file_sep>/demo.cpp #include "dpa.hpp" // Устанавливаем область видимости using namespace morph; /** * main Главная функция приложения * @param argc длина массива параметров * @param argv массив параметров * @return код выхода из приложения */ int main(int argc, char * argv[]){ // Устанавливаем локаль setlocale(LC_ALL, "ru_RU.UTF-8"); // Создаем объект морфологии DPA mtk(OPT_ONELETTER | OPT_SEVERALLETTER | OPT_ALTERNATIVE | OPT_HYPHENTRUE | OPT_HYPHENFALSE | OPT_UNIONTRUE | OPT_UNIONFALSE | OPT_CHECKSPACES); // Буфер данных для ввода текста string buffer; // Выполняем очистку консоли printf("\033c"); // Загружаем корпус в память mtk.read("./ru"); // Информационное сообщение 2 const string info1 = "Для выхода введите"; // Информационное сообщение 1 const string info2 = "Введите текст для исправления"; // Выводим сообщение printf("\r\n\x1B[1m%s.\x1B[0m\r\n\x1B[1m%s:\x1B[0m exit\r\n\r\n", info2.c_str(), info1.c_str()); // Выполняем чтение данных в буфер while(true){ // Считываем данные в буфер getline(cin, buffer); // Если данные существуют if(!buffer.empty()){ // Если это выход тогда выходим if(buffer.compare("exit") == 0){ // Выполняем очистку консоли printf("\033c"); // Выводим прощание printf("\r\n\x1B[34m\x1B[1mДо скорой встречи!\x1B[0m\r\n\r\n"); // Выходим из приложения break; } // Исправленная строка string str = buffer; // Выполняем корректировку текста mtk.correct(str); // Выполняем очистку консоли printf("\033c"); // Выводим сообщение printf("\r\n\x1B[1m%s.\x1B[0m\r\n\x1B[1m%s:\x1B[0m exit\r\n\r\n", info2.c_str(), info1.c_str()); // Выводим исходный текст printf("\r\n\x1B[1mИсходный текст:\x1B[0m\r\n%s\r\n\r\n", buffer.c_str()); // Выводим результат printf("\x1B[1mИсправленный текст:\x1B[0m\r\n%s\r\n\r\n", str.c_str()); } } // Выходим return 0; } <file_sep>/tools/converter.hpp #ifndef _STK_CONVERTER_MORPH_ #define _STK_CONVERTER_MORPH_ #include <map> #include <list> #include <regex> #include <ctime> #include <string> #include <vector> #include <memory> #include <locale> #include <fstream> #include <codecvt> #include <iostream> #include <algorithm> #include <unordered_map> #include <zlib.h> #include <stdio.h> #include <fcntl.h> #include <dirent.h> #include <stdlib.h> #include <signal.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> // Размер чанка буфера для чтения из файла #define BUFFER_CHUNK 0x1000 // Основные флаги прокси сервера #define OPT_NULL (0 << 0) // Флаг пустых данных #define OPT_TYPEWRITE (1 << 1) // Флаг записи в файл #define OPT_TYPEAPPEND (1 << 2) // Флаг добавления в файл #define OPT_PARAMTAG (1 << 3) // Флаг поиска по тегу #define OPT_PARAMPAR (1 << 4) // Флаг поиска по параметру #define OPT_CONSOLE (1 << 5) // Флаг вывода в консоль обработанных слов // Параметры Zlib #define MOD_GZIP_ZLIB_WINDOWSIZE 15 #define MOD_GZIP_ZLIB_CFACTOR 9 #define MOD_GZIP_ZLIB_BSIZE 8096 // Устанавливаем область видимости using namespace std; /* * AHttp пространство имен */ namespace morph { /** * Converter Класс конвертера корпусов */ class Converter { private: /** * Alphabet Класс для работы с алфавитом */ class Alphabet { private: // Список альтернативных букв map <u_int, u_int> alternatives; public: /** * Метод получения списка альтернативных букв * return список альтернативных букв */ const map <u_int, u_int> getAlternatives() const; /** * strFormat Метод реализации функции формирования форматированной строки * @param format формат строки * @param args передаваемые аргументы * @return сформированная строка */ const wstring strFormat(const wchar_t * format, ...) const; /** * lidToLetter Метод перевода цифрового идентификатора буквы в букву * @param lid идентификатор буквы * @return буква в текстовом виде */ const wstring lidToLetter(const u_int lid) const; /** * getAlternative Метод получения альтернативной буквы * @param letter буква для проверки * @return альтернативная буква */ const wstring getAlternative(const wstring & letter) const; /** * getRealLetter Метод получения реальной буквы из альтернативной * @param alternative альтернативная буква * @return реальная буква */ const wstring getRealLetter(const wstring & alternative) const; /** * toString Метод конвертирования строки utf-8 в строку * @param str строка utf-8 для конвертирования * @return обычная строка */ const string toString(const wstring & str) const; /** * toWstring Метод конвертирования строки в строку utf-8 * @param str строка для конвертирования * @return строка в utf-8 */ const wstring toWstring(const string & str) const; /** * toLower Метод перевода русских букв в нижний регистр * @param str строка для перевода * @return строка в нижнем регистре */ const wstring toLower(const wstring & str) const; /** * toUpper Метод перевода русских букв в верхний регистр * @param str строка для перевода * @return строка в верхнем регистре */ const wstring toUpper(const wstring & str) const; /** * isNumber Метод проверки является ли строка числом * @param str строка для проверки * @return результат проверки */ const bool isNumber(const wstring & str) const; /** * letterToLid Метод перевода буквы в цифровой идентификатор * @param letter буква для конвертации * @return идентификатор буквы */ const u_int letterToLid(const wstring & letter) const; /** * isCase Метод определения регистра первого символа в строке * @param str строка для проверки * @return регистр символов (true - верхний, false - нижний) */ const bool isCase(const wstring & str) const; /** * isAlternative Метод проверки существования альтернативной буквы * @param letter буква для проверки * @return результат проверки */ const bool isAlternative(const wstring & letter) const; /** * split Метод разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void split(const wstring & str, const wstring delim, list <wstring> & v) const; /** * uppLetterWord Метод перевода первого символа в строке в верхний регистр * @param str строка для перевода */ void uppLetterWord(wstring & str) const; /** * clearAlternative Метод удаления альтернативной буквы * @param letter буква у которой есть альтернативная буква */ void clearAlternative(const wstring letter = L""); /** * addAlternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void addAlternative(const wstring & letter, const wstring & alternative); }; /** * Df Класс для работы с каталогами и файлами */ struct Df { /** * compress Метод сжатия данных * @param buffer буфер данных для сжатия * @return результат сжатия */ const vector <char> compress(const vector <char> & buffer) const; /** * decompress Метод рассжатия данных * @param buffer буфер данных для расжатия * @return результат расжатия */ const vector <char> decompress(const vector <char> & buffer) const; /** * readRecursiveDir Метод рекурсивного получения файлов во всех подкаталогах * @param path путь до каталога * @param ext расширение файла по которому идет фильтрация * @return список файлов соответствующих расширению */ const vector <string> readRecursiveDir(const string & path, const string & ext) const; /** * read Метод чтения данных из файла * @param filename адрес файла * @param buffer буфер данных для чтения */ void read(const string & filename, vector <char> & buffer) const; /** * write Метод записи данных в файл * @param filename адрес файла * @param buffer буфер данных для записи */ void write(const string & filename, vector <char> & buffer) const; /** * mkdir Метод рекурсивного создания каталогов * @param path адрес каталогов */ void mkdir(const string & path) const; }; // Ключ поиска string key = ""; // Идентификатор словаря wstring id = L""; // Параметры конвертера u_short params = OPT_NULL; // Алфавит Alphabet * alphabet = nullptr; /** * setId Метод установки идентификатора словаря * @param id идентификатор словаря */ void setId(const wstring & id); /** * convertFile Метод конвертации одного файла * @param file путь к файлу корпуса * @param path путь где хранится сконвертированный корпус * @param name название корпуса (идентификатор словаря) */ void convertFile(const string & file, const string & path, const string & name); /** * convertFiles Метод конвертации группы файлов находящихся в дирректории * @param path путь где хранится сконвертированный корпус * @param name название корпуса (идентификатор словаря) * @param dir каталог в котором находятся xml файлы * @param ext расширение корпуса (по умолчанию xml) */ void convertFiles(const string & path, const string & name, const string & dir, const string & ext = "xml"); /** * append Метод добавления в уже созданный ранее файл корпуса, нового списка слов * @param words список слов для записи в файл * @param path путь где хранится сконвертированный корпус * @param name название корпуса (идентификатор словаря) */ void append(const map <u_int, vector <string>> & words, const string & path, const string & name); /** * write Метод записи полученных данных в файл * @param words список слов для записи в файл * @param path путь где хранится сконвертированный корпус * @param name название корпуса (идентификатор словаря) */ void write(const map <u_int, vector <string>> & words, const string & path, const string & name) const; /** * alternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void alternative(const wstring & letter, const wstring & alternative); /** * getBlock Метод получения бинарного блока слов из списка слов * @param letter буква на которую нужно получить бинарный блок данных * @param список слов из которых нужно получить бинарный блок * @return бинарный блок данных */ const vector <char> getBlock(const wstring & letter, const vector <string> & words) const; /** * read Метод чтения данных корпуса * @param file файл корпуса без расширения * @return список слов из файла */ const map <u_int, vector <string>> read(const string & file); /** * parserXmlTag Метод парсинга XML файла по указанным тегам * @param buffer буфер данных для парсинга * @param key ключ поиска параметра * @return список полученных слов */ const map <u_int, vector <string>> parserXmlTag(const vector <char> & buffer, const string & key = "w") const; /** * parserXmlParam Метод парсинга XML файла по указанным параметрам * @param buffer буфер данных для парсинга * @param key ключ поиска параметра * @return список полученных слов */ const map <u_int, vector <string>> parserXmlParam(const vector <char> & buffer, const string & key = "t") const; public: /** * getId Метод получения идентификатора словаря * @return идентификатор словаря */ const string getId() const; /** * split Метод разделения текст на слова * @param text текст для разделения * @param delim разделитель * @return список слов */ const list <string> split(const string text, const string delim) const; /** * clearParams Метод сброса параметров */ void clearParams(); /** * setId Метод установки идентификатора словаря * @param id идентификатор словаря */ void setId(const string id = ""); /** * setKey Метод установки ключа поиска * @param key ключ поиска */ void setKey(const string key = ""); /** * delParams Метод удаления параметров конвертера * @param params параметры конвертера */ void delParams(const u_short params = OPT_NULL); /** * setParams Метод установки параметров конвертера * @param params параметры конвертера */ void setParams(const u_short params = OPT_NULL); /** * alternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void alternative(const string letter, const string alternative); /** * del Метод удаления слова в существующем словаре * @param word слово для удаления * @param path путь к словарю * @param name название словаря */ void del(const string word, const string path, const string name); /** * del Метод удаления слов в существующем словаре * @param words слова для удаления * @param path путь к словарю * @param name название словаря */ void del(const list <string> words, const string path, const string name); /** * add Метод добавления слова в существующий словарь * @param word слово для добавления * @param path путь к словарю * @param name название словаря */ void add(const string word, const string path, const string name); /** * add Метод добавления слов в существующий словарь * @param words слова для добавления * @param path путь к словарю * @param name название словаря */ void add(const list <string> words, const string path, const string name); /** * convert Метод конвертация стороннего корпуса в бинарный корпус * @param file путь к файлу корпуса * @param path путь где хранится сконвертированный корпус * @param dir каталог в котором находятся xml файлы * @param ext расширение корпуса (по умолчанию xml) * @param name название корпуса (идентификатор словаря) */ void convert(const string file = "", const string path = "", const string dir = "", const string ext = "", const string name = ""); /** * Converter Конструктор * @param params параметры конвертера */ Converter(const u_short params = OPT_NULL); /** * ~Converter Деструктор */ ~Converter(); }; }; #endif // _STK_CONVERTER_MORPH_ <file_sep>/tools/app.cpp #include "converter.hpp" // Устанавливаем область видимости using namespace morph; /** * main Главная функция приложения * @param argc длина массива параметров * @param argv массив параметров * @return код выхода из приложения */ int main(int argc, char * argv[]){ // Устанавливаем локаль setlocale(LC_ALL, "en_EN.UTF-8"); // Создаем объект конвертера Converter mtk; // Список слов для обработки list <string> words; // Альтернативные буквы string alt1 = "", alt2 = ""; // Настройки конвертера string corpus = "", prefix = "./", dir = "./", name = "", ext = "xml"; // Параметры конвертера u_short params = OPT_NULL, method = 0; // Переходим по массиву аргументов for(int i = 0; i < argc; i++){ // Получаем значение аргумента string arg = argv[i]; // Определяем ключ поиска if(arg.find("--key=") != string::npos) mtk.setKey(arg.replace(0, 6, "")); // Определяем файл корпуса else if(arg.find("--corpus=") != string::npos) corpus = arg.replace(0, 9, ""); // Определяем путь сохранения словаря else if(arg.find("--prefix=") != string::npos) prefix = arg.replace(0, 9, ""); // Определяем каталог для обработки файлов корпусов else if(arg.find("--dir=") != string::npos) dir = arg.replace(0, 6, ""); // Определяем расширение файла для обработки else if(arg.find("--ext=") != string::npos) ext = arg.replace(0, 6, ""); // Определяем имя словаря else if(arg.find("--name=") != string::npos) name = arg.replace(0, 7, ""); // Определяем альтернативную букву else if(arg.find("--alt=") != string::npos) { // Получаем значение параметра const string & alt = arg.replace(0, 6, ""); // Выполняем поиск разделителя const size_t pos = alt.find("/"); // Если позиция найдена if(pos != string::npos){ // Копируем значение первой буквы alt1 = alt.substr(0, pos); // Копируем значение второй буквы alt2 = alt.substr(pos + 1, alt.size() - (pos + 1)); } // Если это список слов } else if(arg.find("--words=") != string::npos) { // Получаем список слов words = mtk.split(arg.replace(0, 8, ""), ","); // Если это параметр метод работы конвертера } else if(arg.find("--method=") != string::npos) { // Получаем значение параметра const string & mt = arg.replace(0, 9, ""); // Если это метод конвертирования if(mt.compare("conv") == 0) method = 0; // Если это метод добавления слова else if(mt.compare("add") == 0) method = 1; // Если это метод удаления слова else if(mt.compare("del") == 0) method = 2; // Если это параметр вывода в консоль добавления слов } else if(arg.compare("--verbose") == 0) params = (params | OPT_CONSOLE); // Если это параметр обработки корпуса по тегам else if(arg.find("--parser=") != string::npos) { // Получаем значение парсера const string & parser = arg.replace(0, 9, ""); // Если это парсинг по тегам if(parser.compare("tag") == 0) params = (params | OPT_PARAMTAG); // Если это парсинг по параметрам else if(parser.compare("param") == 0) params = (params | OPT_PARAMPAR); // Если это параметр записи или добавления в файл } else if(arg.find("--mode=") != string::npos) { // Получаем значение const string & mode = arg.replace(0, 7, ""); // Если это запись в файл if(mode.compare("write") == 0) params = (params | OPT_TYPEWRITE); // Если это добавление в файл else if(mode.compare("append") == 0) params = (params | OPT_TYPEAPPEND); // Выводим сообщение о помощи } else if(argc == 1) { // Выводим сообщение о поиске printf( "\r\n\x1B[34m\x1B[1mExample:\x1B[0m\r\n\x1B[32m\x1B[1m#\x1B[0m " "./convert --key=t --corpus=./dict.opcorpora.xml --prefix=./ " "--name=ru --alt=е/ё --verbose --parser=param --mode=write --method=conv\r\n" "\x1B[34m\x1B[1mOR\x1B[0m\r\n\x1B[32m\x1B[1m#\x1B[0m " "./convert --key=w --prefix=./ --dir=./Texts --ext=xml " "--name=en --verbose --parser=tag --mode=append --method=conv\r\n" "\x1B[34m\x1B[1mOR\x1B[0m\r\n\x1B[32m\x1B[1m#\x1B[0m " "./convert --prefix=./ --name=ru --verbose --method=add --words=чувак,клёвый\r\n" "\x1B[34m\x1B[1mOR\x1B[0m\r\n\x1B[32m\x1B[1m#\x1B[0m " "./convert --prefix=./ --name=en --verbose --method=del --words=mir\r\n\r\n" ); } } // Устанавливаем параметры конвертера mtk.setParams(params); // Если альтернативные буквы указаны if(!alt1.empty() && !alt2.empty()) mtk.alternative(alt1, alt2); // Если корпус указан if(!corpus.empty() && !prefix.empty() && !name.empty() && words.empty()){ // Выполняем конвертирование корпуса if(method == 0) mtk.convert(corpus, prefix, "", "", name); // Если указан каталог с корпусами } else if(!prefix.empty() && !dir.empty() && !ext.empty() && !name.empty() && words.empty()) { // Выполняем конвертирование корпуса if(method == 0) mtk.convert("", prefix, dir, ext, name); // Если это методы для работы с словами } else if(!words.empty() && !prefix.empty() && !name.empty()) { // Определяем тип метода switch(method){ // Если это добавление слов в файл словаря case 1: { // Добавляем список слов в словарь if(words.size() > 1) mtk.add(words, prefix, name); // Добавляем одно слово в словарь else mtk.add(words.front(), prefix, name); } break; // Если это удаление слов из файла словаря case 2: { // Удаляем список слов из словаря if(words.size() > 1) mtk.del(words, prefix, name); // Удаляем одно слово из словаря else mtk.del(words.front(), prefix, name); } break; } } // Выходим return 0; } <file_sep>/levenshtein.hpp #ifndef _LD_MORPH_ #define _LD_MORPH_ #include <stdlib.h> #include <locale.h> #include <sys/types.h> #include <string> #include <locale> #include <codecvt> #include <iostream> // Реализуем функцию определения минимального значения #define min(begin, end) (((begin) < (end)) ? (begin) : (end)) // Устанавливаем область видимости using namespace std; /* * AHttp пространство имен */ namespace morph { /** * Класс реализации дистанции левенштейна */ class LD { private: /** * minimum Метод определения минимального значения * @param x первое число * @param y второе число * @param z третье число * @return самое минимальное значение из 3-х чисел */ const size_t minimum(const size_t x, const size_t y, const size_t z); /** * matrix Метод создания матриц * @param row количество строк * @param col количество столбцов * @return созданная матрица */ size_t ** matrix(const size_t row = 0, const size_t col = 0); /** * free Метод очистки матрицы * @param matrix матрица для очистки * @param row количество строк */ void free(size_t ** matrix = nullptr, const size_t row = 0); public: /** * tanimoto Метод определения коэффициента Жаккара (частное — коэф. Танимото) * @param first первое слово * @param second второе слово * @param stl размер подстроки при сравнении двух слов (от 1 до минимального размера слова) * @return коэффициент Танимото */ const float tanimoto(const wstring & first, const wstring & second, const u_short stl = 1); /** * tanimoto Метод определения коэффициента Жаккара (частное — коэф. Танимото) * @param first первое слово * @param second второе слово * @param stl размер подстроки при сравнении двух слов (от 1 до минимального размера слова) * @return коэффициент Танимото */ const float tanimoto(const string & first, const string & second, const u_short stl = 1); /** * distance Определение дистанции в фразах * @param pattern шаблон с которым идет сравнение * @param text исходный текст * @return дистанция */ const size_t distance(const wstring & pattern, const wstring & text); /** * distance Определение дистанции в фразах * @param pattern шаблон с которым идет сравнение * @param text исходный текст * @return дистанция */ const size_t distance(const string & pattern, const string & text); }; }; #endif // _LD_MORPH_ <file_sep>/Makefile # Определяем тип операционной системы OS := $(shell uname -s) # Название приложения NAME = demo # Если это MacOS X (Сборка через make) ifeq ($(OS), Darwin) # Компилятор CC = clang++ # Сторонние модули LIBS = -lz \ -lstdc++ endif # Если это FreeBSD (Сборка через gmake) ifeq ($(OS), FreeBSD) # Компилятор CC = clang++ # Сторонние модули LIBS = -lz \ -lstdc++ \ -L/usr/local/lib endif # Если это Linux ifeq ($(OS), Linux) # Компилятор CC = gcc # Сторонние модули LIBS = -lm \ -lz \ -lstdc++ endif # Заголовочные файлы INCLUDE = -I/usr/include \ -I/usr/local/include # Бинарный файл BIN = ./bin # Конфиг для стандартной сборки CONFIG = -std=c++11 ./levenshtein.cpp ./dpa.cpp ./demo.cpp # Правило сборки all: mkdir -p $(BIN) && $(CC) $(CONFIG) -O2 -pipe -mfma -mrdrnd -mf16c $(INCLUDE) $(LIBS) -o $(BIN)/$(NAME) # Правила сборки под Dev dev: mkdir -p $(BIN) && $(CC) $(CONFIG) -O0 -ggdb $(INCLUDE) $(LIBS) -o $(BIN)/$(NAME) # Правило запуска start: $(BIN)/$(NAME) # Правило очистки clean: rm -rf $(BIN) <file_sep>/tools/converter.cpp #include "converter.hpp" // Устанавливаем пространство имен using namespace std; // Устанавливаем шаблон функции template <typename C, typename T, typename A> /** * trim Функция удаления начальных и конечных пробелов * @param str строка для обработки * @param loc локаль * @return результат работы функции */ basic_string <C, T, A> trim(const basic_string <C, T, A> & str, const locale & loc = locale::classic()){ // Запоминаем итератор на первый левый символ auto begin = str.begin(); // Переходим по всем символам в слове и проверяем является ли символ - символом пробела, если нашли то смещаем итератор while((begin != str.end()) && isspace(* begin, loc)) ++begin; // Если прошли все слово целиком значит пробелов нет и мы выходим if(begin == str.end()) return {}; // Запоминаем итератор на первый правый символ auto rbegin = str.rbegin(); // Переходим по всем символам в слове и проверяем является ли символ - символом пробела, если нашли то смещаем итератор while(rbegin != str.rend() && isspace(* rbegin, loc)) ++rbegin; // Выводим результат return {begin, rbegin.base()}; } /** * Метод получения списка альтернативных букв * return список альтернативных букв */ const map <u_int, u_int> morph::Converter::Alphabet::getAlternatives() const { // Результат работы функции map <u_int, u_int> result; // Если список альтернативных букв существует if(!alternatives.empty()) result.insert(alternatives.begin(), alternatives.end()); // Выводим результат return move(result); } /** * strFormat Метод реализации функции формирования форматированной строки * @param format формат строки * @param args передаваемые аргументы * @return сформированная строка */ const wstring morph::Converter::Alphabet::strFormat(const wchar_t * format, ...) const { // Результат работы функции wstring result = L""; // Создаем буфер wchar_t buffer[256]; // Заполняем буфер нулями memset(buffer, 0, sizeof(buffer)); // Создаем список аргументов va_list args; // Устанавливаем начальный список аргументов va_start(args, format); // Выполняем запись в буфер const size_t size = vswprintf(buffer, sizeof(buffer), format, args); // Завершаем список аргументов va_end(args); // Если размер не нулевой if(size > 0) result.assign(buffer, size); // Выводим результат return move(result); } /** * lidToLetter Метод перевода цифрового идентификатора буквы в букву * @param lid идентификатор буквы * @return буква в текстовом виде */ const wstring morph::Converter::Alphabet::lidToLetter(const u_int lid) const { // Результат работы функции wstring result = L""; // Если идентификатор передан, получаем из него строку if(lid > 0) result = wstring(1, wchar_t(lid)); // Выводим результат return move(result); } /** * getAlternative Метод получения альтернативной буквы * @param letter буква для проверки * @return альтернативная буква */ const wstring morph::Converter::Alphabet::getAlternative(const wstring & letter) const { // Резузльтат работы функции wstring result = L""; // Если буква передана if(!letter.empty()){ // Получаем идентификатор буквы const u_int lid = this->letterToLid(letter); // Получаем данные буквы auto data = this->alternatives.find(lid); // Запоминаем результат result = this->lidToLetter(data->second); } // Выводим в результат return move(result); } /** * getRealLetter Метод получения реальной буквы из альтернативной * @param alternative альтернативная буква * @return реальная буква */ const wstring morph::Converter::Alphabet::getRealLetter(const wstring & alternative) const { // Резузльтат работы функции wstring result = L""; // Если альтернативная буква передана if(!alternative.empty()){ // Получаем идентификатор буквы const u_int aid = this->letterToLid(alternative); // Переходим по всему списку альтернативных букв for(auto it = this->alternatives.cbegin(); it != this->alternatives.cend(); ++it){ // Если буква найдена if(aid == it->second){ // Запоминаем результат result = this->lidToLetter(it->first); // Выходим из цикла break; } } } // Выводим в результат return move(result); } /** * toString Метод конвертирования строки utf-8 в строку * @param str строка utf-8 для конвертирования * @return обычная строка */ const string morph::Converter::Alphabet::toString(const wstring & str) const { // Результат работы функции string result; // Если строка передана if(!str.empty()){ // Объявляем конвертер wstring_convert <codecvt_utf8 <wchar_t>> conv; // Выполняем конвертирование в utf-8 строку result = conv.to_bytes(str); } // Выводим результат return move(result); } /** * toWstring Метод конвертирования строки в строку utf-8 * @param str строка для конвертирования * @return строка в utf-8 */ const wstring morph::Converter::Alphabet::toWstring(const string & str) const { // Результат работы функции wstring result; // Если строка передана if(!str.empty()){ // Объявляем конвертер wstring_convert <codecvt_utf8 <wchar_t>> conv; // Выполняем конвертирование в utf-8 строку result = conv.from_bytes(str); } // Выводим результат return move(result); } /** * toLower Метод перевода русских букв в нижний регистр * @param str строка для перевода * @return строка в нижнем регистре */ const wstring morph::Converter::Alphabet::toLower(const wstring & str) const { // Результат работы функции wstring result = str; // Если строка передана if(!str.empty()){ // Объявляем локаль const locale utf8("en_US.UTF-8"); // Переходим по всем символам for(auto & c : result) c = std::tolower(c, utf8); } // Выводим результат return move(result); } /** * toUpper Метод перевода русских букв в верхний регистр * @param str строка для перевода * @return строка в верхнем регистре */ const wstring morph::Converter::Alphabet::toUpper(const wstring & str) const { // Результат работы функции wstring result = str; // Если строка передана if(!str.empty()){ // Объявляем локаль const locale utf8("en_US.UTF-8"); // Переходим по всем символам for(auto & c : result) c = std::toupper(c, utf8); } // Выводим результат return move(result); } /** * isNumber Метод проверки является ли строка числом * @param str строка для проверки * @return результат проверки */ const bool morph::Converter::Alphabet::isNumber(const wstring & str) const { return !str.empty() && find_if(str.begin(), str.end(), [](wchar_t c){ return !iswdigit(c); }) == str.end(); } /** * letterToLid Метод перевода буквы в цифровой идентификатор * @param letter буква для конвертации * @return идентификатор буквы */ const u_int morph::Converter::Alphabet::letterToLid(const wstring & letter) const { // Результат работы функции u_int result = 0; // Если буква передана, выполняем приведение типов if(!letter.empty()) result = u_int(letter[0]); // Выводим результат return move(result); } /** * isCase Метод определения регистра первого символа в строке * @param str строка для проверки * @return регистр символов (true - верхний, false - нижний) */ const bool morph::Converter::Alphabet::isCase(const wstring & str) const { // Результат работы функции bool result = false; // Если данные переданы if(!str.empty()){ // Получаем первую букву слова const wstring & letter1 = str.substr(0, 1); // Переводим букву в верхний регистр const wstring & letter2 = this->toUpper(letter1); // Проверяем на регистр символа result = (letter1.compare(letter2) == 0); } // Выводим результат return move(result); } /** * isAlternative Метод проверки существования альтернативной буквы * @param letter буква для проверки * @return результат проверки */ const bool morph::Converter::Alphabet::isAlternative(const wstring & letter) const { // Результат работы функции bool result = false; // Если буква передана if(!letter.empty()){ // Получаем идентификатор буквы const u_int lid = this->letterToLid(letter); // Выполняем проверку result = (this->alternatives.count(lid) > 0); } // Выводим результат return move(result); } /** * split Метод разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void morph::Converter::Alphabet::split(const wstring & str, const wstring delim, list <wstring> & v) const { size_t i = 0; size_t j = str.find(delim); size_t len = delim.length(); // Выполняем разбиение строк while(j != wstring::npos){ v.push_back(str.substr(i, j - i)); i = ++j + (len - 1); j = str.find(delim, j); if(j == wstring::npos) v.push_back(str.substr(i, str.length())); } // Если слово передано а вектор пустой, тогда создаем вектори из 1-го элемента if(!str.empty() && v.empty()) v.push_back(str); } /** * uppLetterWord Метод перевода первого символа в строке в верхний регистр * @param str строка для перевода */ void morph::Converter::Alphabet::uppLetterWord(wstring & str) const { // Если строка передана if(!str.empty()){ // Переводим букву в верхний регистр const wstring & letter = this->toUpper(str.substr(0, 1)); // Заменяем букву в тексте str.replace(0, letter.length(), letter); } } /** * clearAlternative Метод удаления альтернативной буквы * @param letter буква у которой есть альтернативная буква */ void morph::Converter::Alphabet::clearAlternative(const wstring letter){ // Получаем идентификатор буквы const u_int lid = this->letterToLid(letter); // Если буква передана if(!letter.empty()){ // Удаляем выбранную букву из списка if(this->alternatives.count(lid) > 0) this->alternatives.erase(lid); // Если буква не передана то удаляем все альтернативные буквы } else this->alternatives.clear(); } /** * addAlternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void morph::Converter::Alphabet::addAlternative(const wstring & letter, const wstring & alternative){ // Если буквы переданы if(!letter.empty() && !alternative.empty()){ // Получаем идентификатор буквы const u_int lid = this->letterToLid(letter); // Получаем идентификатор альтернативной буквы const u_int aid = this->letterToLid(alternative); // Если альтернативная буква не найдена в списке if(this->alternatives.count(lid) < 1){ // Добавляем букву в список this->alternatives.insert({move(lid), move(aid)}); } } } /** * compress Метод сжатия данных * @param buffer буфер данных для сжатия * @return результат сжатия */ const vector <char> morph::Converter::Df::compress(const vector <char> & buffer) const { // Результат работы функции vector <char> result; // Если буфер передан if(!buffer.empty()){ // Создаем поток zip z_stream zs; // Результирующий размер данных int ret = 0; // Заполняем его нулями memset(&zs, 0, sizeof(zs)); // Если поток инициализировать не удалось, выходим if(deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, MOD_GZIP_ZLIB_WINDOWSIZE + 16, MOD_GZIP_ZLIB_CFACTOR, Z_DEFAULT_STRATEGY) == Z_OK){ try { // Заполняем входные данные буфера zs.next_in = (Bytef *) buffer.data(); // Указываем размер входного буфера zs.avail_in = buffer.size(); // Создаем буфер с сжатыми данными char * zbuff = new char[(const size_t) zs.avail_in]; // Выполняем сжатие данных do { // Устанавливаем максимальный размер буфера zs.avail_out = zs.avail_in; // Устанавливаем буфер для получения результата zs.next_out = reinterpret_cast<Bytef *> (zbuff); // Выполняем сжатие ret = deflate(&zs, Z_FINISH); // Если данные добавлены не полностью if(result.size() < zs.total_out) // Добавляем оставшиеся данные result.insert(result.end(), zbuff, zbuff + (zs.total_out - result.size())); } while(ret == Z_OK); // Удаляем буфер данных delete [] zbuff; // Если происходит ошибка то игнорируем её } catch(const bad_alloc&) {} } // Завершаем сжатие deflateEnd(&zs); // Если сжатие не удалось то очищаем выходные данные if(ret != Z_STREAM_END) result.clear(); } // Выводим результат return move(result); } /** * decompress Метод рассжатия данных * @param buffer буфер данных для расжатия * @return результат расжатия */ const vector <char> morph::Converter::Df::decompress(const vector <char> & buffer) const { // Результат работы функции vector <char> result; // Если буфер передан if(!buffer.empty()){ // Создаем поток zip z_stream zs; // Результирующий размер данных int ret = 0; // Заполняем его нулями memset(&zs, 0, sizeof(zs)); // Если поток инициализировать не удалось, выходим if(inflateInit2(&zs, MOD_GZIP_ZLIB_WINDOWSIZE + 16) == Z_OK){ try { // Заполняем входные данные буфера zs.next_in = (Bytef *) buffer.data(); // Указываем размер входного буфера zs.avail_in = buffer.size(); // Получаем размер выходных данных const size_t size = (zs.avail_in * 10); // Создаем буфер с результирующими данными char * zbuff = new char[size]; // Выполняем расжатие данных do { // Устанавливаем буфер для получения результата zs.next_out = reinterpret_cast<Bytef *> (zbuff); // Устанавливаем максимальный размер буфера zs.avail_out = size; // Выполняем расжатие ret = inflate(&zs, 0); // Если данные добавлены не полностью if(result.size() < zs.total_out) // Добавляем оставшиеся данные result.insert(result.end(), zbuff, zbuff + (zs.total_out - result.size())); } while(ret == Z_OK); // Удаляем буфер данных delete [] zbuff; // Если происходит ошибка то игнорируем её } catch(const bad_alloc&) {} } // Завершаем расжатие inflateEnd(&zs); // Если сжатие не удалось то очищаем выходные данные if(ret != Z_STREAM_END) result.clear(); } // Выводим результат return move(result); } /** * readRecursiveDir Метод рекурсивного получения файлов во всех подкаталогах * @param path путь до каталога * @param ext расширение файла по которому идет фильтрация * @return список файлов соответствующих расширению */ const vector <string> morph::Converter::Df::readRecursiveDir(const string & path, const string & ext) const { // Результат работы функции vector <string> result; // Если адрес каталога и расширение файлов переданы if(!path.empty() && !ext.empty()){ // Структура проверка статистики struct stat info; // Проверяем переданный нам адрес bool isDir = (stat(path.c_str(), &info) == 0); // Если это файл if(isDir) isDir = ((info.st_mode & S_IFDIR) != 0); // Если путь существует if(isDir){ // Открываем указанный каталог DIR * dir = opendir(path.c_str()); // Если каталог открыт if(dir != nullptr){ // Создаем объект словаря Alphabet alphabet; // Получаем длину адреса const size_t length = path.size(); // Создаем указатель на содержимое каталога struct dirent * ptr = nullptr; // Выполняем чтение содержимого каталога while((ptr = readdir(dir))){ // Пропускаем названия текущие "." и внешние "..", так как идет рекурсия if(!strcmp(ptr->d_name, ".") || !strcmp(ptr->d_name, "..")) continue; // Адрес каталога const wstring & address = alphabet.strFormat(L"%s/%s", path.c_str(), ptr->d_name); // Получаем адрес в виде строки const string & path = alphabet.toString(address); // Если статистика извлечена if(!stat(path.c_str(), &info)){ // Если дочерний элемент является дирректорией if(S_ISDIR(info.st_mode)){ // Считываем файлы в поддиректории const vector <string> & dirs = this->readRecursiveDir(path, ext); // Если пути получены, добавляем их в список if(!dirs.empty()) result.insert(result.end(), dirs.begin(), dirs.end()); // Если дочерний элемент является файлом то удаляем его } else { // Получаем длину адреса const size_t size = address.length(); // Получаем расширение файла const wstring & extension = alphabet.strFormat(L".%s", ext.c_str()); // Переходим по всему адресу файла начиная с конца for(size_t i = size - 1; i > 0; i--){ // Выполняем извлечение полученного файла const wstring & file = address.substr(i, size - i); // Если расширение соответствует тогда добавляем в список адрес и выходим if(file.compare(extension) == 0){ // Добавляем в список адрес файла result.push_back(path); // Выходим из цикла break; } } } } } // Закрываем открытый каталог closedir(dir); } } } // Выводим результат return move(result); } /** * read Метод чтения данных из файла * @param filename адрес файла * @param buffer буфер данных для чтения */ void morph::Converter::Df::read(const string & filename, vector <char> & buffer) const { // Если адрес файла передан if(!filename.empty()){ // Структура проверка статистики struct stat info; // Проверяем переданный нам адрес bool isFile = (stat(filename.c_str(), &info) == 0); // Если это файл if(isFile) isFile = ((info.st_mode & S_IFMT) != 0); // Если путь существует if(isFile){ // Размер файла size_t size = 0; // Открываем файл на чтение ifstream file(filename.c_str(), ios::binary); // Если файл открыт if(file.is_open()){ // Количество обработанных байт size_t osize = 0, lsize = 0; // Перемещаемся в конец файла file.seekg(0, file.end); // Определяем размер файла size = file.tellg(); // Перемещаемся в начало файла file.seekg(0, file.beg); /* // Создаем буфер для чтения данных char bytes[BUFFER_CHUNK]; // Очищаем буфер данных buffer.clear(); // Считываем до тех пор пока все удачно while(file.good()){ // Зануляем буфер данных memset(bytes, 0, BUFFER_CHUNK); // Выполняем чтение данных в буфер file.read(bytes, BUFFER_CHUNK); // Добавляем полученные данные buffer.insert(buffer.end(), bytes, bytes + BUFFER_CHUNK); } */ // Закрываем файл file.close(); } // Если файл не нулевого размера if(size > 0){ // Устанавливаем размер чанка const u_int chunk = (size > (BUFFER_CHUNK * 2) ? (BUFFER_CHUNK * 2) : size); // Устанавливаем размер смещения size_t offset = 0, difference = 0; // Считываемые данные void * data = nullptr; // Открываем файл на чтение const int fd = open(filename.c_str(), O_RDONLY); // Если файловый дескриптор открыт if(fd > -1){ // Выделяем память для буфера данных vector <char> bytes; // Выполняем чтение пока все не прочитаем while(offset < size){ // Определяем разницу размеров difference = (size - offset); // Определяем реальный размер чанка const u_int rhunk = (offset < size ? (difference > chunk ? chunk : difference) : 0); // Выполняем чтение данных data = mmap(nullptr, rhunk, PROT_READ, MAP_SHARED, fd, offset); // Копируем в буфер прочитанные данные bytes.insert(bytes.end(), (char *) data, (char *) data + rhunk); // Выполняем синхронизацию с файловой системой // msync(data, chunk, MS_ASYNC); // Очищаем полученные данные munmap(data, rhunk); // Увеличиваем смещение offset += rhunk; } // Очищаем буфер данных buffer.clear(); // Добавляем полученные данные buffer.insert(buffer.end(), bytes.begin(), bytes.end()); // Закрываем файловый дескриптор close(fd); } } } } } /** * write Метод записи данных в файл * @param filename адрес файла * @param buffer буфер данных для записи */ void morph::Converter::Df::write(const string & filename, vector <char> & buffer) const { // Если адрес файла и буфер переданы if(!filename.empty() && !buffer.empty()){ // Открываем файл на запись ofstream file(filename.c_str(), ios::binary); // Если файл открыт if(file.is_open()){ // Выполняем запись в файл file.write((char *) buffer.data(), buffer.size()); // Закрываем файл file.close(); } } } /** * mkdir Метод рекурсивного создания каталогов * @param path адрес каталогов */ void morph::Converter::Df::mkdir(const string & path) const { // Если путь передан if(!path.empty()){ // Буфер с названием каталога char tmp[256]; // Указатель на сепаратор char * p = nullptr; // Копируем переданный адрес в буфер snprintf(tmp, sizeof(tmp), "%s", path.c_str()); // Определяем размер адреса size_t len = strlen(tmp); // Если последний символ является сепаратором тогда удаляем его if(tmp[len - 1] == '/') tmp[len - 1] = 0; // Переходим по всем символам for(p = tmp + 1; * p; p++){ // Если найден сепаратор if(* p == '/'){ // Сбрасываем указатель * p = 0; // Создаем каталог ::mkdir(tmp, S_IRWXU); // Запоминаем сепаратор * p = '/'; } } // Создаем последний каталог ::mkdir(tmp, S_IRWXU); } } /** * setId Метод установки идентификатора словаря * @param id идентификатор словаря */ void morph::Converter::setId(const wstring & id){ // Если идентификатор передан, сохраняем его if(!id.empty()) this->id = id; } /** * convertFile Метод конвертации одного файла * @param file путь к файлу корпуса * @param path путь где хранится сконвертированный корпус * @param name название корпуса (идентификатор словаря) */ void morph::Converter::convertFile(const string & file, const string & path, const string & name){ // Если путь и название файла переданы if(!path.empty() && !file.empty() && !name.empty() && ((this->params & OPT_PARAMTAG) || (this->params & OPT_PARAMPAR)) && ((this->params & OPT_TYPEWRITE) || (this->params & OPT_TYPEAPPEND))){ // Структура проверка статистики struct stat info; // Проверяем переданный нам адрес bool isFile = (stat(file.c_str(), &info) == 0); // Если это файл if(isFile) isFile = ((info.st_mode & S_IFMT) != 0); // Если путь существует if(isFile){ // Объявляем модуль работы с файловой системой Df df; // Структура проверка статистики struct stat info; // Буфер данных vector <char> buffer; // Проверяем переданный нам адрес bool isDir = (stat(path.c_str(), &info) == 0); // Если это файл if(isDir) isDir = ((info.st_mode & S_IFDIR) != 0); // Если путь не существует if(!isDir) df.mkdir(path.c_str()); // Выполняем чтение данных из файла df.read(file, buffer); // Если данные получены if(!buffer.empty()){ // Список слов для обработки map <u_int, vector <string>> words; // Если нужно произвести поиск по тегу if(this->params & OPT_PARAMTAG) words = this->parserXmlTag(buffer, this->key); // Если нужно произвести поиск по параметру else if(this->params & OPT_PARAMPAR) words = this->parserXmlParam(buffer, this->key); // Если слова получены if(!words.empty()){ // Если нужно произвести запись файла if(this->params & OPT_TYPEWRITE) this->write(words, path, name); // Если нужно произвести добавление в файл данных else if(this->params & OPT_TYPEAPPEND) this->append(words, path, name); } } } } } /** * convertFiles Метод конвертации группы файлов находящихся в дирректории * @param path путь где хранится сконвертированный корпус * @param name название корпуса (идентификатор словаря) * @param dir каталог в котором находятся xml файлы * @param ext расширение корпуса (по умолчанию xml) */ void morph::Converter::convertFiles(const string & path, const string & name, const string & dir, const string & ext){ // Если адрес каталога с файлами для конвертирования, // путь с файлами, расширение файлов и название корпуса переданы if(!path.empty() && !name.empty() && !dir.empty() && !ext.empty() && ((this->params & OPT_PARAMTAG) || (this->params & OPT_PARAMPAR))){ // Объявляем модуль работы с файловой системой Df df; // Выполняем чтение файлов auto files = df.readRecursiveDir(dir, ext); // Если список файлов получен if(!files.empty()){ // Структура проверка статистики struct stat info; // Буфер данных vector <char> buffer; // Проверяем переданный нам адрес bool isDir = (stat(path.c_str(), &info) == 0); // Если это файл if(isDir) isDir = ((info.st_mode & S_IFDIR) != 0); // Если путь не существует if(!isDir) df.mkdir(path.c_str()); // Переходим по всему списку файлов for(auto it = files.cbegin(); it != files.cend(); ++it){ // Очищаем буфер buffer.clear(); // Выполняем чтение данных из файла df.read(* it, buffer); // Если буфер не пустой if(!buffer.empty()){ // Список слов для обработки map <u_int, vector <string>> words; // Выводим в консоль сообщение if(this->params & OPT_CONSOLE) printf("Reading file name: %s\r\n", it->c_str()); // Если нужно произвести поиск по тегу if(this->params & OPT_PARAMTAG) words = this->parserXmlTag(buffer, this->key); // Если нужно произвести поиск по параметру else if(this->params & OPT_PARAMPAR) words = this->parserXmlParam(buffer, this->key); // Выполняем добавление полученных слов в файл if(!words.empty()) this->append(words, path, name); } } } } } /** * append Метод добавления в уже созданный ранее файл корпуса, нового списка слов * @param words список слов для записи в файл * @param path путь где хранится сконвертированный корпус * @param name название корпуса (идентификатор словаря) */ void morph::Converter::append(const map <u_int, vector <string>> & words, const string & path, const string & name){ // Если список слов, путь и имя словаря переданы if(!words.empty() && !path.empty() && !name.empty()){ // Адрес файла string filename = path; // Добавляем разделитель filename.append("/"); // Добавляем идентификатор буквы filename.append(name); // Выполняем чтение данных из созданного ранее файла auto result = this->read(filename); // Если список слов получен if(!result.empty()){ // Флаг добавления данных bool mode = false; // Переходим по всему списку полученных слов for(auto it = words.begin(); it != words.end(); ++it){ // Ищем в результирующем списке нашу букву if(result.count(it->first) > 0){ // Получаем список созданных ранее слов auto words = result.find(it->first); // Запоминаем количество слов const size_t size = words->second.size(); // Добавляем в список слов полученные слова words->second.insert(words->second.end(), it->second.begin(), it->second.end()); // Выполняем сортировку списка sort(words->second.begin(), words->second.end()); // Удаляем все повторяющиеся элементы в списке words->second.erase(unique(words->second.begin(), words->second.end()), words->second.end()); // Если размер изменился, значит была добавлена новая порция данных const bool append = (words->second.size() > size); // Заменяем ранее существующий список if(append) result.at(it->first) = words->second; // Запоминаем что данные изменены if(!mode) mode = append; // Если букву не нашли тогда просто добавляем в список } else { // Запоминаем что данные изменены mode = true; // Добавляем новую букву с текстом в список result.emplace(it->first, it->second); } } // Выполняем запись данных в файл, туда были добавлены данные if(mode) this->write(result, path, name); // Иначе записываем данные в том виде как они пришли } else this->write(words, path, name); } } /** * write Метод записи полученных данных в файл * @param words список слов для записи в файл * @param path путь где хранится сконвертированный корпус * @param name название корпуса (идентификатор словаря) */ void morph::Converter::write(const map <u_int, vector <string>> & words, const string & path, const string & name) const { // Если список слов, путь и имя словаря переданы if(!words.empty() && !path.empty() && !name.empty()){ // Объявляем модуль работы с файловой системой Df df; // Адрес файла string filename = path; // Добавляем разделитель filename.append("/"); // Добавляем идентификатор буквы filename.append(name); // Добавляем расширение файла filename.append(".dpa"); // Размер всех блоков vector <size_t> sizes; // Данные всех слов vector <char> data, buffer; // Удаляем файл если существует remove(filename.c_str()); // Получаем размер идентификатора const size_t sizeId = name.size(); // Получаем список альтернативных букв auto alternative = this->alphabet->getAlternatives(); // Получаем количество альтернативных букв const size_t sizeAlternative = alternative.size(); // Переходим по всему списку слов for(auto it = words.cbegin(); it != words.cend(); ++it){ // Получаем букву const wstring & letter = this->alphabet->lidToLetter(it->first); // Запрашиваем блок auto frame = this->getBlock(letter, it->second); // Если блок не пустой if(!frame.empty()){ // Запоминаем размер каждого блока sizes.push_back(frame.size()); // Заполняем список данных data.insert(data.end(), frame.begin(), frame.end()); } } // Получаем количество блоков const size_t count = sizes.size(); // Получаем бинарные данные количества полученных блоков const char * sbcb = reinterpret_cast <const char *> (&count); // Получаем бинарные данные идентификатора буквы const char * sbid = reinterpret_cast <const char *> (&sizeId); // Получаем бинарные данные количества альтернативных букв const char * sbalt = reinterpret_cast <const char *> (&sizeAlternative); // Добавляем буфер размер идентификатора словаря buffer.insert(buffer.end(), sbid, sbid + sizeof(size_t)); // Добавляем в буфер сам идентификатор словаря buffer.insert(buffer.end(), name.begin(), name.end()); // Добавляем в буфер количество альтернативных букв buffer.insert(buffer.end(), sbalt, sbalt + sizeof(size_t)); // Если список альтернативных букв не пустой if(!alternative.empty()){ // Переходим по всему списку альтернативных букв for(auto it = alternative.cbegin(); it != alternative.cend(); ++it){ // Получаем первую букву const char * first = reinterpret_cast <const char *> (&it->first); // Получаем вторую букву const char * second = reinterpret_cast <const char *> (&it->second); // Добавляем в буфер первую букву buffer.insert(buffer.end(), first, first + sizeof(u_int)); // Добавляем в буфер вторую букву buffer.insert(buffer.end(), second, second + sizeof(u_int)); } } // Добавляем в буфер количество блоков buffer.insert(buffer.end(), sbcb, sbcb + sizeof(size_t)); // Переходим по всем размерам блока for(size_t i = 0; i < sizes.size(); i++){ // Получаем размер блока const char * size = reinterpret_cast <const char *> (&sizes[i]); // Добавляем в буфер размеры блоков buffer.insert(buffer.end(), size, size + sizeof(size_t)); } // Добавляем в буфер сами данные блоков buffer.insert(buffer.end(), data.begin(), data.end()); // Выполняем запись в файл df.write(filename, buffer); } } /** * alternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void morph::Converter::alternative(const wstring & letter, const wstring & alternative){ // Если данные переданы if(!letter.empty() && !alternative.empty()){ // Добавляем альтернативную букву в алфавит this->alphabet->addAlternative(letter, alternative); } } /** * getBlock Метод получения бинарного блока слов из списка слов * @param letter буква на которую нужно получить бинарный блок данных * @param список слов из которых нужно получить бинарный блок * @return бинарный блок данных */ const vector <char> morph::Converter::getBlock(const wstring & letter, const vector <string> & words) const { // Результат работы функции vector <char> result; // Если буква передана if(!letter.empty() && !words.empty()){ // Если список получен if(!words.empty()){ // Объявляем модуль работы с файловой системой Df df; // Данные всех слов vector <char> data; // Размеры всех слов vector <size_t> sizes; // Получаем количество слов const size_t count = words.size(); // Выполняем получение идентификатора буквы const u_int lid = this->alphabet->letterToLid(this->alphabet->toLower(letter)); // Получаем размеры каждого слова for(auto it = words.cbegin(); it != words.cend(); ++it){ // Получаем слово const string & str = (* it); // Получаем размер слова const size_t size = str.size(); // Получаем данные слова const char * word = str.data(); // Заполняем список данных data.insert(data.end(), word, word + size); // Заполняем список размеров sizes.push_back(size); } // Получаем бинарные данные идентификатора буквы const char * clid = reinterpret_cast <const char *> (&lid); // Получаем бинарные данные количества слов const char * ccount = reinterpret_cast <const char *> (&count); // Добавляем в результирующий массив идентификатор буквы result.insert(result.end(), clid, clid + sizeof(lid)); // Добавляем в результирующий массив количество букв result.insert(result.end(), ccount, ccount + sizeof(count)); // Переходим по всем размерам блока for(size_t i = 0; i < sizes.size(); i++){ // Получаем размер блока const char * size = reinterpret_cast <const char *> (&sizes[i]); // Добавляем в буфер размеры блоков result.insert(result.end(), size, size + sizeof(size_t)); } // Добавляем в результирующий массив - все данные слов result.insert(result.end(), data.begin(), data.end()); // Выполняем сжатие блока данных result = df.compress(result); // Очищаем данные слов vector <char> ().swap(data); // Очищаем размеры всех слов vector <size_t> ().swap(sizes); } } // Выводим результат return move(result); } /** * read Метод чтения данных корпуса * @param file файл корпуса без расширения * @return список слов из файла */ const map <u_int, vector <string>> morph::Converter::read(const string & file){ // Результат работы функции map <u_int, vector <string>> result; // Если путь передан и буквы существуют if(!file.empty()){ // Объявляем модуль работы с файловой системой Df df; // Структура проверка статистики struct stat info; // Создаем имя файла string filename = file; // Добавляем расширение файла filename.append(".dpa"); // Проверяем переданный нам адрес bool isFile = (stat(filename.c_str(), &info) == 0); // Если это файл if(isFile) isFile = ((info.st_mode & S_IFMT) != 0); // Если путь существует if(isFile){ /** * appendWord Функция добавления слова в результирующий список * @param word слово для добавления */ auto appendWord = [&result, this](const string & word){ // Если слово для добавления передано if(!word.empty()){ // Получаем текст в нижнем регистре const wstring & str = this->alphabet->toLower(this->alphabet->toWstring(word)); // Если это не только цифры if(!this->alphabet->isNumber(str)){ // Переводим букву в нижний регистр const wstring & letter = str.substr(0, 1); // Конвертируем слово обратно в строку const string & word = this->alphabet->toString(str); // Выполняем копирование слова const u_int lid = this->alphabet->letterToLid(letter); // Если буква в списке найдена if(result.count(lid) > 0){ // Добавляем в список result.find(lid)->second.push_back(word); // Выполняем запись в память } else result.insert({lid, {word}}); } } }; /** * createResult Функция формирования результата * @param frame фрейм с данными */ auto createResult = [&df, &appendWord, this](const vector <char> & frame){ // Если объект с словами передан if(!frame.empty()){ // Размеры всех слов vector <size_t> sizes; // Идентификатор буквы u_int lid = 0; // Смещение в буфере size_t count = 0, offset = 0, length = 0; // Выполняем декомпрессию буфера данных auto data = df.decompress(frame); // Получаем размер данных const size_t size = data.size(); // Получаем буфер данных const char * buffer = data.data(); // Получаем размер данных length = sizeof(lid); // Получаем идентификатор буквы memcpy(&lid, buffer + offset, length); // Запоминаем смещение offset += length; // Получаем размер данных length = sizeof(count); // Получаем количество слов в блоке memcpy(&count, buffer + offset, length); // Запоминаем смещение offset += length; // Смещение в буфере размеров блоков size_t i = count; // Получаем размер данных length = sizeof(size); // Переходим по всем блокам размеров while(i > 0){ // Размер блока size_t size = 0; // Копируем размер блока memcpy(&size, buffer + offset, length); // Добавляем в массив размер блока sizes.push_back(size); // Запоминаем смещение offset += length; // Уменьшаем внутреннее смещение i--; } // Переходим по всему списку размеров for(auto it = sizes.cbegin(); it != sizes.cend(); ++it){ // Буфер слова char word[256]; // Заполняем буфер слова memset(word, 0, sizeof(word)); // Получаем размер слова const size_t wsize = (* it); // Выполняем копирование слова в буфер memcpy(word, buffer + offset, wsize); // Запоминаем смещение offset += wsize; // Добавляем слово в базу appendWord(word); } } }; // Буфер данных vector <char> data; // Буфер слова char word[256]; // Смещение в буфере size_t offset = 0, length = 0, count = 0; // Выполняем чтение данных из файла df.read(filename, data); // Если буфер не пустой if(!data.empty()){ // Получаем даныне буфера const char * buffer = data.data(); // Получаем размер буфера const size_t size = data.size(); // Размер идентификатора словаря size_t sizeId = 0; // Получаем размер данных length = sizeof(sizeId); // Считываем размер идентификатора словаря memcpy(&sizeId, buffer + offset, length); // Увеличиваем смещение offset += length; // Если размер идентификатора словаря существует if(sizeId > 0){ // Заполняем буфер слова нулями memset(word, 0, sizeof(word)); // Считываем данные идентификатора memcpy(word, buffer + offset, sizeId); // Увеличиваем смещение offset += sizeId; // Устанавливаем идентификатор словаря this->setId(word); } // Количество альтернативных букв size_t sizeAlternative = 0; // Считываем количество альтернативных букв memcpy(&sizeAlternative, buffer + offset, length); // Увеличиваем смещение offset += length; // Если количество альтернативных букв больше 0 if(sizeAlternative > 0){ // Буква и альтернативная буква u_int letter = 0, aletter = 0, ptr = 0; // Запоминаем размер буквы length = sizeof(letter); // Смещение в буфере альтернативных букв size_t i = (sizeAlternative * 2); // Очищаем список альтернативных букв this->alphabet->clearAlternative(); // Считываем альтернативные буквы до тех пор пока все не будут прочитаны while(i > 0){ // Увеличиваем смещение букв ptr++; // Считываем идентификатор буквы if(ptr % 2) memcpy(&letter, buffer + offset, length); // Считываем альтернативный идентификатор буквы else memcpy(&aletter, buffer + offset, length); // Увеличиваем смещение offset += length; // Если обе буквы получены if((letter > 0) && (aletter > 0)){ // Добавляем альтернативные слова в список this->alphabet->addAlternative(this->alphabet->lidToLetter(letter), this->alphabet->lidToLetter(aletter)); // Очищаем обе буквы letter = 0; aletter = 0; } // Уменьшаем внутреннее смещение i--; } } // Получаем размер данных length = sizeof(count); // Считываем количество блоков memcpy(&count, buffer + offset, length); // Увеличиваем смещение offset += length; // Если количество блоков получено if(count > 0){ // Смещение в буфере размеров блоков size_t i = count; // Размер всех блоков vector <size_t> sizes; // Получаем размер данных length = sizeof(sizeId); // Переходим по всем блокам размеров while(i > 0){ // Размер блока size_t size = 0; // Копируем размер блока memcpy(&size, buffer + offset, length); // Добавляем в массив размер блока sizes.push_back(size); // Запоминаем смещение offset += length; // Уменьшаем внутреннее смещение i--; } // Блок данных vector <char> frame; // Переходим по всем размерам и считываем блоки данных for(auto it = sizes.cbegin(); it != sizes.cend(); ++it){ // Очищаем блок данных frame.clear(); // Размер блока const size_t size = (* it); // Выполняем чтение данных блока frame.insert(frame.end(), buffer + offset, buffer + (offset + size)); // Формируем результат createResult(frame); // Запоминаем смещение offset += size; } } } } } // Выводим результат return move(result); } /** * parserXmlTag Метод парсинга XML файла по указанным тегам * @param buffer буфер данных для парсинга * @param key ключ поиска параметра * @return список полученных слов */ const map <u_int, vector <string>> morph::Converter::parserXmlTag(const vector <char> & buffer, const string & key) const { // Результат работы функции map <u_int, vector <string>> result; // Если буфер данных передан if(!buffer.empty() && !key.empty()){ // Результат работы регулярного выражения wsmatch match; /** * appendWord Функция добавления слова в результирующий список * @param word слово для добавления */ auto appendWord = [&result, this](const wstring & word){ // Если слово для добавления передано if(!word.empty()){ // Получаем строку в нижнем регистре const wstring & str = trim(this->alphabet->toLower(word)); // Получаем строку слова const string & word = this->alphabet->toString(str); // Переводим букву в нижний регистр const wstring & letter = str.substr(0, 1); // Выполняем копирование слова const u_int lid = this->alphabet->letterToLid(letter); // Если буква в списке найдена if(result.count(lid) > 0){ // Добавляем в список result.find(lid)->second.push_back(word); // Выполняем запись в память } else result.insert({lid, {word}}); // Выводим в консоль сообщение if(this->params & OPT_CONSOLE) printf("Received the word: %s\r\n", word.c_str()); } }; // Строка для поиска wstring str = this->alphabet->toWstring(string(buffer.data(), buffer.size())); // Формируем регулярное выражение const wstring & rgx = this->alphabet->strFormat(L"<%ls[\\s\\\"\\w\\=]+>([^\\d\\r\\n\\t\\\"<>]+)<\\/%ls>", key.c_str(), key.c_str()); // Выполняем обработку XML текста while(true){ // Выполняем проверку regex_search(str, match, wregex(rgx, regex::ECMAScript | regex::icase)); // Если результат найден if(!match.empty()){ // Получаем первую строку const wstring & first = match[0].str(); // Получаем вторую строку const wstring & second = trim(match[1].str()); // Выполняем поиск первого слова const size_t pos = str.find(first); // Если слово найдено if(pos != wstring::npos) str.replace(0, pos + first.size(), L""); // Добавляем слово в список appendWord(second); // Если больше ничего не найдено то выходим } else break; } // Если результат получен if(!result.empty()){ // Переходим по списку полученных букв for(auto it = result.begin(); it != result.end(); ++it){ // Выполняем сортировку списка sort(it->second.begin(), it->second.end()); // Удаляем все повторяющиеся элементы в списке it->second.erase(unique(it->second.begin(), it->second.end()), it->second.end()); } } } // Выводим результат return move(result); } /** * parserXmlParam Метод парсинга XML файла по указанным параметрам * @param buffer буфер данных для парсинга * @param key ключ поиска параметра * @return список полученных слов */ const map <u_int, vector <string>> morph::Converter::parserXmlParam(const vector <char> & buffer, const string & key) const { // Результат работы функции map <u_int, vector <string>> result; // Если буфер данных передан if(!buffer.empty() && !key.empty()){ // Строка полутекста string tmp = ""; // Смещение в буфере данных size_t offset = 0; // Получаем размер буфера const size_t size = buffer.size(); /** * appendWord Функция добавления слова в результирующий список * @param word слово для добавления */ auto appendWord = [&result, this](const string & word){ // Если слово для добавления передано if(!word.empty()){ // Получаем текст в нижнем регистре const wstring & str = trim(this->alphabet->toLower(this->alphabet->toWstring(word))); // Если это не только цифры if(!this->alphabet->isNumber(str)){ // Переводим букву в нижний регистр const wstring & letter = str.substr(0, 1); // Конвертируем слово обратно в строку const string & word = this->alphabet->toString(str); // Выполняем копирование слова const u_int lid = this->alphabet->letterToLid(letter); // Если буква в списке найдена if(result.count(lid) > 0){ // Добавляем в список result.find(lid)->second.push_back(word); // Выполняем запись в память } else result.insert({lid, {word}}); // Выводим в консоль сообщение if(this->params & OPT_CONSOLE) printf("Received the word: %s\r\n", word.c_str()); } } }; // Выполняем обработку до тех пор пока все не обработаем while(offset < size){ // Размер байтов для чтения u_int bytes = (offset + BUFFER_CHUNK > size ? size - offset : BUFFER_CHUNK); // Создаем строку поиска string str(buffer.data() + offset, bytes); // Выполняем парсинг полученного текста while(true){ // Если временная переменная существует if(tmp.empty()){ // Выполняем поиск начала строки const size_t pos1 = str.find(string(" ") + key + "=\""); // Еслти буква найдена if(pos1 != string::npos){ // Если начало найдено, ищим конец const size_t pos2 = str.find("\"", pos1 + 4); // Если завершение строки найдено if(pos2 != string::npos){ // Получаем искомую строку const string & word = str.substr(pos1 + 4, pos2 - (pos1 + 4)); // Если слово найдено if(!word.empty()){ // Добавляем слово в список appendWord(word); // Удаляем из строки полученные данные str = str.replace(pos1, pos2 - pos1, ""); } // Если конечная позиция не найдена } else { // Получаем искомую строку const string & word = str.substr(pos1 + 4, bytes - (pos1 + 4)); // Создаем временную переменную tmp.append(word); // Иначе заканчиваем обход break; } // Иначе заканчиваем обход } else break; // Если переменная не пустая } else { // Если начало найдено, ищим конец const size_t pos1 = str.find("\""); // Еслти буква найдена if(pos1 != string::npos){ // Получаем искомую строку const string & word = str.substr(0, pos1); // Добавляем остаток слова tmp.append(word); // Добавляем слово в список appendWord(tmp); // Очищаем временную переменную tmp.clear(); // Иначе заканчиваем обход } else break; } } // Увеличиваем значение смещения offset += bytes; } // Если результат получен if(!result.empty()){ // Переходим по списку полученных букв for(auto it = result.begin(); it != result.end(); ++it){ // Выполняем сортировку списка sort(it->second.begin(), it->second.end()); // Удаляем все повторяющиеся элементы в списке it->second.erase(unique(it->second.begin(), it->second.end()), it->second.end()); } } } // Выводим результат return move(result); } /** * getId Метод получения идентификатора словаря * @return идентификатор словаря */ const string morph::Converter::getId() const { // Выводрим результат return this->alphabet->toString(this->id); } /** * split Метод разделения текст на слова * @param text текст для разделения * @param delim разделитель * @return список слов */ const list <string> morph::Converter::split(const string text, const string delim) const { // Результат работы функции list <string> result; // Если текст передан if(!text.empty()){ // Список слов list <wstring> words; // Получаем текст const wstring & str = this->alphabet->toWstring(trim(text)); // Разбиваем слова на строки this->alphabet->split(str, this->alphabet->toWstring(delim), words); // Если список слов получен if(!words.empty()){ // Переходим по всему списку for(auto it = words.cbegin(); it != words.cend(); ++it){ // Добавляем слово в результирующий список result.push_back(trim(this->alphabet->toString(* it))); } } } // Выводим результат return move(result); } /** * clearParams Метод сброса параметров */ void morph::Converter::clearParams(){ // Выполняем сброс параметров this->params = OPT_NULL; } /** * setId Метод установки идентификатора словаря * @param id идентификатор словаря */ void morph::Converter::setId(const string id){ // Если идентификатор передан то устанавливаем его if(!id.empty()) this->setId(this->alphabet->toWstring(id)); } /** * setKey Метод установки ключа поиска * @param key ключ поиска */ void morph::Converter::setKey(const string key){ // Если ключ передан, то устанавливаем его if(!key.empty()) this->key = key; } /** * delParams Метод удаления параметров конвертера * @param params параметры конвертера */ void morph::Converter::delParams(const u_short params){ // Если уровень передан if((params != OPT_NULL) && (this->params != OPT_NULL)){ // Формируем параметры u_int settings = this->params; // Убираем настройку settings = settings ^ params; // Если параметры больше стали чем были значит ошибка if(settings > this->params) settings = this->params; // Устанавливаем новые параметры this->params = settings; } } /** * setParams Метод установки параметров конвертера * @param params параметры конвертера */ void morph::Converter::setParams(const u_short params){ // Если параметр парсера передан, то устанавливаем его if(params != OPT_NULL){ // Устанавливаем параметры this->params = (this->params | params); // Если параметры и на запись и на добавление установлены if((this->params & OPT_TYPEWRITE) && (this->params & OPT_TYPEAPPEND)){ // Если был передан параметр на запись if(params & OPT_TYPEWRITE) this->delParams(OPT_TYPEAPPEND); // Если был передан параметр на добавление else if(params & OPT_TYPEAPPEND) this->delParams(OPT_TYPEWRITE); } // Если параметры поиска по тегам и поиска по параметрам установлены if((this->params & OPT_PARAMTAG) && (this->params & OPT_PARAMPAR)){ // Если был передан параметр поиска по тегам if(params & OPT_PARAMTAG) this->delParams(OPT_PARAMPAR); // Если был передан параметр поиска по параметрам else if(params & OPT_PARAMPAR) this->delParams(OPT_PARAMTAG); } } } /** * alternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void morph::Converter::alternative(const string letter, const string alternative){ // Если данные переданы if(!letter.empty() && !alternative.empty()){ // Добавляем альтернативную букву в алфавит this->alternative( this->alphabet->toWstring(letter), this->alphabet->toWstring(alternative) ); } } /** * del Метод удаления слова в существующем словаре * @param word слово для удаления * @param path путь к словарю * @param name название словаря */ void morph::Converter::del(const string word, const string path, const string name){ // Если входные данные переданы if(!word.empty() && !path.empty() && !name.empty()){ // Адрес файла string filename = path; // Добавляем разделитель filename.append("/"); // Добавляем идентификатор буквы filename.append(name); // Выполняем чтение данных из созданного ранее файла auto result = this->read(filename); // Если результат получен if(!result.empty()){ // Результат поиска слова bool find = false; // Получаем слово const wstring & str = trim(this->alphabet->toLower(this->alphabet->toWstring(word))); // Получаем первую букву из слова const wstring & letter = str.substr(0, 1); // Получаем букву const u_int lid = this->alphabet->letterToLid(letter); // Ищем в результирующем списке нашу букву if(result.count(lid) > 0){ // Получаем список созданных ранее слов auto words = result.find(lid); // Если список не пустой if(!words->second.empty()){ // Переходим по всему списку слов for(auto it = words->second.begin(); it != words->second.end(); ++it){ // Если слово найдено if(it->compare(trim(word)) == 0){ // Запоминаем что слово найдено find = true; // Удаляем слово из списка words->second.erase(it); // Выводим в консоль сообщение if(this->params & OPT_CONSOLE) printf("Deleted the word: %s\r\n", trim(word).c_str()); // Выходим из цикла break; } } // Если буквы в списке еще есть if(!words->second.empty()){ // Заменяем ранее существующий список result.at(lid) = words->second; // Удаляем полностью букву в словаре } else result.erase(lid); } } // Выполняем запись данных в файл if(find) this->write(result, path, name); } } } /** * del Метод удаления слов в существующем словаре * @param words слова для удаления * @param path путь к словарю * @param name название словаря */ void morph::Converter::del(const list <string> words, const string path, const string name){ // Если входные данные переданы if(!words.empty() && !path.empty() && !name.empty()){ // Адрес файла string filename = path; // Добавляем разделитель filename.append("/"); // Добавляем идентификатор буквы filename.append(name); // Выполняем чтение данных из созданного ранее файла auto result = this->read(filename); // Если результат получен if(!result.empty()){ // Результат поиска слова bool find = false; // Переходим по всему списку полученных слов for(auto it = words.begin(); it != words.end(); ++it){ // Получаем слово const wstring & word = trim(this->alphabet->toLower(this->alphabet->toWstring(* it))); // Получаем первую букву из слова const wstring & letter = word.substr(0, 1); // Получаем букву const u_int lid = this->alphabet->letterToLid(letter); // Ищем в результирующем списке нашу букву if(result.count(lid) > 0){ // Получаем список созданных ранее слов auto words = result.find(lid); // Если список не пустой if(!words->second.empty()){ // Переходим по всему списку слов for(auto jt = words->second.begin(); jt != words->second.end(); ++jt){ // Если слово найдено if(jt->compare(trim(* it)) == 0){ // Запоминаем что слово найдено find = true; // Удаляем слово из списка words->second.erase(jt); // Выводим в консоль сообщение if(this->params & OPT_CONSOLE) printf("Deleted the word: %s\r\n", trim(* it).c_str()); // Выходим из цикла break; } } // Если буквы в списке еще есть if(!words->second.empty()){ // Заменяем ранее существующий список result.at(lid) = words->second; // Удаляем полностью букву в словаре } else result.erase(lid); } } } // Выполняем запись данных в файл if(find) this->write(result, path, name); } } } /** * add Метод добавления слова в существующий словарь * @param word слово для добавления * @param path путь к словарю * @param name название словаря */ void morph::Converter::add(const string word, const string path, const string name){ // Если входные данные переданы if(!word.empty() && !path.empty() && !name.empty()){ // Адрес файла string filename = path; // Добавляем разделитель filename.append("/"); // Добавляем идентификатор буквы filename.append(name); // Выполняем чтение данных из созданного ранее файла auto result = this->read(filename); // Получаем строку слова const wstring & str = trim(this->alphabet->toLower(this->alphabet->toWstring(word))); // Получаем первую букву из слова const wstring & letter = str.substr(0, 1); // Получаем букву const u_int lid = this->alphabet->letterToLid(letter); // Ищем в результирующем списке нашу букву if(!result.empty() && (result.count(lid) > 0)){ // Получаем список созданных ранее слов auto words = result.find(lid); // Добавляем в список слов полученные слова words->second.push_back(trim(word)); // Выполняем сортировку списка sort(words->second.begin(), words->second.end()); // Удаляем все повторяющиеся элементы в списке words->second.erase(unique(words->second.begin(), words->second.end()), words->second.end()); // Заменяем ранее существующий список result.at(lid) = words->second; // Если букву не нашли тогда просто добавляем в список } else result.insert({lid, {trim(word)}}); // Выводим в консоль сообщение if(this->params & OPT_CONSOLE) printf("Received the word: %s\r\n", trim(word).c_str()); // Выполняем запись данных в файл this->write(result, path, name); } } /** * add Метод добавления слов в существующий словарь * @param words слова для добавления * @param path путь к словарю * @param name название словаря */ void morph::Converter::add(const list <string> words, const string path, const string name){ // Если входные данные переданы if(!words.empty() && !path.empty() && !name.empty()){ // Адрес файла string filename = path; // Добавляем разделитель filename.append("/"); // Добавляем идентификатор буквы filename.append(name); // Выполняем чтение данных из созданного ранее файла auto result = this->read(filename); // Переходим по всему списку полученных слов for(auto it = words.begin(); it != words.end(); ++it){ // Получаем слово const wstring & word = trim(this->alphabet->toLower(this->alphabet->toWstring(* it))); // Получаем первую букву из слова const wstring & letter = word.substr(0, 1); // Получаем букву const u_int lid = this->alphabet->letterToLid(letter); // Ищем в результирующем списке нашу букву if(!result.empty() && (result.count(lid) > 0)){ // Получаем список созданных ранее слов auto words = result.find(lid); // Добавляем в список слов полученные слова words->second.push_back(trim(* it)); // Выполняем сортировку списка sort(words->second.begin(), words->second.end()); // Удаляем все повторяющиеся элементы в списке words->second.erase(unique(words->second.begin(), words->second.end()), words->second.end()); // Заменяем ранее существующий список result.at(lid) = words->second; // Если букву не нашли тогда просто добавляем в список } else result.insert({lid, {trim(* it)}}); // Выводим в консоль сообщение if(this->params & OPT_CONSOLE) printf("Received the word: %s\r\n", trim(* it).c_str()); } // Выполняем запись данных в файл this->write(result, path, name); } } /** * convert Метод конвертация стороннего корпуса в бинарный корпус * @param file путь к файлу корпуса * @param path путь где хранится сконвертированный корпус * @param dir каталог в котором находятся xml файлы * @param ext расширение корпуса (по умолчанию xml) * @param name название корпуса (идентификатор словаря) */ void morph::Converter::convert(const string file, const string path, const string dir, const string ext, const string name){ // Определяем начальное время const time_t start = time(nullptr); // Если параметры для конвертирования файла переданы if(!path.empty() && !file.empty() && !name.empty()){ // Выполняем конвертирование файла this->convertFile(file, path, name); // Если параметры для конвертирования дирректории с файлами переданы } else if(!path.empty() && !name.empty() && !dir.empty() && !ext.empty()) { // Выполняем конвертирование группы файлов this->convertFiles(path, name, dir, ext); } // Если вывод в консоль информации разрешен if(this->params & OPT_CONSOLE){ // Определяем конечное время const time_t end = time(nullptr); // Выводим информацию о времени конвертации printf("\r\nCorpus convert time: %ld min.\r\n\r\n", ((end - start) / 60)); } } /** * Converter Конструктор * @param params параметры конвертера */ morph::Converter::Converter(const u_short params){ try { // Объявляем алфавит this->alphabet = new Alphabet; // Добавляем параметры если они переданы if(params != OPT_NULL) this->setParams(params); // Если происходит ошибка то игнорируем её } catch(const bad_alloc&) { // Выходим из приложения exit(SIGSEGV); } } /** * ~Converter Деструктор */ morph::Converter::~Converter(){ // Если алфавит создан тогда удаляем его if(this->alphabet != nullptr) delete this->alphabet; } <file_sep>/dpa.hpp #ifndef _STK_MORPH_ #define _STK_MORPH_ #include <map> #include <set> #include <list> #include <regex> #include <ctime> #include <queue> #include <string> #include <vector> #include <memory> #include <locale> #include <fstream> #include <codecvt> #include <iostream> #include <algorithm> #include <unordered_map> #include <zlib.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <dirent.h> #include <signal.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include "levenshtein.hpp" // Размер чанка буфера для чтения из файла #define BUFFER_CHUNK 0x1000 // Основные флаги прокси сервера #define OPT_NULL (0 << 0) // Флаг устанавливающий пустые данные #define OPT_ONELETTER (1 << 0) // Флаг разрешающий проверять только одну неправильную букву #define OPT_SEVERALLETTER (1 << 1) // Флаг разрешающий проверять несколько неправильных букв #define OPT_ALTERNATIVE (1 << 2) // Флаг разрешающий проверку наличия альтернативной буквы #define OPT_HYPHENTRUE (1 << 3) // Флаг разрешающий проверку наличия дефиза в правильном слове #define OPT_HYPHENFALSE (1 << 4) // Флаг разрешающий проверку наличия дефиза в неправильном слове #define OPT_UNIONTRUE (1 << 5) // Флаг разрешающий проверку слитых правильных слов #define OPT_UNIONFALSE (1 << 6) // Флаг разрешающий проверку слитых неправильных слов #define OPT_CHECKSPACES (1 << 7) // Флаг разрешающий проверку слов разделенных пробелом // Параметры Zlib #define MOD_GZIP_ZLIB_WINDOWSIZE 15 #define MOD_GZIP_ZLIB_CFACTOR 9 #define MOD_GZIP_ZLIB_BSIZE 8096 // Пороги определения схожести #define THRESHOLD_WORD 0.40; // Порог принятия нечеткой эквивалентности между двумя словами; #define SUBTOKEN_LENGTH 2; // Размер подстроки при сравнении двух слов (от 1 до Минимального размера слова [3]) // Устанавливаем область видимости using namespace std; /* * AHttp пространство имен */ namespace morph { /** * DPA Класс модуля исправления опечаток */ class DPA { private: /** * Alphabet Класс для работы с алфавитом */ class Alphabet { private: // Список альтернативных букв map <u_int, u_int> alternatives; // Алфавит для проверки set <u_int> letters; public: /** * cbegin Метод итератор начала списка * @return итератор */ const set <u_int>::iterator cbegin() const; /** * cend Метод итератор конца списка * @return итератор */ const set <u_int>::iterator cend() const; /** * crbegin Метод обратный итератор начала списка * @return итератор */ const set <u_int>::reverse_iterator crbegin() const; /** * crend Метод обратный итератор конца списка * @return итератор */ const set <u_int>::reverse_iterator crend() const; /** * Метод получения списка альтернативных букв * return список альтернативных букв */ const map <u_int, u_int> getAlternatives() const; /** * lettersByText Метод получения списка букв в слове * @param word слово для обработки * @return список букв */ const list <wstring> lettersByText(const wstring & word) const; /** * replace Метод замены в тексте слово на другое слово * @param text текст в котором нужно произвести поиск * @param word слово для поиска * @param alt слово на которое нужно произвести замену * @return результирующий текст */ const wstring replace(const wstring text, const wstring word, const wstring alt = L"") const; /** * lidToLetter Метод перевода цифрового идентификатора буквы в букву * @param lid идентификатор буквы * @return буква в текстовом виде */ const wstring lidToLetter(const u_int lid) const; /** * getAlternative Метод получения альтернативной буквы * @param letter буква для проверки * @return альтернативная буква */ const wstring getAlternative(const wstring & letter) const; /** * getRealLetter Метод получения реальной буквы из альтернативной * @param alternative альтернативная буква * @return реальная буква */ const wstring getRealLetter(const wstring & alternative) const; /** * toString Метод конвертирования строки utf-8 в строку * @param str строка utf-8 для конвертирования * @return обычная строка */ const string toString(const wstring & str) const; /** * toWstring Метод конвертирования строки в строку utf-8 * @param str строка для конвертирования * @return строка в utf-8 */ const wstring toWstring(const string & str) const; /** * toLower Метод перевода русских букв в нижний регистр * @param str строка для перевода * @return строка в нижнем регистре */ const wstring toLower(const wstring & str) const; /** * toUpper Метод перевода русских букв в верхний регистр * @param str строка для перевода * @return строка в верхнем регистре */ const wstring toUpper(const wstring & str) const; /** * isNumber Метод проверки является ли строка числом * @param str строка для проверки * @return результат проверки */ const bool isNumber(const wstring & str) const; /** * letterToLid Метод перевода буквы в цифровой идентификатор * @param letter буква для конвертации * @return идентификатор буквы */ const u_int letterToLid(const wstring & letter) const; /** * count Метод получения количества букв в словаре * @return количество букв в словаре */ const size_t count() const; /** * find Метод поиска текста без учета регистра * @param text1 текст в котором нужно найти другой текст * @param text2 текст который нужно найти * @return позиция первого символа найденного текста */ const size_t find(const wstring & text1, const wstring & text2) const; /** * similarity Метод проверки схожести двух текстов * @param text1 первый текст для проверки * @param text2 второй текст для проверки * @return результат проверки */ const bool similarity(const wstring & text1, const wstring & text2) const; /** * check Метод проверки соответствии буквы * @param letter буква для проверки * @return результат проверки */ const bool check(const wstring & letter) const; /** * isCase Метод определения регистра первого символа в строке * @param str строка для проверки * @return регистр символов (true - верхний, false - нижний) */ const bool isCase(const wstring & str) const; /** * isAlternative Метод проверки существования альтернативной буквы * @param letter буква для проверки * @return результат проверки */ const bool isAlternative(const wstring & letter) const; /** * split Метод разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void split(const wstring & str, const wstring delim, list <wstring> & v) const; /** * uppLetterWord Метод перевода первого символа в строке в верхний регистр * @param str строка для перевода */ void uppLetterWord(wstring & str) const; /** * clearBadChar Метод очистки текста от всех символов кроме русских * @param str строка для очистки */ void clearBadChar(wstring & str); /** * add Метод добавления буквы в алфавит * @param letter буква для добавления */ void add(const wstring & letter); /** * clearAlternative Метод удаления альтернативной буквы * @param letter буква у которой есть альтернативная буква */ void clearAlternative(const wstring letter = L""); /** * addAlternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void addAlternative(const wstring & letter, const wstring & alternative); }; /** * Df Класс для работы с каталогами и файлами */ struct Df { /** * compress Метод сжатия данных * @param buffer буфер данных для сжатия * @return результат сжатия */ const vector <char> compress(const vector <char> & buffer) const; /** * decompress Метод рассжатия данных * @param buffer буфер данных для расжатия * @return результат расжатия */ const vector <char> decompress(const vector <char> & buffer) const; /** * read Метод чтения данных из файла * @param filename адрес файла * @param buffer буфер данных для чтения */ void read(const string & filename, vector <char> & buffer) const; /** * write Метод записи данных в файл * @param filename адрес файла * @param buffer буфер данных для записи */ void write(const string & filename, vector <char> & buffer) const; /** * mkdir Метод рекурсивного создания каталогов * @param path адрес каталогов */ void mkdir(const string & path) const; }; /** * Stk Класс базы морфологического словаря */ class Stk { private: // Конец слова bool end = false; // Корректор буквы ё bool isalter = false; // Буква структуры u_int letter = 0; // Количество потомков size_t descendants = 0; // Алфавит Alphabet * alphabet = nullptr; // Список наследников map <u_int, void *> children; /** * checkCount Метод получения количества потомков * @param ref эталон для проверки * @param word слово для поиска * @return результат проверки */ const size_t checkCount(const wstring & ref, wstring word = L"") const; /** * count Метод получения количества потомков * @param ref эталон для проверки * @param ctx объект структуры для поиска * @param word слово для поиска * @return результат проверки */ const size_t count(const wstring & ref, void * ctx = nullptr, wstring word = L"") const; /** * checkNext Метод проверки следующего слова * @param ref эталон для проверки * @param word слово для поиска * @return результат проверки */ const bool checkNext(const wstring & ref, wstring word = L"") const; /** * check Метод проверки существования слова * @param ref эталон для проверки * @param ctx объект структуры для поиска * @param word слово для поиска * @return результат проверки */ const bool check(const wstring & ref, void * ctx = nullptr, wstring word = L"") const; /** * add Метод добавления букв в базу * @param word часть слова для добавления * @param ctx объект на следующий элемент структуры */ void add(queue <wstring> & word, void * ctx = nullptr); /** * removeNext Метод удаления следующего слова * @param ref эталон для проверки * @param word слово для удаления */ void removeNext(const wstring & ref, wstring word = L""); /** * findNext Метод поиска следующего слова * @param ref эталон для проверки * @param words список результат поиска * @param depth глубина поиска (количество букв которые отличаются) * @param max максимальное количество слов для отдачи * @param word слово для поиска */ void findNext(const wstring & ref, list <wstring> & words, const u_short depth, const size_t max, wstring word = L"") const; /** * remove Метод удаления подходящих слов * @param ref эталон для проверки * @param ctx объект структуры для поиска * @param word слово для поиска */ void remove(const wstring & ref, void * ctx = nullptr, wstring word = L""); /** * find Метод поиска подходящих слов * @param ref эталон для проверки * @param words список результат поиска * @param ctx объект структуры для поиска * @param depth глубина поиска (количество букв которые отличаются) * @param max максимальное количество слов для отдачи * @param word слово для поиска */ void find(const wstring & ref, list <wstring> & words, void * ctx = nullptr, const u_short depth = 0, const size_t max = 0, wstring word = L"") const; public: /** * count Метод получения количество дочерних элементов * @return количество дочерних элементов */ const size_t count() const; /** * countWord Метод получения количество потомков * @param word слово для проверки * @return результат проверки */ const size_t countWord(const wstring & word); /** * getLetter Метод получения буквы * @return хранимая буква */ const wstring getLetter() const; /** * findWords Метод поиска подходящих слов * @param word эталон для проверки * @param depth глубина поиска (количество букв которые отличаются) * @param max максимальное количество слов для отдачи * @param parent родительский объект * @return список результат поиска */ const list <wstring> findWords(const wstring & word, const u_short depth = 0, const size_t max = 0, void * parent = nullptr); /** * getStkByLetter Метод получения объекта * @param letter буква для поиска * @return результат работы метода */ void * getStkByLetter(const wstring & letter); /** * isEnd Метод проверки на конец слова * @return результат проверки */ const bool isEnd() const; /** * checkLetter Метод проверки на существование буквы * @param letter буква * @return результат проверки */ const bool checkLetter(const wstring & letter) const; /** * checkWord Метод проверки существования слова * @param word слово для проверки * @return результат проверки */ const bool checkWord(const wstring & word); /** * clear Метод очистки структуры */ void clear(); /** * delAlternative Метод деактивации корректора альтернативной буквы */ void delAlternative(); /** * setAlternative Метод активации корректора буквы альтернативной буквы */ void setAlternative(); /** * setLetter Метод добавления буквы * @param letter буква для добавления * @param end завершение работы */ void setLetter(const wstring & letter, const bool end); /** * addWord Метод добавления слова * @param word строка без пробелов (слово должно быть без опечаток) */ void addWord(const wstring & word); /** * deleteWords Метод удаления похожих слов * @param word слово для поиска */ void deleteWords(const wstring & word); /** * Stk Конструктор * @param alphabet объект алфавита */ Stk(Alphabet * alphabet = nullptr); /** * ~Stk Деструктор */ ~Stk(); }; /** * Структура для данных замены */ struct Rdata { // Регистр первой буквы bool icase; // Значение слов list <wstring> words; }; // Идентификатор словаря wstring id = L""; // Уровень проверки u_short level = OPT_NULL; // Алфавит Alphabet * alphabet = nullptr; // Список всех букв map <u_int, Stk *> letters; /** * count Метод получения количества потомков * @param word слово для удаления */ const size_t count(const wstring & word) const; /** * check Метод проверки существования слова * @param word слово для проверки * @return результат проверки */ const bool check(const wstring & word) const; /** * checkLevel Метод проверки уровня проверок * @param level уровень проверки * @return результат проверки */ const bool checkLevel(const u_short level = OPT_NULL) const; /** * test Метод проверки текста на соответствие словарю * @param text текст для проверки * @return результат проверки */ const bool test(const wstring & text) const; /** * directException Метод прямого исключения * @param word слово для поиска * @return результат работы функции */ const wstring directException(const wstring & word); /** * bruteCompare Метод поиска наиболее подходящего слова в списке вариантов * @param word оригинальное слово * @param words список вариантов слов * @return наиболее подходящее слово */ const wstring bruteCompare(const wstring & word, const list <wstring> & words); /** * brutePicking Метод поиска слова методом подстановки * @param word слово для поиска * @param depth глубина поиска * @return искомое слово */ const wstring brutePicking(const wstring & word, const size_t depth = 0); /** * bruteForce Метод поиска слова методом перебора * @param word слово для поиска * @return найденное слово */ const wstring bruteForce(const wstring & word); /** * bruteHyphen Метод поиска слова методом переноса дефиза * @param word слово для поиска * @return результат поиска */ const wstring bruteHyphen(const wstring & word); /** * find Метод поиска подходящего слова * @param word слово для поиска * @param brute выполнять предварительную проверку перебором вариантов * @result результат работы функции */ const wstring find(const wstring & word, const bool brute = false); /** * search Метод поиска наиболее подходящего слова * @param etalon слово для поиска * @param first первое слово для поиска * @return ископоме слово */ const wstring search(const wstring & etalon, const wstring & first = L""); /** * bruteNotSpace Метод разделения текста на слова * @param text текст для разбора * @return слово полученное при разборе */ const pair <wstring, wstring> bruteNotSpace(const wstring & text); /** * bruteSpace Метод проверки разделенных слов * @param text текст для обработки * @return список обнаруженных слов */ const unordered_map <wstring, Rdata> bruteSpace(const wstring & text); /** * checkSpace Метод проверки слова на наличие пробела * @param word текст для обработки * @return список обнаруженных вариантов слов */ const list <wstring> checkSpace(const wstring & word); /** * bruteForceVariants Метод поиска вариантов слова методом перебора * @param word слово для поиска * @param limit количество вариантов * @return найденные варианты слов */ const list <wstring> bruteForce(const wstring & word, const u_int limit); /** * brutePicking Метод поиска слова методом подстановки * @param word слово для поиска * @param depth глубина поиска * @return искомое слово */ const list <wstring> brutePicking(const wstring & word, const u_int limit, const size_t depth = 0); /** * getBlock Метод получения бинарного блока слов из списка слов * @param letter буква на которую нужно получить бинарный блок данных * @param список слов из которых нужно получить бинарный блок * @return бинарный блок данных */ const vector <char> getBlock(const wstring & letter, const vector <string> & words); /** * getBlock Метод получения бинарного блока слов из базы данных * @param letter буква на которую нужно получить бинарный блок данных * @return бинарный блок данных */ const vector <char> getBlock(const wstring & letter); /** * split Метод разделения текст на слова * @param text текст для разделения * @return список слов */ const list <wstring> split(const wstring & text) const; /** * search Метод поиска наиболее подходящих слов * @param word слово для поиска * @param limit количество вариантов на слово с ошибкой * @return список найденных вариантов */ const list <wstring> search(const wstring & word, const u_int limit); /** * find Метод поиска подходящего слова * @param word слово для поиска * @param limit количество вариантов на слово с ошибкой * @param brute выполнять предварительную проверку перебором вариантов * @return результат работы функции */ const list <wstring> find(const wstring & word, const u_int limit, const bool brute = false); /** * revalt Метод подстановку альтернативной буквы * @param word слово для корректировки */ void revalt(wstring & word); /** * setId Метод установки идентификатора словаря * @param id идентификатор словаря */ void setId(const wstring & id); /** * clause Метод добавления целых предложений (слова должны быть истинными) * @param clause текст на русском языке (не отформатированный) */ void clause(const wstring & clause); /** * del Метод удаления слова * @param word слово для удаления */ void del(const wstring & word); /** * set Метод вставки слова * @param word слово для вставки */ void set(const wstring & word); /** * get Метод чтения слова * @param word слово для поиска * @param words список результат поиска * @param offset дистанция поиска (количество букв которые отличаются) * @param limit максимальное количество слов для отдачи */ void get(const wstring & word, list <wstring> & words, const u_short offset = 2, const size_t limit = 10); /** * alternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void alternative(const wstring & letter, const wstring & alternative); /** * setBlock Метод добавления блока слов в базу данных * @param frame блок слов в бинарном виде * @param info информировать о добавлении слов */ void setBlock(const vector <char> * frame = nullptr, const bool info = false); /** * correct Метод корректировки текста * @param text текст для корректировки * @param info список слов для которых выполнена коррекция */ void correct(wstring & text, list <pair <wstring, wstring>> * info = nullptr); /** * analyze Метод проведения анализа текста * @param text текст для проведения анализа * @param limit количество вариантов на слово с ошибкой * @param info список слов для которых выполнена коррекция */ void analyze(const wstring & text, const u_int limit = 1, list <pair <wstring, list <wstring>>> * info = nullptr); public: /** * getId Метод получения идентификатора словаря * @return идентификатор словаря */ const string getId() const; /** * count Метод получения количества потомков * @param word слово для удаления */ const size_t count(const string word) const; /** * check Метод проверки существования слова * @param word слово для проверки * @return результат проверки */ const bool check(const string word) const; /** * test Метод проверки текста на соответствие словарю * @param text текст для проверки * @return результат проверки */ const bool test(const string & text) const; /** * setId Метод установки идентификатора словаря * @param id идентификатор словаря */ void setId(const string id); /** * clause Метод добавления целых предложений (слова должны быть истинными) * @param clause текст на русском языке (не отформатированный) */ void clause(const string clause); /** * del Метод удаления слова * @param word слово для удаления */ void del(const string word); /** * set Метод вставки слова * @param word слово для вставки */ void set(const string word); /** * get Метод чтения слова * @param word слово для поиска * @param words список результат поиска * @param offset дистанция поиска (количество букв которые отличаются) * @param limit максимальное количество слов для отдачи */ void get(const string word, list <string> & words, const u_short offset = 2, const size_t limit = 10); /** * alternative Метод добавления альтернативной буквы * @param letter буква у которой есть альтернатива * @param alternative альтернативная буква */ void alternative(const string letter, const string alternative); /** * correct Метод корректировки текста * @param text текст для корректировки * @param info список слов для которых выполнена коррекция */ void correct(string & text, list <pair <string, string>> * info = nullptr); /** * analyze Метод проведения анализа текста * @param text текст для проведения анализа * @param limit количество вариантов на слово с ошибкой * @param info список слов для которых выполнена коррекция */ void analyze(const string & text, const u_int limit = 1, list <pair <string, list <string>>> * info = nullptr); /** * read Метод чтения корпуса * @param file файл корпуса без расширения */ void read(const string file); /** * write Метод записи корпуса * @param path адрес где будет хранится файл корпуса */ void write(const string path); /** * delLevel Метод удаления уровня * @param level уровень проверки */ void delLevel(const u_short level = OPT_NULL); /** * setLevel Метод установки уровня проверки * @param level уровень проверки */ void setLevel(const u_short level = OPT_NULL); /** * DPA Конструктор * @param level уровень проверки */ DPA(const u_short level = OPT_NULL); /** * ~DPA Деструктор */ ~DPA(); }; }; #endif // _STK_MORPH_ <file_sep>/tools/README.md # Конвертер корпусов (C++11) Конвертирование корпусов в бинарные словари для системы исправления опечатков, поддерживаются только **xml** корпуса ## Сборка и запуск: ### MacOS X: ``` # make # make start ``` ### Linux: ``` # make # make start ``` ### FreeBSD: ``` # gmake # gmake start ``` > Для работы "demo" необходимо установить пакет **[Zlib](http://www.zlib.net)** ## Документация: ### Параметры сборки * **ext** - Расширение файлов корпусов которые необходимо обработать.<br><br> * **dir** - Каталог где расположены группы файлов корпусов для обработки.<br><br> * **key** - Установка ключа поиска (название параметра или название тега содержащего текст).<br><br> * **alt** - Альтернативная буква которая имеет дублирующее значение, например для русского языка буква (Ё).<br><br> * **name** - Название словаря.<br><br> * **mode** - Выполнять запись новых данных в файл или добавление.<br><br> * **words** - Список слов для добавления или удаления из словаря.<br><br> * **corpus** - Путь к фалу корпуса.<br><br> * **parser** - Парсить слова по тегам или параметрам.<br><br> * **prefix** - Адрес по которому будет сохранен собранный словарь.<br><br> * **method** - Метод работы конвертера (Конвертирование корпусов, Удаление слов, Добавление слов).<br><br> * **verbose** - Выводить информацию о добавлении слов в консоль.<br><br> ### Пример #### Удаление одного слова ```bash $ ./convert --prefix=./ --name=en --verbose --method=del --words=mir ``` #### Добавление группы слов ```bash $ ./convert --prefix=./ --name=ru --verbose --method=add --words=чувак,клёвый ``` #### Сборка из множества файлов корпуса ```bash $ ./convert --key=w --prefix=./ --dir=./Texts --ext=xml --name=en --verbose --parser=tag --mode=append --method=conv ``` #### Сборка из одного файла корпуса ```bash $ ./convert --key=t --corpus=./dict.opcorpora.xml --prefix=./ --name=ru --alt=е/ё --verbose --parser=param --mode=write --method=conv ``` <file_sep>/levenshtein.cpp #include "levenshtein.hpp" // Устанавливаем пространство имен using namespace std; /** * minimum Метод определения минимального значения * @param x первое число * @param y второе число * @param z третье число * @return самое минимальное значение из 3-х чисел */ const size_t morph::LD::minimum(const size_t x, const size_t y, const size_t z){ // Определяем минимальное значение return min(min(x, y), z); } /** * matrix Метод создания матриц * @param row количество строк * @param col количество столбцов * @return созданная матрица */ size_t ** morph::LD::matrix(const size_t row, const size_t col){ // Таблица матрицы size_t ** table = nullptr; // Если размеры матрицы переданы if((row > 0) && (col > 0)){ try { // Выделяем динамически память для строк в таблице table = new size_t * [row]; // Создаем нужное нам количество столбцов в таблице for(size_t i = 0; i < row; ++i) table[i] = new size_t [col]; // Если происходит ошибка то игнорируем её } catch(const bad_alloc&) {} } // Выводим созданную таблицу return move(table); } /** * free Метод очистки матрицы * @param matrix матрица для очистки * @param row количество строк */ void morph::LD::free(size_t ** matrix, const size_t row){ // Если матрица передана if((matrix != nullptr) && (row > 0)){ // Переходим по всем строкам for(size_t i = 0; i < row; i++) delete [] matrix[i]; // Удаляем саму матрицу delete [] matrix; } } /** * tanimoto Метод определения коэффициента Жаккара (частное — коэф. Танимото) * @param first первое слово * @param second второе слово * @param stl размер подстроки при сравнении двух слов (от 1 до минимального размера слова) * @return коэффициент Танимото */ const float morph::LD::tanimoto(const wstring & first, const wstring & second, const u_short stl){ // Результат работы функции float result = 0.0; // Если первое и второе слово переданы if(!first.empty() && !second.empty()){ try { // Количество эквивалентных подстрок float esubCount = 0.0; // Получаем размер подстроки const u_short subToken = (stl > 1 ? stl : 1); // Получаем количество символов в первом слове const size_t fsize = first.length(); // Получаем количество символов во втором слове const size_t ssize = second.length(); // Получаем размер первой подстроки const size_t subfCount = ((fsize - subToken) + 1); // Получаем размер второй подстроки const size_t subsCount = ((ssize - subToken) + 1); // Выделяем динамически память bool * tokens = new bool[(const size_t) ssize - (subToken + 1)]; // Переходим по всем буквам первого слова for(size_t i = 0; i < subfCount; ++i){ // Получаем подстроку первого слова const wstring & subFirst = first.substr(i, subToken); // Переходим по всем буквам второго слова for(size_t j = 0; j < subsCount; ++j){ // Если подстроки не совпадают if(!tokens[j]){ // Получаем подстроку второго слова const wstring & subSecond = second.substr(j, subToken); // Если подстроки совпадают if(subFirst.compare(subSecond) == 0){ // Увеличиваем количество эквивалентных подстрок esubCount++; // Запоминаем что подстроки совпадают tokens[j] = true; // Выходим из цикла break; } } } } // Выполняем расчет коэффициента Танимото result = esubCount / (float(subfCount + subsCount) - esubCount); // Удаляем выделенную ранее память delete [] tokens; // Если происходит ошибка то игнорируем её } catch(const bad_alloc&) {} } // Выводим результат return move(result); } /** * tanimoto Метод определения коэффициента Жаккара (частное — коэф. Танимото) * @param first первое слово * @param second второе слово * @param stl размер подстроки при сравнении двух слов (от 1 до минимального размера слова) * @return коэффициент Танимото */ const float morph::LD::tanimoto(const string & first, const string & second, const u_short stl){ // Результат работы функции float result = 0.0; // Если первое и второе слово переданы if(!first.empty() && !second.empty()){ // Объявляем конвертер wstring_convert <codecvt_utf8 <wchar_t>> conv; // Конвертируем строки const wstring & text1 = conv.from_bytes(first); const wstring & text2 = conv.from_bytes(second); // Выводим расчет result = this->tanimoto(text1, text2, stl); } // Выводим результат return move(result); } /** * distance Определение дистанции в фразах * @param pattern шаблон с которым идет сравнение * @param text исходный текст * @return дистанция */ const size_t morph::LD::distance(const wstring & pattern, const wstring & text){ // Результат работы функции size_t result = 0; // Если шаблон для сравнения и исходный текст переданы if(!pattern.empty() && !text.empty()){ // Конвертируем строки const wstring txt = text; const wstring ptr = pattern; // Определяем размер исходного текста const size_t txtlen = txt.length(); // Определяем размер шаблона const size_t ptrlen = ptr.length(); // Если исходный текст не передан, то разница в длину шаблона if(txtlen == 0) return ptrlen; // Если шаблон не передан, то разница в длину исходного текста else if(ptrlen == 0) return txtlen; // Выполняем создание матрицы size_t ** table = this->matrix(ptrlen + 1, txtlen + 1); // Если таблица создана if(table != nullptr){ // Заполняем столбцы в нулевой строке таблицы for(size_t i = 0; i <= txtlen; ++i) table[0][i] = i; // Заполняем строки в таблице for(size_t i = 0; i <= ptrlen; ++i) table[i][0] = i; // Переменные для измерения дистанции Левенштейна size_t aboveCell, leftCell, diagonalCell, cost; // Получаем строку исходного текста const wchar_t * ctxt = txt.c_str(); // Получаем строку шаблона const wchar_t * cptr = ptr.c_str(); // Переходим по всем строкам начиная с 1-й строки for(size_t i = 1; i <= ptrlen; ++i){ // Переходим по всем столбцам начиная с 1-го столбца for(size_t j = 1; j <= txtlen; ++j){ // Если текущие два символа обеих строк одинаковы, то значение стоимости будет равна 0, иначе будет 1 if(ptr[i - 1] == txt[j - 1]) cost = 0; else cost = 1; // Находим указанную ячейку в текущей ячейке aboveCell = table[i - 1][j]; // Находим левую ячейку в текущей ячейке leftCell = table[i][j - 1]; // Находим диагональную ячейку в текущей ячейке diagonalCell = table[i - 1][j - 1]; // Вычисляем текущее значение (редактируемое расстояние) и результат в текущей ячейки матрицы table[i][j] = this->minimum(aboveCell + 1, leftCell + 1, diagonalCell + cost); } } // Определяем результат (что и есть расстояние Левенштейна) result = table[ptrlen][txtlen]; // Удаляем выделенную ранее память this->free(table, ptrlen + 1); } } // Выводим результат return move(result); } /** * distance Определение дистанции в фразах * @param pattern шаблон с которым идет сравнение * @param text исходный текст * @return дистанция */ const size_t morph::LD::distance(const string & pattern, const string & text){ // Результат работы функции size_t result = 0; // Если шаблон для сравнения и исходный текст переданы if(!pattern.empty() && !text.empty()){ // Объявляем конвертер wstring_convert <codecvt_utf8 <wchar_t>> conv; // Конвертируем строки const wstring & txt = conv.from_bytes(text); const wstring & ptr = conv.from_bytes(pattern); // Выводим результат result = this->distance(ptr, txt); } // Выводим результат return move(result); }
44848258dd6f78796d621331a2a90cb2bfc527f1
[ "Markdown", "Makefile", "C++" ]
11
C++
anyks/misprint
d134d5bba74c8394cbb76274dd3815a268129837
707a6437c09ff2500b1228e084eca663bab78568
refs/heads/master
<file_sep>package app.robo.com.getgit; import android.content.Context; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONObject; class JSONObjRequest { public static void getData(int method, Context context, String url, Response.Listener<JSONObject> listenerResponse, Response.ErrorListener listenerError) { JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, listenerResponse, listenerError); Volley.newRequestQueue(context).add(request); } }<file_sep>package app.robo.com.getgit; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.app.NavUtils; import android.support.v4.view.GravityCompat; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.CardView; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.GridLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.support.v7.widget.ShareActionProvider; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.google.gson.Gson; import com.squareup.picasso.Picasso; import org.w3c.dom.Text; public class NavRepoActivity extends AppCompatActivity { private ShareActionProvider shareActionProvider; String url; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_repos); Toolbar toolbar = findViewById(R.id.RepToolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_home_black_24dp); final ImageView picIv = findViewById(R.id.ownerIv); final TextView nameTv = findViewById(R.id.repoName); final TextView starTv = findViewById(R.id.starsTv); final TextView watchTv = findViewById(R.id.watcherTv); final TextView forkTv = findViewById(R.id.forksTv); final TextView sizeTv = findViewById(R.id.sizeTv); final TextView langTv = findViewById(R.id.langTv); final ImageButton sharebtn = findViewById(R.id.shareBtn); final ViewPager mView = findViewById(R.id.RepoViewpager); final TabLayout mTab = findViewById(R.id.repoTab); mTab.setupWithViewPager(mView); mView.setOffscreenPageLimit(2); sharebtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (url != null) { Intent share = new Intent(); share.setAction(Intent.ACTION_SEND); share.putExtra(Intent.EXTRA_TEXT, String.valueOf(url)); share.setType("text/plain"); startActivity(Intent.createChooser(share,"Share With ")); } } }); String url = getIntent().getStringExtra("url"); Log.d("url_repo",url.toString()); Response.Listener<org.json.JSONObject> listenerResponse = new Response.Listener<org.json.JSONObject>() { @Override public void onResponse(org.json.JSONObject response) { try{ String name = response.getString("full_name"); String size = response.getString("size"); String stars = response.getString("stargazers_count"); String watchers = response.getString("watchers_count"); String forks = response.getString("forks_count"); String lang = response.getString("language"); String commits = response.getString("commits_url"); String contribute = response.getString("contributors_url"); org.json.JSONObject avatar = response.getJSONObject("owner"); String pic = avatar.getString("avatar_url"); Picasso.with(getApplicationContext()) .load(pic) .into(picIv); nameTv.setText(name); starTv.setText(stars); sizeTv.setText(size + " KB"); watchTv.setText(watchers); forkTv.setText(forks); langTv.setText(lang); Bundle repoBundle = new Bundle(); repoBundle.putString("commit_url",commits); repoBundle.putString("contributors_url",contribute); ReposFragmentAdapter adapter = new ReposFragmentAdapter(getSupportFragmentManager(),repoBundle); mView.setAdapter(adapter); } catch (Exception e) { } } }; Response.ErrorListener listenerError = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Error " + error, Toast.LENGTH_LONG).show(); } }; JSONObjRequest.getData(Request.Method.GET,getApplicationContext(), url, listenerResponse, listenerError); } @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()){ case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } public class ReposFragmentAdapter extends FragmentStatePagerAdapter { Bundle info; public ReposFragmentAdapter(FragmentManager fm,Bundle repoBundle) { super(fm); info = repoBundle; } @Override public Fragment getItem(int position) { if (position == 0) { Fragment f1 = new CommitFragment(); f1.setArguments(info); return f1; } else { Fragment f2 = new ContributorsFragment(); f2.setArguments(info); return f2; } } @Override public int getCount() { return 2; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "Commits"; case 1: return "Contributors"; default: return null; } } } private void setShareActionProvider(Intent shareIntent){ if (shareActionProvider != null) { shareActionProvider.setShareIntent(shareIntent); } } } <file_sep>package app.robo.com.getgit; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import static com.android.volley.VolleyLog.TAG; public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> { private List<String> mData; private LayoutInflater mInflater; String owner; private Context context; Bundle bundle4 = new Bundle(); Bundle repoInfo; String url,name; // data is passed into the constructor public MyRecyclerViewAdapter(Context context, ArrayList<String> data,String owner) { this.mInflater = LayoutInflater.from(context); this.mData = data; this.context = context; this.owner= owner; } // inflates the row layout from xml when needed @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.show_list, parent, false); return new ViewHolder(view); } // binds the data to the TextView in each row @Override public void onBindViewHolder(ViewHolder holder, final int position) { holder.myTextView.setText(mData.get(position)); holder.mCardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { url = "https://api.github.com/repos/" + owner+"/"+mData.get(position); Log.d("url_repo",url.toString()); Response.Listener<JSONObject> listenerResponse = new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try{ String name = response.getString("full_name"); String desc = response.getString("description"); String size = response.getString("size"); String stars = response.getString("stargazers_count"); String watchers = response.getString("watchers_count"); String forks = response.getString("forks_count"); String lang = response.getString("language"); String commits = response.getString("commits_url"); String contribute = response.getString("contributors_url"); JSONObject avatar = response.getJSONObject("owner"); String pic = avatar.getString("avatar_url"); /* Bundle b1=new Bundle(); b1.putString("url",url); b1.putString("full name",name); b1.putString("desc",desc); b1.putString("size",size); b1.putString("stars",stars); b1.putString("watchers",watchers); b1.putString("forks",forks); b1.putString("lang",lang); b1.putString("pic",pic); b1.putString("commits_url",commits); b1.putString("contribute_url",contribute);*/ app.robo.com.getgit.JSONObject RepoObject = new app.robo.com.getgit.JSONObject(name,pic,size,stars,watchers,forks,lang,commits,contribute,url); Intent intent = new Intent(context,ReposActivity.class); /* Gson gson = new Gson(); String myString = gson.toJson(RepoObject);*/ intent.putExtra("Repo_info",RepoObject); context.startActivity(intent); } catch (Exception e) { } } }; Response.ErrorListener listenerError = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(context, "Error " + error, Toast.LENGTH_LONG).show(); } }; JSONObjRequest.getData(Request.Method.GET,context, url, listenerResponse, listenerError); } }); } // total number of rows @Override public int getItemCount() { return mData.size(); } // stores and recycles views as they are scrolled off screen public class ViewHolder extends RecyclerView.ViewHolder{ TextView myTextView; CardView mCardView; ViewHolder(View itemView) { super(itemView); myTextView = itemView.findViewById(R.id.RepName); mCardView = itemView.findViewById(R.id.card_view1); } } }<file_sep>package app.robo.com.getgit; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Text; import java.util.ArrayList; import static com.android.volley.VolleyLog.TAG; public class CommitFragment extends Fragment { String commit,commit_url,jsonResponse; ArrayList<String> author_nameList = new ArrayList<>(); ArrayList<String> commit_dateList = new ArrayList<>(); ArrayList<String> messageList = new ArrayList<>(); private RecyclerView.Adapter mAdapter; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); commit = getArguments().getString("commit_url"); String[] num1 = commit.split("\\{"); commit_url = num1[0]; Log.d("commit",commit_url); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.recycler_view, container, false); } @Override public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final RecyclerView recyclerView = view.findViewById(R.id.ShowRepos); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); JsonArrayRequest req = new JsonArrayRequest(commit_url, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { ProgressBar progressBar = view.findViewById(R.id.progress); progressBar.setVisibility(view.VISIBLE); try { // Parsing json array response // loop through each json object for (int i = 0; i < response.length(); i++) { JSONObject commit_object = (JSONObject) response.get(i); JSONObject commit = commit_object.getJSONObject("commit"); String message = commit.getString("message"); JSONObject author = commit.getJSONObject("author"); String author_name = author.getString("name"); String commit_date = author.getString("date"); messageList.add(message); author_nameList.add(author_name); commit_dateList.add(commit_date); } progressBar.setVisibility(view.GONE); Log.d("mList",messageList.toString()); mAdapter = new CommitFragmentAdapter(getContext(), messageList, author_nameList,commit_dateList); recyclerView.setAdapter(mAdapter); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); // Adding request to request queue JSONArrayRequest.getInstance().addToRequestQueue(req); } } <file_sep>package app.robo.com.getgit; import android.app.ProgressDialog; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import static com.android.volley.VolleyLog.TAG; public class ContributorsFragment extends Fragment { Bundle bundle; String contribute; ArrayList<String> loginList = new ArrayList<>(); ArrayList<String> avatarList= new ArrayList<>(); ArrayList<String> urlList = new ArrayList<>(); private RecyclerView.Adapter mAdapter; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); contribute = getArguments().getString("contributors_url"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.recycler_view, container, false); } @Override public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final RecyclerView recyclerView = view.findViewById(R.id.ShowRepos); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); JsonArrayRequest req = new JsonArrayRequest(contribute, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { ProgressBar progressBar = view.findViewById(R.id.progress); progressBar.setVisibility(view.VISIBLE); try { // Parsing json array response // loop through each json object for (int i = 0; i < response.length(); i++) { JSONObject contribute_object = (JSONObject) response.get(i); String login = contribute_object.getString("login"); String avatar = contribute_object.getString("avatar_url"); String url = contribute_object.getString("url"); loginList.add(login); avatarList.add(avatar); urlList.add(url); } progressBar.setVisibility(view.GONE); Log.d("mList",loginList.toString()); mAdapter = new ContributorFragmentAdapter(getContext(), loginList, avatarList,urlList); recyclerView.setAdapter(mAdapter); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); // Adding request to request queue JSONArrayRequest.getInstance().addToRequestQueue(req); } } <file_sep>This is a mockup project for development purposes only. This project is intented to access Github API using Retrofit library. <file_sep>package app.robo.com.getgit; import android.os.Parcel; import android.os.Parcelable; public class JSONObject implements Parcelable { private String full_name; private String size; private String watchers_count; private String forks_count; private String language; private String commits_url; private String contributors_url; private String star; private String pic; private String url; @Override public int describeContents() { return 0; } public String getUrl() { return url; } public JSONObject(String full_name, String pic, String size, String stars, String watchers_count, String forks_count, String language, String commits_url, String contributors_url,String url){ this.full_name = full_name; this.size = size; this.star=stars; this.watchers_count=watchers_count; this.forks_count=forks_count; this.language=language; this.commits_url=commits_url; this.contributors_url=contributors_url; this.pic=pic; this.url=url; } public String getFull_name() { return full_name; } public String getSize() { return size; } public String getWatchers_count() { return watchers_count; } public String getForks_count() { return forks_count; } public String getLanguage() { return language; } public String getCommits_url() { return commits_url; } public String getContributors_url() { return contributors_url; } public String getStar() { return star; } public String getPic() { return pic; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(full_name); dest.writeString(pic); dest.writeString(size); dest.writeString(star); dest.writeString(watchers_count); dest.writeString(forks_count); dest.writeString(language); dest.writeString(commits_url); dest.writeString(contributors_url); dest.writeString(url); } public JSONObject(Parcel in){ full_name = in.readString(); pic = in.readString(); size = in.readString(); star = in.readString(); watchers_count = in.readString(); forks_count = in.readString(); language = in.readString(); commits_url = in.readString(); contributors_url = in.readString(); url = in.readString(); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public JSONObject createFromParcel(Parcel in) { return new JSONObject(in); } public JSONObject[] newArray(int size) { return new JSONObject[size]; } }; } <file_sep>package app.robo.com.getgit; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.util.Log; 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.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import java.util.ArrayList; import java.util.List; public class NavRecyclerViewAdapter extends RecyclerView.Adapter<NavRecyclerViewAdapter.ViewHolder> { private List<String> mData; private LayoutInflater mInflater; String pic,url; Context context ; String owner; // data is passed into the constructor public NavRecyclerViewAdapter(Context context, ArrayList<String> data) { this.mInflater = LayoutInflater.from(context); this.mData = data; this.context=context; } // inflates the row layout from xml when needed @Override public NavRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.nav_layout, parent, false); return new NavRecyclerViewAdapter.ViewHolder(view); } // binds the data to the TextView in each row @Override public void onBindViewHolder(NavRecyclerViewAdapter.ViewHolder holder, final int position) { holder.myTextView.setText(mData.get(position)); holder.mCard.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { url = "https://api.github.com/repos/"+mData.get(position); Intent intent =new Intent(context,NavRepoActivity.class); intent.putExtra("url",url); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }); } // total number of rows @Override public int getItemCount() { return mData.size(); } // stores and recycles views as they are scrolled off screen public class ViewHolder extends RecyclerView.ViewHolder{ TextView myTextView; CardView mCard; ViewHolder(View itemView) { super(itemView); myTextView = itemView.findViewById(R.id.RepName); mCard = itemView.findViewById(R.id.navCard); } } }
d8fdf546872dab27ce43158c3c98e774819cd375
[ "Markdown", "Java" ]
8
Java
Ehtisham95/GETGIT
151e4415aa04884c3d172f7a29b2db076eea97f9
598b38a9e34351539999f34e91ea206339231638
refs/heads/master
<repo_name>hhaisYouShan/hzler<file_sep>/index2/js/script.js (function($) { "use strict"; // Windows load $(window).on("load", function() { console.log("123"); // Site loader // $(".loader-inner").fadeOut(); // $(".loader").delay(200).fadeOut("slow"); }); // var height=document.body.offsetHeight; // Site navigation setup var header = $('.header'), pos = header.offset(), blockTop = $('.block-top'); //Hero resize var mainHero = $(" .hero .main-slider .slides li"); function mainHeroResize() { mainHero.css('height', $(window).height()); } $(function() { mainHeroResize() }), $(window).resize(function() { mainHeroResize() }); // Mobile menu var mobileBtn = $('.mobile-but'); var nav = $('.main-nav ul.main-menu'); var navHeight = nav.height(); $(mobileBtn).on("click", function() { $(".toggle-mobile-but").toggleClass("active"); nav.slideToggle(); $('.main-nav li a').addClass('mobile'); return false; }); $("#showCornerImg a").on("click", function () { $(".backColor").show(); $("#showNewImg").css('display','block'); // console.log($(this).children().attr('src')); $("#showNewImg img").attr("src",$(this).children().attr('src')); }); $(document).mouseup(function(e){ var _con = $('#showCornerImg '); // 设置目标区域 if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1 $("#showNewImg").css('display','none'); $(".backColor").hide(); // some code... // 功能代码 } }); // Append images as css background $('.background-img').each(function() { var path = $(this).children('img').attr('src'); $(this).css('background-image', 'url("' + path + '")').css('background-position', 'initial'); }); })(jQuery); <file_sep>/index2/js/mp3ZDY.js //原创音乐定制 const arrMp3Original=[ { mp3Url:'index2/mp3/original/寻回主题歌.mp3', //mp3路径 mp3Title:'《寻回》主题歌' , //你描述的内容 mp3Background:'index2/mp3/img/寻回.jpeg' //背景图片 }, { mp3Url:'index2/mp3/original/爱与被爱的权力MIX.mp3', mp3Title:'爱与被爱的权力MIX' , mp3Background:'index2/mp3/img/爱与被爱的权利.JPG' }, { mp3Url:'index2/mp3/original/巴厘MIX3.mp3', mp3Title:'巴厘MIX3' , mp3Background:'index2/mp3/img/巴里.png' }, { mp3Url:'index2/mp3/original/bzaw.mp3', mp3Title:'别再爱我 MIX0519', mp3Background:'index2/mp3/img/别再爱我.JPG' }, { mp3Url:'index2/mp3/original/差旅篇1122.mp3', mp3Title:'差旅篇1122', mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/original/剪掉.mp3', mp3Title:'剪掉', mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/original/whh.mp3', mp3Title:'娃哈哈 MIX', mp3Background:'index2/mp3/img/娃哈哈实现梦想.png' }, { mp3Url:'index2/mp3/original/万象城主题歌《最美声音》.mp3', mp3Title:'万象城主题歌《最美声音》', mp3Background:'index2/mp3/img/最美声音.png' }, { mp3Url:'index2/mp3/original/我们是新时代的移民管理警察Final Mix.mp3', mp3Title:'我们是新时代的移民管理警察FinalMix' , mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/original/我在兰溪等你成品MIX.mp3', mp3Title:'我在兰溪等你 成品MIX' , mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/original/向阳之歌MIX.mp3', mp3Title:'向阳之歌 MIX' , mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/original/协会篇.mp3', mp3Title:'协会篇' , mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/original/缘落mix.mp3', mp3Title:'缘落mix' , mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/original/中国公安纪录片.mp3', mp3Title:'中国公安纪录片主题歌《责任》' , mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/original/brokenbaedDEMPMIX.mp3', mp3Title:'brokenbaedDEMPMIX' , mp3Background:'index2/mp3/img/brokenbaed.JPG' }, { mp3Url:'index2/mp3/original/WBK开场.mp3', mp3Title:'WBK开场', mp3Background:'index2/mp3/img/commun.jpg' }, ]; //录音翻唱 const arrMp3Reprie=[ { mp3Url:'index2/mp3/reprise/爱要怎么说出口.mp3', mp3Title:'爱要怎么说出口', mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/reprise/匆匆那年.mp3', mp3Title:'匆匆那年' , mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/reprise/房间MIX.mp3', mp3Title:'房间 MIX', mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/reprise/gnzw.mp3', mp3Title:'光年之外 MIX', mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/reprise/那些你很冒险的梦MIX.mp3', mp3Title:'那些你很冒险的梦MIX' , mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/reprise/同花顺.mp3', mp3Title:'同花顺' , mp3Background:'index2/mp3/img/commun.jpg' }, { mp3Url:'index2/mp3/reprise/再见录音.mp3', mp3Title:'再见录音' , mp3Background:'index2/mp3/img/commun.jpg' }]; function arrList(arrMp3,classHtml){ let bg_center=localStorage.getItem("bgCenterSrc"); if(!bg_center){ localStorage.setItem('bgCenterSrc','index2/mp3/img/commun.jpg'); bg_center=localStorage.getItem("bgCenterSrc"); } var iHtml=''; for(let i=0;i<arrMp3.length;i++){ // console.log("123"); // iHtml = '<tr>'+ // console.log(iHtml); let mp3Url=arrMp3[i].mp3Url; // console.log(arrMp3[i].mp3Url); iHtml = '<tr>' + '<td style="width:130px;height:150px">'+ '<div class="btns-bg">'+ '<div class="PlayEy PlayEyBack" style="background: url('+arrMp3[i].mp3Background+'),url('+bg_center+') no-repeat center; background-size:100% 100%; "></div>'+ '<div class="Btn"></div>'+ '<div class="Play">'+ '<audio src="'+mp3Url+'" preload="none" type="audio/mp3"></audio>'+ '</div>'+ '</div>'+ '</td>'+ '<td>'+ '<p class="textOverflow">'+ arrMp3[i].mp3Title+ '</p>'+ '</td>'+ '</tr>'; $("."+classHtml).append(iHtml); } } arrList(arrMp3Reprie,'mp3Reprise'); arrList(arrMp3Original,'Mp3Original'); $('.Play').each(function (index,value) { let MUSIC_LENGTH =$('.Play').length; $(this).children('audio').attr('id','audiosList'+index); $(this).click(function () { $('.Play').css('backgroundImage',"url(index2/img/vidio/pause.png)"); let oPlayEy=$(this).prev('.Btn').prev('.PlayEy'); let oPlay=$(this); let audios=document.getElementById($(this).children('audio').attr('id')); var seii = setInterval(function() { (i == 360) ? i = 0 : i++; oPlayEy.css('transform',"rotate(" + i + "deg)"); // oPlayEy.style.transform = "rotate(" + i + "deg)"; if(audios.paused) { clearInterval(seii); } }, 30); if(audios.paused) { for(let i=0;i<MUSIC_LENGTH;i++){ if(i==index){ console.log("12313"); oPlay.css('backgroundImage',"url(index2/img/vidio/play.png)"); oPlay.css('width',"32px"); oPlay.css('height',"32px"); audios.play(); } else { document.getElementById("audiosList"+i).pause(); } } } else { audios.pause(); oPlay.css('backgroundImage',"url(index2/img/vidio/pause.png)"); oPlay.css('width',"29px"); oPlay.css('height',"36px"); } }) }) <file_sep>/index2/js/lib.js //悬浮看框 $(function(){ // 获取window的引用: var $window = $(window); // 获取包含data-src属性的img,并以jQuery对象存入数组: var lazyImgs = _.map($('img[data-src]').get(), function (i) { return $(i); }); // 定义事件函数: var onScroll = function() { // 获取页面滚动的高度: var wtop = $window.scrollTop(); // 判断是否还有未加载的img: if (lazyImgs.length > 0) { // 获取可视区域高度: var wheight = $window.height(); // 存放待删除的索引: var loadedIndex = []; // 循环处理数组的每个img元素: _.each(lazyImgs, function ($i, index) { // 判断是否在可视范围内: if ($i.offset().top - wtop < wheight) { // 设置src属性: $i.attr('src', $i.attr('data-src')); // 添加到待删除数组: loadedIndex.unshift(index); } }); // 删除已处理的对象: _.each(loadedIndex, function (index) { lazyImgs.splice(index, 1); }); } }; // 绑定事件: $window.scroll(onScroll); $('.slide .icon li').not('.up,.down').mouseenter(function(){ $('.slide .info').addClass('hover'); $('.slide .info li').hide(); $('.slide .info li.'+$(this).attr('class')).show();//.slide .info li.qq }); $('.slide').mouseleave(function(){ $('.slide .info').removeClass('hover'); }); $('#btn').click(function(){ $('.slide').toggle(); if($(this).hasClass('index_cy')){ $(this).removeClass('index_cy'); $(this).addClass('index_cy2'); }else{ $(this).removeClass('index_cy2'); $(this).addClass('index_cy'); } }); // $(".backTop").click(function(){if(scroll=="off") return;$("html,body").animate({scrollTop: 0}, 600);}); $('.backTop').hide() $(window).scroll(function(){ if($(this).scrollTop() > 350){ $(".backTop").fadeIn(); } else{ $(".backTop").fadeOut(); } }) //置顶事件 $(".backTop").click(function(){ $('body,html').animate({scrollTop:0},300); }) });
614d35ce235dceecf127be691aa188e57ef52d53
[ "JavaScript" ]
3
JavaScript
hhaisYouShan/hzler
db1b184ae00567393bc6f68e2156c01994f57ca7
e6d75e12eca998bc8f988d5a30cabc67bc4423e7
refs/heads/master
<file_sep>target 'testPodsManager' do pod 'YYImage' #图片 pod 'YYModel', '1.0.4' #模型 pod 'AFNetworking', '~> 4.0' #网络请求 pod 'Masonry', '1.1.0' #界面布局 end
dc89d03b3ba81208c52e347088bac3aeb527e7ef
[ "Ruby" ]
1
Ruby
HPTears/TestPodsManager
87459095013884f12cbbdd34aa04d33aaa9da15f
064f104ffea38be3cffce7fc68381eebcebbb06c
refs/heads/main
<repo_name>AloneBlind/WhatsApp-Bot<file_sep>/README.md # WhatsApp-Bot This bot is aiming to be leveling bot. From the creator of GanyuBot # Under development! Please do not use this now. it may not work. # Features | FEATURES | STATUS | | :---: | :---: | | Leveling | ❎ | | Money | ❎ | # Help me! Help this project running by donating * [Trakteer](https://trakteer.id/Ganyu) <file_sep>/src/lib/commands/handler.js /* This file is used for message handling. */ const fs = require("fs") const defaultPrefix = "/"; // Default prefix const client = require("../../index").client(); function getPrefix(message) { let data = JSON.parse(fs.readFileSync("./lib/database/groups.json")) if (!message.isGroupMsg) return defaultPrefix; else return data[message.sender.groupMetadata.id].prefix; } function match(message, command) { if (message.body.startsWith(getPrefix(message)+command)) return true; return false; } /* Bot modules */ const help = require("./help"); module.exports = async (message) => { let {from, sender, id, body} = message; if (await match(message, "help")) { } }<file_sep>/src/index.js require("@open-wa/wa-automate").create().then(client=>start(client)); const messageHandler = require("./lib/commands/handler"); exports.client = () => gclient; let gclient; function start(client) { gclient = client; /* Message handling hwre */ client.onMessage(messageHandler); }<file_sep>/src/lib/database/handler.js const fs = require("fs") exports.handle = async (message) => { let {sender, id, from} = message! let group = JSON.parse(fs.readFileSync("./lib/database/group.json"; if (message.isGroupMsg) { //If Group message if (group[sender.groupMetadata.id] === undefined) group[sender.groupMetadata.id] = {}; if (group[sender.groupMetadata.id].prefix === undefined) group[sender.groupMetadata.id].prefix = "/"; //Default prefix fs.writeFileSync("./lib/database/group.json", JSON.stringify(group)); } }
fa8b9e7fa77dc561152054ed97f17205763cb16f
[ "Markdown", "JavaScript" ]
4
Markdown
AloneBlind/WhatsApp-Bot
1dd4b993254d3603ca989c4a30707c6f881f959a
f6175fed684406cb95a044f1ca2fd08783b800e3
refs/heads/master
<repo_name>sarmadzaki/Application-With-React<file_sep>/src/components/Submit.jsx import React, { Component } from 'react' import Navbar from './Navbar' import Ingredient from './Ingredient' class Submit extends Component { constructor(props) { super(props); this.state={}; } submitRecipe() { console.log('submit recipe'); console.log(this.refs.name.value, this.refs.desc.value,this.refs.quantity.value, this.refs.ingredient.value) } render() { return ( <div> <Navbar /> <div className="row"> <div className="container"> <h1>Submit</h1> <form> <div className="form-group"> <label htmlFor="Name">Name</label> <input ref="name" type="text" className="form-control" id="Name" placeholder="Name" /> </div> <div className="form-group"> <label htmlFor="exampleInputPassword1">Description</label> <textarea ref="desc" type="text" className="form-control" placeholder="enter a brief description" /> </div> <Ingredient /> <button type="button" onClick={() => this.submitRecipe()} className="btn btn-default">Submit</button> </form> </div> </div> </div> ) } } export default Submit;<file_sep>/src/components/Ingredient.jsx import React, { Component } from 'react' class Ingredient extends Component { constructor(props) { super(props); } addIngredients() { console.log("ingredient added") console.log(this.refs.quantity.value, this.refs.ingredient.value) } render() { return ( <div className="form-inline form-group"> <label htmlFor="quantity">Quantity</label> <input ref="quantity" type="text" className="form-control" id="Quantity" placeholder="Quantity" /> <label htmlFor="ingredient">Ingredients</label> <input ref="ingredient" type="text" className="form-control" id="ingredient" placeholder="Ingredient" /> <button type="button" onClick={() => this.addIngredients()} className="btn btn-info">Add</button> </div> ) } } export default Ingredient;<file_sep>/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './components/App'; import registerServiceWorker from './registerServiceWorker'; import 'bootstrap/dist/css/bootstrap.css'; import { Router, Route, browserHistory } from 'react-router'; import Submit from './components/Submit' import Home from './components/Home' ReactDOM.render( <Router history={browserHistory}> <Route path="/" component={App} /> <Route path="/home" component={Home} /> <Route path="/submit" component={Submit} /> </Router>, document.getElementById('root')); registerServiceWorker();
8b46c0924fba46a01b6b1ab6baa3ee68b148e3ba
[ "JavaScript" ]
3
JavaScript
sarmadzaki/Application-With-React
ae729e5f1cbbb7c7951676411f046da696e8556f
1de25fd4b8eff6f8d312fd9f23f222b86ba770bb
refs/heads/master
<file_sep>import threading import queue import cmd from theo.src.framework.DictList import DictList class System: """ System provides component and interface functionality. It makes you to build your system easy. System supports a prompt functionality to execute your system. Because the interface module works with registered interfaces by components, please use System with Component. Methods: register_interface(component, command, argument_numbers, func) : registering interface execute_interface(component, command, *arguments) : executing interface register_component(constructor) register_components(constructors) components = get_components() : getting the registered components startup_components() : creating registered components and calling the initial function of the components start_interface_prompt() Example: from theo.framework import System, Component class TheoFriend(Component): def initial(self): self.log.print('info', 'initial') System.register_interface('TheoFriend', 'print_theo_friend', [1], self.print_theo_friend) def print_theo_friend(self, name): self.log.print('info', 'Theo has a friend, {}'.format(name)) System.register_component(TheoFriend) System.startup_components() System.execute_interface('TheoFriend', 'print_theo_friend', 'Grace') """ interface_dictlist = DictList() component_dictlist = DictList() is_prompt_started = False @staticmethod def register_interface(component, command, argument_numbers, func): try: if not System.interface_dictlist.get([{'key': 'component', 'value': component}, {'key': 'command', 'value': command}]): System.interface_dictlist.append( {'component': component, 'command': command, 'argument_numbers': argument_numbers, 'func': func}) except Exception as error: print(f'error: {error} / System.register_interface(component:{component}/{type(component)},', f'command:{command}/{type(command)},') print(f'\targument_numbers:{argument_numbers}/{type(argument_numbers)}, func:{func}/{type(func)})') @staticmethod def execute_interface(component, command, *arguments): try: interface = System.interface_dictlist.get([ {'key': 'component', 'value': component}, {'key': 'command', 'value': command} ]) if interface and len(arguments) in interface['argument_numbers']: return interface['func'](*arguments) return None except Exception as error: print(f'error: {error} / System.execute_interface(component:{component}/{type(component)},', f'command:{command}/{type(command)},') print(f'\t*arguments:{arguments}/{type(arguments)})') return None @staticmethod def register_component(constructor): try: if not System.component_dictlist.get('constructor', constructor): System.component_dictlist.append({'constructor': constructor, 'handler': None, 'init': False}) except Exception as error: print(f'error: {error} / System.register_component(constructor:{constructor}/{type(constructor)})') @staticmethod def register_components(constructors): try: for constructor in constructors: if not System.component_dictlist.get('constructor', constructor): System.component_dictlist.append({'constructor': constructor, 'handler': None, 'init': False}) except Exception as error: print(f'error: {error} / System.register_components(constructor:{constructors}/{type(constructors)})') @staticmethod def get_components(): try: return list(map(lambda component: component['constructor'].__name__, System.component_dictlist.get_list())) except Exception as error: print(f'error: {error} / System.get_components()') @staticmethod def startup_components(): try: for component in System.component_dictlist.get_list(): if not component['handler']: component['handler'] = component['constructor']() if not component['init']: component['handler'].initial() component['init'] = True except Exception as error: print(f'error: {error} / System.get_components()') @staticmethod def start_interface_prompt(): try: if not System.is_prompt_started: system_queue = queue.Queue() prompt_queue = queue.Queue() prompt = Prompt() prompt.set_queue(system_queue, prompt_queue) threading.Thread(target=prompt.cmdloop).start() System.is_prompt_started = True while True: messages = system_queue.get() if len(messages) == 1 and messages[0] == 'exit': break elif len(messages) == 1 and messages[0] == 'get_interfaces': prompt_queue.put(System.interface_dictlist.get_list()) elif len(messages) >= 2: prompt_queue.put(System.execute_interface(messages[0], messages[1], *messages[2:])) else: prompt_queue.put(None) except Exception as error: print(f'error: {error} / System.start_interface_prompt()') class Prompt(cmd.Cmd): intro = 'help : print user commands what are registered' \ + '\nexit : quit the prompt' prompt = '(prompt) ' system_queue = None prompt_queue = None def set_queue(self, system_queue, prompt_queue): self.system_queue = system_queue self.prompt_queue = prompt_queue def precmd(self, inputs): try: inputs = inputs.split() if len(inputs) < 1: return '' elif len(inputs) == 1 and inputs[0] == 'exit': return 'exit' elif len(inputs) == 1 and inputs[0] == 'help': self.system_queue.put(['get_interfaces']) interfaces = self.prompt_queue.get() print(f'Interface list(num:{len(interfaces)})') for interface in interfaces: print('- {} {} {}'.format( interface['component'], interface['command'], interface['argument_numbers'])) return '' elif len(inputs) < 2: print('Invalid command') return '' self.system_queue.put(inputs) result = self.prompt_queue.get() if isinstance(result, DictList): print('Result : below DictList') result.print() elif isinstance(result, list): print(f'Result : List(num:{len(result)})') for index, element in enumerate(result): print(f'[index:{index}] {element}') else: print(f'Result : {result}/{type(result)}') return '' except Exception as error: print(f'error: {error} / Prompt.precmd(inputs:{inputs}/{type(inputs)})') def do_exit(self, inputs): self.system_queue.put(['exit']) return True <file_sep>import abc from theo.src.framework.Log import Log class Component(metaclass=abc.ABCMeta): """ Component is a system part. In the project, components are initialized by system and communicate using interface functions. How to use: Copy the example and change the ComponentName If the component has a dependency with other components, class the System.get_components() and check the existence. Define the function, initial and add calling system.register_interface and initial sequence for it. Add System.register_component(ComponentName) at program main. When main call system.startup_components(), the component will be initialized. Example: Please refer the docstings of System """ def __init__(self): self.log = Log(type(self).__name__) def __name__(self): return type(self).__name__ @abc.abstractmethod def initial(self): pass <file_sep>from theo.src.framework.DictList import DictList from theo.src.framework.Log import Log from theo.src.framework.Component import Component from theo.src.framework.System import System <file_sep>import logging import os import datetime import shutil from theo.src.framework.DictList import DictList class Log: """ Log is made to log a program by printing and storing. Log works with the configurations. When Log works with new name and new level, configuration files are stored the data as JSON. File locations are set from configurations. By the configuration, printing and storing work by level comparison. If value of argument level is higher than value of name's level, the print function works. The default levels are critical(100), info(50), debug(30), none(0). And the default configuration is Print(info), Store(debug). If the configuration is not changed, the log what is set a level higher than info is printed and debug is stored. Initially, the storing does not work. To store a log, calling configure(store_enabled=True) is needed before construct Log class. Methods: Log.configure(print_enabled=None, store_enabled=None, config_directory=None, log_directory=None, over_time_log_clear_enabled=None, over_time_days=None) log = Log(name) log.print(level, message) Example: from theo.framework import Log Log.configure(print_enabled=True, store_enabled=True, over_time_log_clear_enabled=True) log = Log('name') log.print('info', 'Hello, theo.framework!') """ is_started = False print_logger = None store_logger = None name_config_dictlist = DictList(key='name') level_config_dictlist = DictList(key='level') print_enabled = True store_enabled = False config_directory = os.path.join(os.getcwd(), 'configs', 'log') name_config_path = os.path.join(config_directory, 'name_config.json') level_config_path = os.path.join(config_directory, 'level_config.json') log_directory = os.path.join(os.getcwd(), 'files', 'log') log_store_directory = os.path.join(log_directory, datetime.datetime.now().strftime('%Y-%m-%d')) over_time_log_clear_enabled = False over_time_days = 3 @staticmethod def configure(print_enabled=None, store_enabled=None, config_directory=None, log_directory=None, over_time_log_clear_enabled=None, over_time_days=None): try: if not Log.is_started: Log.print_enabled = True if print_enabled else Log.print_enabled Log.store_enabled = True if store_enabled else Log.store_enabled Log.config_directory = config_directory if config_directory else Log.config_directory Log.name_config_path = os.path.join(Log.config_directory, 'name_config.json') if config_directory else Log.name_config_path Log.level_config_path = os.path.join(Log.config_directory, 'level_config.json') if config_directory else Log.level_config_path Log.log_directory = log_directory if log_directory else Log.log_directory Log.over_time_log_clear_enabled = \ True if over_time_log_clear_enabled else Log.over_time_log_clear_enabled Log.over_time_days = over_time_days if over_time_days else Log.over_time_days except Exception as error: print(f'error: {error} / Log.configure(print_enabled:{print_enabled}/{type(print_enabled)},', f'store_enabled:{store_enabled}/{type(store_enabled)},') print(f'\tconfig_directory:{config_directory}/{type(config_directory)},', f'log_directory:{log_directory}/{type(log_directory)}') print(f'\tover_time_log_clear_enabled:{over_time_log_clear_enabled}/{type(over_time_log_clear_enabled)},', f'over_time_days:{over_time_days}/{type(over_time_days)}') def __init__(self, name): try: self.name = name if not Log.is_started: print(f'Log Enabled(print:{Log.print_enabled}, store:{Log.store_enabled})') print(f'Log Directories(config:{Log.config_directory}' + (f', log:{Log.log_directory})' if Log.store_enabled else ')')) if Log.store_enabled: print(f'Log Option(over_time_log_clear_enabled:{Log.over_time_log_clear_enabled}' + f', days:{Log.over_time_days})' if Log.over_time_log_clear_enabled else ')') if not os.path.exists(Log.config_directory): os.makedirs(Log.config_directory) if os.path.exists(Log.name_config_path): Log.name_config_dictlist.import_json(Log.name_config_path) if not os.path.exists(Log.level_config_path): Log.level_config_dictlist.append({'level': 'critical', 'value': 100}) Log.level_config_dictlist.append({'level': 'info', 'value': 50}) Log.level_config_dictlist.append({'level': 'debug', 'value': 30}) Log.level_config_dictlist.append({'level': 'none', 'value': 0}) Log.level_config_dictlist.export_json(Log.level_config_path) else: Log.level_config_dictlist.import_json(Log.level_config_path) if Log.print_enabled: Log.print_logger = logging.getLogger('print') Log.print_logger.setLevel(logging.INFO) print_stream_handler = logging.StreamHandler() print_stream_handler.setFormatter(logging.Formatter('[%(asctime)s]%(message)s')) Log.print_logger.addHandler(print_stream_handler) if Log.store_enabled: if not os.path.exists(Log.log_directory): os.makedirs(Log.log_directory) if Log.over_time_log_clear_enabled: for directory in os.listdir(Log.log_directory): if os.path.isdir(os.path.join(Log.log_directory, directory)) \ and (Log.over_time_days <= (datetime.datetime.now() - datetime.datetime.strptime(directory, '%Y-%m-%d')).days): shutil.rmtree(os.path.join(Log.log_directory, directory)) Log.log_store_directory = os.path.join(Log.log_directory, datetime.datetime.now().strftime('%Y-%m-%d')) if not os.path.exists(Log.log_store_directory): os.makedirs(Log.log_store_directory) Log.store_logger = logging.getLogger('store') Log.store_logger.setLevel(logging.INFO) file_handler = logging.FileHandler( os.path.join(Log.log_store_directory, datetime.datetime.now().strftime('%H-%M-%S.log'))) file_handler.setFormatter(logging.Formatter('[%(asctime)s]%(message)s')) Log.store_logger.addHandler(file_handler) Log.is_started = True self.level_config = Log.name_config_dictlist.get(name) if not self.level_config: self.level_config = {'name': name, 'print': 'info', 'store': 'debug'} Log.name_config_dictlist.append(self.level_config) Log.name_config_dictlist.export_json(Log.name_config_path) except Exception as error: print(f'error: {error} / Log(name:{name}/{type(name)})') @staticmethod def get_level_value(level): try: level_config = Log.level_config_dictlist.get(level) if not level_config: level_config = {'level': level, 'value': 50} Log.level_config_dictlist.append(level_config) Log.level_config_dictlist.export_json(Log.level_config_path) return level_config['value'] except Exception as error: print(f'error: {error} / Log.get_level_value(level:{level}/{type(level)})') return 50 def print(self, level, *messages): try: log = f'[{self.name}][{level}]' for message in messages: log += ' ' + str(message) level_value = Log.get_level_value(level) if Log.print_logger and level_value >= Log.get_level_value(self.level_config['print']): Log.print_logger.info(log) if Log.store_logger and level_value >= Log.get_level_value(self.level_config['store']): Log.store_logger.info(log) except Exception as error: print(f'error: {error} / log.print(level:{level}/{type(level)}, message:{message}/{type(message)})') <file_sep># theo-framework It is the framework what makes building a project easy. DictList is the data structure to control data easily and efficiently. Log is made to log a program by printing and storing. System and Component make building a system easy. I am likely waiting a any kind of contribution. # Theo series Framework : pip install theo-framework, https://github.com/TheodoreWon/python-theo-framework Database : pip install theo-database, https://github.com/TheodoreWon/python-theo-database Message : pip install theo-message, https://github.com/TheodoreWon/python-theo-message Internet : pip install theo-message, https://github.com/TheodoreWon/python-theo-internet Trade : pip install theo-trade, https://github.com/TheodoreWon/python-theo-trade # How to use Install the framework > pip install theo-framework Print docstrings > from theo.framework import DictList, Log, System, Component > print(DictList.&#95;&#95;doc&#95;&#95;) > print(Log.&#95;&#95;doc&#95;&#95;) > print(System.&#95;&#95;doc&#95;&#95;) > print(Component.&#95;&#95;doc&#95;&#95;) Simple example (For System, Component, please refer docstrings) > ''' import theo-framework ''' > from theo.framework import Log, DictList > ''' print log using Log ''' > Log.configure(print_enabled=True, store_enabled=True) : default of store_enable is False > log = Log('main') > log.print('info', 'Hello, theo-framework!') >> [2018-12-31 13:29:27,958][main][info] Hello, theo-framework! : log file will be stored. > ''' print csv file using DictList ''' > import os > kospi_dictlist = DictList('code') > kospi_dictlist.import_csv(os.path.join(os.getcwd(), 'kospi.csv')) > kospi_dictlist.print() >> DictList(num:1523/key:code) walkers(num:0) >> 0 {'code': '000020', 'tag': '', '250 days high': '13400.0', '250 days low': '7500.0', 'eps': '1683.0', 'market capitalization': '2623.0', 'net profit': '470.0', 'net sales': '2589.0', 'operating profit': '110.0', 'pbr': '0.88', 'per': '5.58', 'roe': '17.1'} >> 1 {'code': '000030', 'tag': 'kospi100/kospi50', '250 days high': '17400.0', '250 days low': '13550.0', 'eps': '2237.0', 'market capitalization': '108160.0', 'net profit': '15301.0', 'net sales': '85507.0', 'operating profit': '21567.0', 'pbr': '0.53', 'per': '7.15', 'roe': '7.4'} >> 2 {'code': '000040', 'tag': '', '250 days high': '760.0', '250 days low': '317.0', 'eps': '-263.0', 'market capitalization': '684.0', 'net profit': '-315.0', 'net sales': '417.0', 'operating profit': '-260.0', 'pbr': '1.51', 'per': '0.0', 'roe': '-61.3'} >> ... >> 1520 {'code': '590017', 'tag': '', '250 days high': '12600.0', '250 days low': '11020.0', 'eps': '0.0', 'market capitalization': '242.0', 'net profit': '0.0', 'net sales': '0.0', 'operating profit': '0.0', 'pbr': '0.0', 'per': '0.0', 'roe': '0.0'} >> 1521 {'code': '590018', 'tag': '', '250 days high': '13115.0', '250 days low': '7880.0', 'eps': '0.0', 'market capitalization': '173.0', 'net profit': '0.0', 'net sales': '0.0', 'operating profit': '0.0', 'pbr': '0.0', 'per': '0.0', 'roe': '0.0'} >> 1522 {'code': '900140', 'tag': '', '250 days high': '5650.0', '250 days low': '1750.0', 'eps': '311.0', 'market capitalization': '1209.0', 'net profit': '136.0', 'net sales': '3334.0', 'operating profit': '-226.0', 'pbr': '0.27', 'per': '8.11', 'roe': '3.4'} > ''' get datum ''' > print(kospi_dictlist.get_datum('000060')) >> {'code': '000060', 'tag': '', '250 days high': '25750.0', '250 days low': '17400.0', 'eps': '3479.0', 'market capitalization': '23532.0', 'net profit': '3846.0', 'net sales': '64287.0', 'operating profit': '5136.0', 'pbr': '1.28', 'per': '5.95', 'roe': '22.5'} > ''' get datum ''' > print(kospi_dictlist.get_datum('roe', '17.1')) >> {'code': '000020', 'tag': '', '250 days high': '13400.0', '250 days low': '7500.0', 'eps': '1683.0', 'market capitalization': '2623.0', 'net profit': '470.0', 'net sales': '2589.0', 'operating profit': '110.0', 'pbr': '0.88', 'per': '5.58', 'roe': '17.1'} > ''' get data ''' > print(kospi_dictlist.get_data([{'key': 'net sales', 'value': '0.0'}, {'key': 'net profit', 'value': '0.0'}])) >> [{'code': '000075', 'tag': '', '250 days high': '70900.0', '250 days low': '45050.0', 'eps': '0.0', 'market capitalization': '145.0', 'net profit': '0.0', 'net sales': '0.0', 'operating profit': '0.0', 'pbr': '0.0', 'per': '0.0', 'roe': '0.0'}, {'code': '000087', 'tag': '', '250 days high': '19200.0', '250 days low': '13550.0', 'eps': '0.0', 'market capitalization': '163.0', 'net profit': '0.0', 'net sales': '0.0', 'operating profit': '0.0', 'pbr': '0.0', 'per': '0.0', 'roe': '0.0'}, {'code': '000105', 'tag': '', '250 days high': '296000.0', '250 days low': '161000.0', 'eps': '0.0', 'market capitalization': '514.0', 'net profit': '0.0', 'net sales': '0.0', 'operating profit': '0.0', 'pbr': '0.0', 'per': '0.0', 'roe': '0.0'}, {'code': '000145', 'tag': '', '250 days high': '10700.0', '250 days low': '7020.0', 'eps': '0.0', 'market capitalization': '39.0', 'net profit': '0.0', 'net sales': '0.0', 'operating profit': '0.0', 'pbr': '0.0', 'per': '0.0', 'roe': '0.0'}, {'code': '000155', 'tag': '', '250 days high': '84300.0', '250 days low': '69800.0', 'eps': '0.0', 'market capitalization': '3427.0', 'net profit': '0.0', 'net sales': '0.0', 'operating profit': '0.0', 'pbr': '0.0', 'per': '0.0', 'roe': '0.0'}, ... > ''' export ''' >> kospi_dictlist.import_mongodb('kospi', 'codes') # Authors <NAME> - Owner of this project # License This project is licensed under the MIT License - see the LICENSE file for details # Versioning Basically, this project follows the 'Semantic Versioning'. (https://semver.org/) But, to notify new feature, I added several simple rules at the Semantic Versioning. I would like to call 'Theo Versioning'. - Version format is MAJOR.MINOR.PATCH - MAJOR version is increased when API is changed or when new feature is provided. - New feature does not affect a interface. - But, to notify new feature, New feature makes MAJOR version up. - Before official version release (1.0.0), MAJOR is kept 0 and MINOR version is used. - MINOR version is up when the API is added. (New functionality) - PATCH version is lifted when bug is fixed, test code is uploaded, comment or document or log is updated. <file_sep>import setuptools setuptools.setup( name='theo-framework', version='2.1.2', install_requires=['theo-database'], url='https://github.com/TheodoreWon/python-theo-framework', license='MIT', author='<NAME>', author_email='<EMAIL>', description='theo-framework', packages=['theo', 'theo.src.framework'], # long_description='GitHub : https://github.com/TheodoreWon/python-theo-framework', long_description=open('README.md').read(), long_description_content_type='text/markdown', zip_safe=False, ) ''' NOTE: How to make a package and release the software 0. pip install setuptools, pip install wheel, pip install twine 1. python setup.py bdist_wheel 2. cd dist 3. twine upload xxx.whl ''' <file_sep>import os import json import csv class DictList: """ DictList is a simple list structure. DictList stores a list what is consist of dictionaries. A variety of importing and exporting methods is supported. (JSON, CSV, MONGODB, etc.) And to refine a list, walker feature is supported. Attributes: key (str, optional): To support sorting and searching algorithm, a key is needed. If the key is set, all of the element dictionary should includes the key. Methods: dictlist = DictList(key=None) str(dictlist) dictlist.print(print_all=False) length = dictlist.count() : getting the count value how many dictionaries are stored element = dictlist.get(value) : getting the element what is matched with the stored key and argument value element = dictlist.get(key, value) : getting the element what is matched with argument key and argument value element = dictlist.get(queries) : getting the element what is matched with argument queries queries (list): the list of queries query (dictionary) : the key 'key', 'value' should be included to find list = dictlist.get_list() : getting the list what is stored list = dictlist.get_list(value) : getting the list what is matched with the stored key and argument value list = dictlist.get_list(key, value) : getting the list what is matched with argument key and argument value list = dictlist.get_list(queries) : getting the list what is matched with argument queries list = values(key, overlap=False, sort=False) dictlist.append(element) : appending argument element dictlist.insert(element) : inserting argument element at the first of the stored list dictlist.extend(dictlist) : extending the list from argument dictlist dictlist.extend_list(list) : extending the list dictlist.remove(element) : removing argument element if the element is exist in the stored list element = dictlist.pop(element) : poping argument element if the element is exist in the stored list dictlist.clear() : clear the stored list dictlist.import_json(file, encoding='UTF-8-sig') : importing the json data from json file dictlist.export_json(file, encoding='UTF-8-sig') : exporting the data what is stored list to csv file dictlist.import_csv(file, encoding='UTF-8-sig', separator=',') : importing the json data from json file dictlist.export_csv(file, encoding='UTF-8-sig') : exporting the data what is stored list to csv file file (str): the file path (ex. os.path.join(os.getcwd(), 'files', 'data.json')) dictlist.import_mongodb(database, collection, range_filter=None) : importing the data from mongodb dictlist.export_mongodb(database, collection) : exporting the datawhat is stored list to mongodb walker_handler = dictlist.plug_in_walker(walker, walker_delay=False, insert=False) dictlist.plug_out_walker(walker_handler) Example: contract_dictlist = DictList(key='name') contract_dictlist.import_csv(os.path.join(os.getcwd(), 'files', 'contract.csv')) contract_dictlist.print() contract_dictlist.append({'name': 'theo', 'email': '<EMAIL>'}) theo_contract = contract_dictlist.get('theo') print(theo_contract) : {'name': 'theo', 'email': '<EMAIL>'} """ def __init__(self, key=None): self.data = list() self.key = key if key is not None and isinstance(key, str) else None self.sorted = True self.walkers = list() def __str__(self): return f'DictList(num:{len(self.data)}/key:{self.key}' \ + (f')' if not len(self.walkers) else f'/walkers:{len(self.walkers)})') def print(self, print_all=None): try: if self.key is not None and not self.sorted: self.data.sort(key=lambda element: element[self.key]) self.sorted = True except Exception as error: print(f'error: {error} / dictlist.print(print_all:{print_all}/{type(print_all)})') print(f'\tno value for the key({self.key}) at', f'{list(filter(lambda element: self.key not in element, self.data))}') return try: print(str(self)) if print_all or len(self.data) <= 6: for index, element in enumerate(self.data): print(f'[index:{index}] {element}') else: for index in [0, 1, 2]: print(f'[index:{index}] {self.data[index]}') print('...') for index in [-3, -2, -1]: print(f'[index:{len(self.data) + index}] {self.data[index]}') except Exception as error: print(f'error: {error} / dictlist.print(print_all:{print_all}/{type(print_all)})') def count(self): return len(self.data) def get(self, attr1, attr2=None): try: if self.key and not self.sorted: self.data.sort(key=lambda element: element[self.key]) self.sorted = True except Exception as error: print(f'error: {error} / dictlist.get(attr1:{attr1}/{type(attr1)}, attr2:{attr2}/{type(attr2)})') print(f'\tno value for the key({self.key}) at', f'{list(filter(lambda element: self.key not in element, self.data))}') return None # element = get(queries) : getting the element what is matched with argument queries if not attr2 and isinstance(attr1, list): try: if not len(attr1): raise for element in self.data: for query in attr1: if not (query['key'] in element and element[query['key']] == query['value']): break else: return element return None except Exception as error: print(f'error: {error} / dictlist.get(queries:{attr1}/{type(attr1)})') print('\telement = dictlist.get(queries) : getting the element what is matched with argument queries') return None # element = dictlist.get(value) : getting the element what is matched with the stored key and argument value elif not attr2: try: left_index, right_index = 0, len(self.data) - 1 while left_index <= right_index: index = (left_index + right_index) // 2 if self.data[index][self.key] > attr1: right_index = index - 1 elif self.data[index][self.key] < attr1: left_index = index + 1 else: return self.data[index] return None except Exception as error: print(f'error: {error} / dictlist.get(value:{attr1}/{type(attr1)})') print('\telement = dictlist.get(value) : getting the element what is matched with the stored key and argument value') if len(self.walkers): print('\tif you set the key, the key could be cleared by activation of walker') return None # element = dictlist.get(key, value) : getting the element what is matched with argument key and argument value else: try: for element in self.data: if attr1 in element and element[attr1] == attr2: return element return None except Exception as error: print(f'error: {error} / dictlist.get(key:{attr1}/{type(attr1)}, value:{attr2}/{type(attr2)})') print('\telement = dictlist.get(key, value) : getting the element what is matched with argument key and argument value') return None def get_list(self, attr1=None, attr2=None): try: if self.key and not self.sorted: self.data.sort(key=lambda element: element[self.key]) self.sorted = True except Exception as error: print(f'error: {error} / dictlist.get_list(attr1:{attr1}/{type(attr1)}, attr2:{attr2}/{type(attr2)})') print(f'\tno value for the key({self.key}) at', f'{list(filter(lambda element: self.key not in element, self.data))}') return None # list = dictlist.get_list() : getting the list what is stored if attr1 is None and attr2 is None: return self.data # list = dictlist.get_list(queries) : getting the list what is matched with argument queries if not attr2 and isinstance(attr1, list): try: if not len(attr1): raise data = list() for element in self.data: for query in attr1: if not (query['key'] in element and element[query['key']] == query['value']): break else: data.append(element) return data except Exception as error: print(f'error: {error} / dictlist.get_list(queries:{attr1}/{type(attr1)})') print('\tlist = dictlist.get_list(queries) : getting the list what is matched with argument queries') return None # list = dictlist.get_list(value) : getting the list what is matched with the stored key and argument value elif not attr2: try: return list(filter(lambda element: element[self.key] == attr1, self.data)) except Exception as error: print(f'error: {error} / dictlist.get_list(value:{attr1}/{type(attr1)})') print('\tlist = dictlist.get_list(value) :', 'getting the list what is matched with the stored key and argument value') return None # list = dictlist.get_list(key, value) : getting the list what is matched with argument key and argument value else: try: return list(filter(lambda element: element[attr1] == attr2, self.data)) except Exception as error: print(f'error: {error} / dictlist.get_list(key:{attr1}/{type(attr1)}, value:{attr2}/{type(attr2)})') print('\tlist = dictlist.get_list(key, value) :', 'getting the list what is matched with argument key and argument value') return None def values(self, key, overlap=False, sort=False): try: if self.key and not self.sorted: self.data.sort(key=lambda element: element[self.key]) self.sorted = True except Exception as error: print(f'error: {error} / dictlist.values(key:{key}/{type(key)})') print(f'\tno value for the key({self.key}) at', f'{list(filter(lambda element: self.key not in element, self.data))}') return None try: values = list(map(lambda element: element[key], filter(lambda element: key in element, self.data))) if not overlap: values = list(set(values)) if sort: values.sort() return values except Exception as error: print(f'error: {error} / dictlist.values(key:{key}/{type(key)},', f'overlap:{overlap}/{type(overlap)}, sort:{sort}/{type(sort)})') return None def append(self, element): try: self.data.append(element) self.sorted = False self.run_walker() except Exception as error: print(f'error: {error} / dictlist.append(element:{element}/{type(element)})') def insert(self, element): try: self.data.insert(0, element) self.sorted = False self.run_walker() except Exception as error: print(f'error: {error} / dictlist.insert(element:{element}/{type(element)})') def extend(self, dictlist): try: if dictlist.count(): self.data.extend(dictlist.get_list()) self.sorted = False self.run_walker() except Exception as error: print(f'error: {error} / dictlist.extend(dictlist:{dictlist}/{type(dictlist)})') def extend_list(self, data): try: if len(data): self.data.extend(data) self.sorted = False self.run_walker() except Exception as error: print(f'error: {error} / dictlist.extend_list(list:{data}/{type(data)})') def remove(self, element): try: self.data.remove(element) except Exception as error: print(f'error: {error} / dictlist.remove(element:{element}/{type(element)})') def pop(self, element): try: if element in self.data: self.data.remove(element) return element return None except Exception as error: print(f'error: {error} / dictlist.remove(element:{element}/{type(element)})') return None def clear(self): self.data.clear() self.sorted = True def import_json(self, file, encoding='UTF-8-sig'): try: if os.path.exists(file): file_handler = open(file, 'r', encoding=encoding) data = json.load(file_handler) file_handler.close() if len(data): self.data.extend(data) self.sorted = False self.run_walker() except Exception as error: print(f'error: {error} / dictlist.import_json(file:{file}/{type(file)},', f'encoding:{encoding}/{type(encoding)})') def export_json(self, file, encoding='UTF-8-sig'): try: if self.key and not self.sorted: self.data.sort(key=lambda element: element[self.key]) self.sorted = True except Exception as error: print(f'error: {error} / dictlist.import_json(file:{file}/{type(file)}, encoding:{encoding}/{type(encoding)})') print(f'\tno value for the key({self.key}) at', f'{list(filter(lambda element: self.key not in element, self.data))}') return None try: if len(self.data): if not os.path.exists(os.path.dirname(os.path.abspath(file))): os.makedirs(os.path.dirname(os.path.abspath(file))) file_handler = open(file, 'w', encoding=encoding) json.dump(self.data, file_handler, ensure_ascii=False, indent="\t") file_handler.close() except Exception as error: print(f'error: {error} / dictlist.import_json(file:{file}/{type(file)},', 'encoding:{encoding}/{type(encoding)})') def import_csv(self, file, encoding='UTF-8-sig', separator=','): try: if os.path.exists(file): file_handler = open(file, 'r', encoding=encoding) csv_reader = csv.reader(file_handler, delimiter=separator) data = list() for index, values in enumerate(csv_reader): if index == 0: keys = list(map(lambda value: value, values)) else: element = dict() for key_index, key in enumerate(keys): if values[key_index]: element[key] = values[key_index] data.append(element) file_handler.close() if len(data): self.data.extend(data) self.sorted = False self.run_walker() except Exception as error: print(f'error: {error} / dictlist.import_csv(file:{file}/{type(file)},', f'encoding:{encoding}/{type(encoding)})') def export_csv(self, file, encoding='UTF-8-sig'): try: if self.key and not self.sorted: self.data.sort(key=lambda element: element[self.key]) self.sorted = True except Exception as error: print(f'error: {error} / dictlist.export_csv(file:{file}/{type(file)}, encoding:{encoding}/{type(encoding)})') print(f'\tno value for the key({self.key}) at' f'{list(filter(lambda element: self.key not in element, self.data))}') return None try: if len(self.data): if not os.path.exists(os.path.dirname(os.path.abspath(file))): os.makedirs(os.path.dirname(os.path.abspath(file))) file_handler = open(file, 'w', encoding=encoding, newline='\n') keys = list(self.data[0].keys()) csv_writer = csv.writer(file_handler) csv_writer.writerow(keys) for element in self.data: csv_writer.writerow(list(map(lambda key: str(element.get(key)) if key in element else '', keys))) file_handler.close() except Exception as error: print(f'error: {error} / dictlist.export_csv(file:{file}/{type(file)},', f'encoding:{encoding}/{type(encoding)})') def import_mongodb(self, database, collection, range_filter=None): try: from theo.src.framework.System import System from theo.database import MongoDB if 'MongoDBCtrl' in System.get_components(): data = System.execute_interface( 'MongoDBCtrl', 'select', database, collection, self.key, None, range_filter) else: mongodb = MongoDB() data = mongodb.select(database, collection, sorting_key=self.key, range=range_filter) del mongodb if len(data): self.data.extend(data) self.sorted = False self.run_walker() except Exception as error: print(f'error: {error} / dictlist.import_mongodb(database:{database}/{type(database)},', f'collection:{collection}/{type(collection)}, range:{range}/{type(range)})') def export_mongodb(self, database, collection): try: if self.key and not self.sorted: self.data.sort(key=lambda element: element[self.key]) self.sorted = True except Exception as error: print(f'error: {error} / dictlist.export_mongodb(database:{database}/{type(database)},', f'collection:{collection}/{type(collection)})') print(f'tno value for the key({self.key}) at', f'{list(filter(lambda element: self.key not in element, self.data))}') return None try: if len(self.data): from theo.src.framework.System import System from theo.database import MongoDB if 'MongoDBCtrl' in System.get_components(): System.execute_interface('MongoDBCtrl', 'insert', database, collection, self.data, self.key) else: mongodb = MongoDB() mongodb.insert(database, collection, self.data, unique_key=self.key) del mongodb except Exception as error: print(f'error: {error} / dictlist.export_mongodb(database:{database}/{type(database)},', f'collection:{collection}/{type(collection)})') def plug_in_walker(self, walker, walker_delay=False, insert=False): try: if self.key and not self.sorted: self.data.sort(key=lambda element: element[self.key]) self.sorted = True except Exception as error: print(f'error: {error} / dictlist.plug_in_walker(walker:{walker}/{type(walker)},', f'walker_delay:{walker_delay}/{type(walker_delay)}, insert:{insert}/{type(insert)})') print(f'\tno value for the key({self.key}) at', f'{list(filter(lambda element: self.key not in element, self.data))}') return None try: handler = {'index': 0, 'walker': walker} if insert: self.walkers.insert(0, handler) else: self.walkers.append(handler) if not walker_delay: self.run_walker() self.key = None return handler except Exception as error: print(f'error: {error} / dictlist.plug_in_walker(walker:{walker}/{type(walker)},', f'walker_delay:{walker_delay}/{type(walker_delay)}, insert:{insert}/{type(insert)})') return None def plug_out_walker(self, handler): try: self.walkers.remove(handler) except Exception as error: print(f'error: {error} / dictlist.plug_out_walker(handler:{handler}/{type(handler)})') def run_walker(self): try: if len(self.walkers): index = min(map(lambda walker: walker['index'], self.walkers)) while index != len(self.data): for walker in self.walkers: if walker['index'] == index: walker['walker'](self.data[index]) walker['index'] = walker['index'] + 1 index = index + 1 except Exception as error: print(f'error: {error} / dictlist.run_walker()')
2f308b36ad364e9c5d4de82725f24aa0a817cf6e
[ "Markdown", "Python" ]
7
Python
TaeheeWon/python-theo-framework
0ef99eec503970cf04d0ab89596faee791b27a09
4f3b8c6006d88d6c9cc72ec2ab8e5874de979d33
refs/heads/master
<repo_name>huntingmarco/project<file_sep>/spec/models/project_task_validation_spec.rb require 'rails_helper' RSpec.describe ProjectTask, :type => :model do describe "Project task model test" do subject { described_class.new(content: "Anything", deadline: DateTime.now, created_at: DateTime.now, updated_at: DateTime.now) } it "is valid with valid attributes" do expect(subject).to be_valid end it "is not valid without a content" do subject.content = nil expect(subject).to_not be_valid end it "is not valid without a deadline" do subject.deadline = nil expect(subject).to_not be_valid end end end<file_sep>/spec/models/project_list_validation_spec.rb require 'rails_helper' RSpec.describe ProjectList, :type => :model do describe "Project List model test" do subject { described_class.new(title: "Anything", description: "Lorem ipsum", user_id: 1) } it "is valid with valid attributes" do expect(subject).to be_valid end it "is not valid without a title" do subject.title = nil expect(subject).to_not be_valid end it "is not valid without a description" do subject.description = nil expect(subject).to_not be_valid end describe "Associations" do it { should belong_to(:user).without_validating_presence } it { should have_many(:project_tasks).dependent(:destroy) } end end end<file_sep>/app/controllers/project_tasks_controller.rb class ProjectTasksController < ApplicationController before_action :set_project_list before_action :set_project_task, except: [:create,:new] def new @project_task = @project_list.project_tasks.create end def edit #@project_task = @project_list.project_tasks.find(params[:id]) #@project_task = ProjectTask.find(params[:id]) end def create @project_task = @project_list.project_tasks.create(project_task_params) respond_to do |format| if @project_task.save format.js else #flash[:msg] = "invalid" format.js { render 'displaymessages.js.erb' } end end end def update respond_to do |format| if @project_task.update(project_task_params) format.js else format.js { render 'displaymessages.js.erb' } end end end def destroy @project_task = @project_list.project_tasks.find(params[:id]) @project_task.destroy respond_to do |format| format.js end end def done @project_task.update_attribute(:done_at, Time.now) respond_to do |format| format.js end end private def set_project_list @project_list = ProjectList.find(params[:project_list_id]) end def set_project_task @project_task = @project_list.project_tasks.find(params[:id]) end def project_task_params params[:project_task].permit(:content, :deadline, file:[]) end end <file_sep>/config/routes.rb Rails.application.routes.draw do devise_for :users, controllers: { omniauth_callbacks: "omniauth" } #was add for user login test devise_scope :user do get 'sign_in', to: 'devise/sessions#new' end resources :project_lists do resources :project_tasks do member do patch :done end end end #was add for user login test resources :user_session root "project_lists#index" end <file_sep>/spec/factories/user.rb FactoryGirl.define do factory :user do |f| f.email "<EMAIL>" f.password "<PASSWORD>" f.password_confirmation "<PASSWORD>" end end<file_sep>/spec/features/project_list_matching_spec.rb require 'rails_helper' RSpec.describe "Home page matcing" do it "it displays the name of the app" do visit('/project_lists') expect(page).to have_content('Project') click_link('login') expect(current_path).to eql('/users/sign_in') expect(page).to have_content('Email') end end<file_sep>/test/system/project_lists_test.rb require "application_system_test_case" class ProjectListsTest < ApplicationSystemTestCase setup do @project_list = project_lists(:one) end test "visiting the index" do visit project_lists_url assert_selector "h1", text: "Project Lists" end test "creating a Project list" do visit project_lists_url click_on "New Project List" fill_in "Description", with: @project_list.description fill_in "Title", with: @project_list.title click_on "Create Project list" assert_text "Project list was successfully created" click_on "Back" end test "updating a Project list" do visit project_lists_url click_on "Edit", match: :first fill_in "Description", with: @project_list.description fill_in "Title", with: @project_list.title click_on "Update Project list" assert_text "Project list was successfully updated" click_on "Back" end test "destroying a Project list" do visit project_lists_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Project list was successfully destroyed" end end <file_sep>/db/migrate/20200923055850_add_done_at_to_project_tasks.rb class AddDoneAtToProjectTasks < ActiveRecord::Migration[6.0] def change add_column :project_tasks, :done_at, :datetime end end <file_sep>/app/models/project_list.rb class ProjectList < ApplicationRecord validates :title, presence:true validates :description, presence:true has_many :project_tasks, dependent: :destroy belongs_to :user end <file_sep>/app/controllers/project_lists_controller.rb class ProjectListsController < ApplicationController before_action :set_project_list, only: [:show, :edit, :update, :destroy] before_action :authenticate_user!, except: [:index, :show] # GET /project_lists # GET /project_lists.json def index @project_lists = ProjectList.all end # GET /project_lists/1 # GET /project_lists/1.json def show end # GET /project_lists/new def new @project_list = current_user.project_lists.build end # GET /project_lists/1/edit def edit end # POST /project_lists # POST /project_lists.json def create @project_list = current_user.project_lists.build(project_list_params) respond_to do |format| if @project_list.save format.js else #flash[:msg] = "invalid" format.js { render 'displaymessages.js.erb' } end end end # PATCH/PUT /project_lists/1 # PATCH/PUT /project_lists/1.json def update respond_to do |format| if @project_list.update(project_list_params) format.js else format.js { render 'displaymessages.js.erb' } end end end # DELETE /project_lists/1 # DELETE /project_lists/1.json def destroy respond_to do |format| @project_list.destroy format.js end end private # Use callbacks to share common setup or constraints between actions. def set_project_list @project_list = ProjectList.find(params[:id]) end # Only allow a list of trusted parameters through. def project_list_params params.require(:project_list).permit(:title, :description) end end <file_sep>/spec/features/login_matching_spec.rb require 'rails_helper' RSpec.describe "Signin" do it "it displays the signin content of the app" do visit('/users/sign_in') expect(page).to have_content('Log in') end end<file_sep>/spec/features/user_login_spec.rb require 'rails_helper' feature 'Visitor signs in' do scenario 'with valid email and password' do create_user '<EMAIL>', '<PASSWORD>' sign_in_with '<EMAIL>', '<PASSWORD>' user_should_be_signed_in end scenario 'tries with invalid password' do create_user '<EMAIL>', '<PASSWORD>' sign_in_with '<EMAIL>', '<PASSWORD>' page_should_display_sign_in_error user_should_be_signed_out end private def create_user(email, password) FactoryGirl.create(:user, :email => email, :password => <PASSWORD>,:password_confirmation => <PASSWORD>) end def sign_in_with(email, password) visit sign_in_path fill_in 'user_email', :with => email fill_in 'user_password', :with => <PASSWORD> click_button "Log in" end def user_should_be_signed_in visit root_path page.should have_content('logout') end def user_should_be_signed_out page.should have_content('login') end def page_should_display_sign_in_error #page.should have_css('div.error', 'Invalid email or password') page.should have_content('Log in') end end<file_sep>/app/models/project_task.rb class ProjectTask < ApplicationRecord validates :content, presence:true validates :deadline, presence:true belongs_to :project_list, optional: true has_many_attached :file def done? !done_at.blank? end end
c630dc6778c93d97dff5e2eba2d18530594966af
[ "Ruby" ]
13
Ruby
huntingmarco/project
299c87f48bec9ab073b348dc12b471d718ec9557
22a63eb9b96ca950a32be94dee3da83fd412127e
refs/heads/master
<repo_name>kinget007/proxy<file_sep>/test.py import datetime import json import urllib import mitmproxy.http from mitmproxy import ctx class Counter: def __init__(self): self.num = 0 def request(self, flow: mitmproxy.http.HTTPFlow): if flow.request.host == 'www.google.com': return # if flow.request.path.find(".") == -1 and flow.request.path.find("track") == -1 and (flow.request.host.find("yeshj") > -1 or flow.request.host.find("hujiang") > -1): else: ctx.log.info("--------------------------------------------------------------------------------------") self.num = self.num + 1 timestamp_ = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') result = { "num": self.num, "url": flow.request.pretty_url, "method": str(flow.request.method), "query": urllib.parse.unquote(str(flow.request.query).replace("\\x", "%").replace('MultiDictView', ''), encoding='utf-8', errors='replace'), "post_data": urllib.parse.unquote(str(flow.request.raw_content).replace("\\x", "%"), encoding='utf-8', errors='replace'), # "HJ_UID": str(flow.request.cookies.get('HJ_UID')), "time": timestamp_ } import os import logging logging.basicConfig(filename=os.path.join('/home/log/', 'log.log'), level=logging.INFO, format='') logging.info(json.dumps(result)) addons = [ Counter() ] <file_sep>/Dockerfile FROM alpine:3.8 ENV LANG=en_US.UTF-8 ADD log.log /home/log/log.log ADD test.py /home/rule/test.py ADD mitmproxy-4.0.4-py3-none-any.whl /home/mitmproxy/mitmproxy-4.0.4-py3-none-any.whl # Add our user first to make sure the ID get assigned consistently, # regardless of whatever dependencies get added. RUN apk add --no-cache \ git \ g++ \ libffi \ libffi-dev \ libstdc++ \ openssl \ openssl-dev \ python3 \ python3-dev \ && python3 -m ensurepip \ && LDFLAGS=-L/lib pip3 install -U /home/mitmproxy/mitmproxy-4.0.4-py3-none-any.whl \ && apk del --purge \ git \ g++ \ libffi-dev \ openssl-dev \ python3-dev \ && rm -rf ~/.cache/pip /home/mitmproxy/mitmproxy-4.0.4-py3-none-any.whl \ && mkdir -p /home/mitmproxy/.mitmproxy VOLUME /root/.mitmproxy VOLUME /home/log/ EXPOSE 8080 CMD mitmdump -s /home/rule/test.py
baa2cc09f9853367ee310bbc24f415e9cd2272f2
[ "Python", "Dockerfile" ]
2
Python
kinget007/proxy
ebfda50eec729ce7178ceca077eade3ca27eeb6f
1e273407e7043903c6d13545e498c737594fb928
refs/heads/master
<file_sep>import React,{useState,useEffect } from 'react'; import './App.css'; import image from './Assets/Images/instagram.png'; //import images from './Assets/Images/myimage.jpg'; //import img from '. /Assets/Images/image2.JPG'; import {db,auth } from './Firebase'; import Modal from './Modal/Modal'; import Aux from './hoc/Auxilliary'; import Post from './Posts/Post/Post'; import {Button,Input} from '@material-ui/core'; import PostUpload from './PostUpload/PostUpload'; function App() { const[posts,setPosts]=useState([]); const[show,setShow]=useState(null); const[username,setUsername]=useState(''); const[email,setEmail]=useState(''); const[password,setPassword]=useState(''); const[user,setUser]=useState(null); const[openSignIn,setOpenSignIn]= useState(null); useEffect(()=>{ const unsuscribe=auth.onAuthStateChanged((authUser)=>{ if(authUser){ //user is logged in console.log(authUser); setUser(authUser); }else{ //user has logged out setUser(null); } }) return ()=>{ //perform some cleanup actions unsuscribe(); } },[user,username]); useEffect(()=>{ db.collection('posts').orderBy('timestamp','desc').onSnapshot(snapshot=>{ // console.log(snapshot.docs); setPosts(snapshot.docs.map(doc =>( { id: doc.id, post: doc.data() } ) )); }) },[]); const signUp=(event)=>{ event.preventDefault(); auth.createUserWithEmailAndPassword(email,password) .then((authUser)=>{ authUser.user.updateProfile({ displayName: username, }) setShow(!show); }) .catch((error)=>alert(error.message)) } const signIn=(event)=>{ event.preventDefault(); auth.signInWithEmailAndPassword(email,password) .catch((error)=> alert(error.message)); setOpenSignIn(!openSignIn); } return ( <Aux> <Modal show={show} clicked={()=>setShow(!show)}> <div> <form className="app__signup"> <center> <img className="app__headerImage" src={image} alt="" /> </center> <Input type="text" placeholder="username" value={username} onChange={(e)=>setUsername(e.target.value)} /> <Input type="text" placeholder="email" value={email} onChange={(e)=>setEmail(e.target.value)} /> <Input type="password" placeholder="<PASSWORD>" value={password} onChange={(e)=>setPassword(e.target.value)} /> <Button type="submit" onClick={signUp}>Sign UP</Button> </form> </div> </Modal> <Modal show={openSignIn} clicked={()=>setOpenSignIn(!openSignIn)}> <div> <form className="app__signup"> <center> <img className="app__headerImage" src={image} alt="" /> </center> <Input type="text" placeholder="email" value={email} onChange={(e)=>setEmail(e.target.value)} /> <Input type="<PASSWORD>" placeholder="<PASSWORD>" value={<PASSWORD>} onChange={(e)=>setPassword(e.target.value)} /> <Button type="submit" onClick={signIn}>Sign In</Button> </form> </div> </Modal> <div className="app"> <div className="app__header"> <img className="app__headerImage" src={image} alt=""/> {user?<Button onClick={()=> auth.signOut()}>Log Out</Button> : ( <div className="app__loginContainer"> <Button onClick={()=>setShow(true)}>Sign Up</Button> <Button onClick={()=>setOpenSignIn(true)}>Sign In</Button> </div> ) } </div> { user?.displayName ? <PostUpload username={user.displayName}/>: <h3>Sorry you need to login to Upload</h3> } { posts.map(({id,post})=>( <Post key={id} postId={id} user={user?.displayName} username={post.username } image={post.image} caption={post.caption}/> )) } {/* Header */} {/*Posts*/} {/*Posts*/} </div> </Aux> ); } export default App; <file_sep>import React ,{useState}from 'react'; import {storage, db} from "../Firebase.js"; import {Button} from '@material-ui/core'; import firebase from "firebase"; import './PostUpload.css'; function PostUpload(props){ const [image,setImage]=useState(null); const[caption,setCaption]=useState(''); const[url,setUrl]=useState(''); const[progress,setProgress]=useState(0); const handleChange= e=>{ if(e.target.files[0]){ setImage(e.target.files[0]); } }; const handleUpload=()=>{ const uploadTask =storage.ref(`images/${image.name}`).put(image); uploadTask.on("state_changed", (snapShot)=>{ //progress function const progress=Math.round( (snapShot.bytesTransferred/snapShot.totalBytes)*100 ); setProgress(progress); }, (error)=>{ //this is where we show error occured during upload alert(error.message); }, ()=>{ //this is the section whis shows what is to be done when upload is complete storage.ref("images") .child(image.name) .getDownloadURL() .then( url=>{ //post image inside db db.collection("posts").add({ timestamp:firebase.firestore.FieldValue.serverTimestamp(), caption:caption, image:url, username: props.username }); setProgress(0); setCaption(""); setImage(null); } ); }) } return( <div className="postUpload"> <progress value={progress} max="100"/> <input type="text" placeholder="Enter a caption.." onChange={event=>setCaption(event.target.value)} value={caption}/> <input className="imageUpload" type="file" onChange={handleChange}/> <Button className="imageUpload__button" onClick={handleUpload}>Upload</Button> </div> ); } export default PostUpload;<file_sep>import React from 'react'; import "./AddComment.css"; const AddComment= (props)=>{ return( <div className="comment"> {props.children} <form className="comment__form"> <input className="comment__input" placeholder="Add Comment...." type="text" value={props.comment} onChange={props.onChange} /> <button className="comment__button" type="submit" onClick={props.postComment}>Post</button> </form> </div> ); } export default AddComment;<file_sep> import firebase from "firebase"; const firebaseApp= firebase.initializeApp({ apiKey: "<KEY>", authDomain: "instagram-ce43a.firebaseapp.com", databaseURL: "https://instagram-ce43a.firebaseio.com", projectId: "instagram-ce43a", storageBucket: "instagram-ce43a.appspot.com", messagingSenderId: "917211046268", appId: "1:917211046268:web:981709472d5a04d45604f9", measurementId: "G-C26NVP7CKR" }); const db=firebaseApp.firestore(); const auth= firebase.auth(); const storage= firebase.storage(); export {db,auth,storage};
55285bc107a4bb7d57a7e51b8c521ff041639784
[ "JavaScript" ]
4
JavaScript
adhikariprakriti/mini-instagram
3ad85793ed2d5988d19b3df7029714623c9199da
3a1312272657fcc2936b75a79239af86bda34224
refs/heads/main
<repo_name>african-market-allstars/front-end<file_sep>/front-end/src/Components/About.js import { useState } from "react" import axios from 'axios'; import "./About.css"; export default function About() { const feedbackForm = { name: "", email: "", feedbackField: "" } const [feedback, setFeedback] = useState(feedbackForm) const onChange = event => { const { name, value, type } = event.target setFeedback({ ...feedback, [name]: value }) } const onSubmit = event => { event.preventDefault() const newFeedback = { name: feedback.name.trim(), email: feedback.email.trim(), feedbackField: feedback.feedbackField.trim() } axios.post("https://reqres.in/api/users", newFeedback) .then((response) => { console.log(response.data); }) .catch((error) => { console.log(error) }) } return ( <div> <h1>Who we are</h1> <p className="bioAndFeedback"> Even since all the way back during 3500 BCE when African Marketplace was first founded, it has never stopped being our mission to connect customers from all around the world with venders who sell quality products. It does not matter whether you are from Italy, Peru, Ethiopia, Cananda, Taiwan, or even Austrailia; we assure you that whereever you buy a product from, that it will arrive on your doorstep as if you bought it from town! </p> <p className="bioAndFeedback"> We would love to know how your experience with our site has been! By filling out the form below you help us make African Marketplace the best place for goods from around the world. </p> <form onSubmit={onSubmit}> <label> Name <input name='name' type='text' value={feedback.name} onChange={onChange} /> </label> <label> Email <input name='email' type='email' value={feedback.email} onChange={onChange} /> </label> <label> Feedback <input name='feedbackField' type='text' value={feedback.feedbackField} onChange={onChange} /> </label> <button className="submit"> Submit </button> </form> <h2>Contact</h2> <p>Email: <EMAIL></p> <p>Phone: 1-800-233-2012 (Available 10am - 7pm EST all 7 days of the week)</p> <p>Address: 465 Stracke Roads, Norfolk, ZA, South Africa</p> </div> ) } <file_sep>/front-end/src/Components/EditItem.js import React from 'react' import { makeStyles } from '@material-ui/core/styles'; import { TextField } from '@material-ui/core'; import Button from '@material-ui/core/Button'; const EditItem = ({itemToEdit , setItemToEdit , currentEdit , setEditing}) => { const useStyles = makeStyles((theme) => ({ root: { backgroundColor: '#f3f3f3', width:'35%', borderRadius: '25px', margin: 'auto', '& > *': { margin: theme.spacing(1), width: '25ch', }, }, card: { display: 'flex', flexWrap:'wrap', width:'90%', marginLeft:'5%', justifyContent:'space-around', alignItems: 'center' }, button: { backgroundColor: '#1EBA4D', color: 'white' } })); const classes = useStyles(); return( <form className={classes.root} onSubmit={currentEdit}> <TextField id="standard-basic" label="Item Name" name = 'name' type = 'text' value = {itemToEdit.name} onChange = {(e) => setItemToEdit({...itemToEdit , name: e.target.value})} /> <TextField id="standard-basic" label = "Category" name = 'category' type = 'text' value = {itemToEdit.category} onChange = {(e) => setItemToEdit({...itemToEdit , category: e.target.value})} /> <TextField id="standard-basic" label = "Price" name = 'price' type = 'text' value = {itemToEdit.price } onChange = {(e) => setItemToEdit({...itemToEdit , price: e.target.value})} /> <TextField id="standard-basic" label = "Description" name = 'description' value = {itemToEdit.description} onChange = {(e) => setItemToEdit({...itemToEdit , description: e.target.value})} multiline /> <Button className={classes.button} variant="contained" type="submit">Submit</Button> <Button color="secondary" variant="contained" onClick={() => setEditing(false)}>Cancel</Button> </form> ) } export default EditItem<file_sep>/front-end/src/reducers/index.js import { GET_ITEMS, GET_ITEMS_SUCCESS, GET_ITEMS_FAILURE, UPDATE_ITEM, DELETE_ITEM } from "../actions" const initialState = { itemList: [], items: { name:'', price: '', image: '', category:'', description: '' }, isLoading: false, error: '' } export const reducer = ( state = initialState, action) => { switch( action.type) { case GET_ITEMS: return { ...state, isLoading:true } case GET_ITEMS_SUCCESS: return { ...state, itemList: action.payload, isLoading: false } case GET_ITEMS_FAILURE: return { ...state, isLoading: false, error:action.payload } case UPDATE_ITEM: return { ...state, items: action.payload, isLoading: false } case DELETE_ITEM: return { ...state, items: action.payload, isLoading: false } default: return state } }<file_sep>/front-end/src/actions/index.js import axios from 'axios' export const GET_ITEMS = 'GET_ITEMS' export const GET_ITEMS_SUCCESS = 'GET_ITEMS_SUCCESS' export const GET_ITEMS_FAILURE = 'GET_ITEMS_FAILURE' export const UPDATE_ITEM = 'UPDATE_ITEM' export const DELETE_ITEM = 'DELETE_ITEM' export const getItems = () => (dispatch) => { axios.get('https://african-market-allstars.herokuapp.com/api/items') .then( res => { console.log( 'items found', res) dispatch({ type:GET_ITEMS_SUCCESS, payload: { name: res.data.name, category: res.data.category, image: res.data.image_url, price: res.data.price, description: res.data.description } }) }) .catch( err => { console.log('items not found', err.message) dispatch({ type: GET_ITEMS_FAILURE, payload: err.message }) } ) } <file_sep>/front-end/src/Components/Profile.js // import axios from 'axios' import axios from 'axios'; import React, { useEffect, useState } from 'react' import { useParams } from 'react-router'; import { axiosWithAuth } from '../Utilities/axiosWithAuth'; import EditItem from './EditItem' import { makeStyles } from '@material-ui/core/styles'; import { TextField } from '@material-ui/core'; import Button from '@material-ui/core/Button'; import ItemCard from './ItemCard' import { connect } from 'react-redux' import {getItems} from '../actions' const Profile = () => { // INITIAL FORM DATA const initialForm = { name: '', category: '', price: '', description: '' }; // STATE const [itemList , setItemList] = useState([]) const [item , setItem] = useState(initialForm) const [editing , setEditing] = useState(false) const [itemToEdit , setItemToEdit] = useState(initialForm) // GET ALL ITEMS useEffect( () => { axios.get('https://african-market-allstars.herokuapp.com/api/items') .then(res => { console.log(res) setItemList(res.data) }) .catch(err => console.log(err)) },[] ) // INPUT CHANGE HANDLER const onChange = (e) => { const {name , value} = e.target setItem({ ...item, [name]: value, }); }; // POST NEW ITEM const postItem = item => { // axiosWithAuth().post(`https://african-market-allstars.herokuapp.com/api/users/${params.id}/items`, item) axiosWithAuth().post("https://reqres.in/api/order", item) .then(res => { console.log(res) setItemList([...itemList , res.data]) }) .catch( err => console.log('error', err)) } // HANDLE SUBMIT const onSubmit = (e) => { e.preventDefault() postItem(item) setItem(initialForm) }; // EDIT ITEMS const editItem = item => { setEditing(true) setItemToEdit(item) } const currentEdit = e => { e.preventDefault() // axiosWithAuth().put(`https://african-market-allstars.herokuapp.com/api/users${params.id}/items/${itemToEdit.id}`, itemToEdit) axiosWithAuth().put(`https://reqres.in/api/users/${itemToEdit.id}`, itemToEdit) .then( res => { console.log(res) setEditing(false) const modifiedItem = res.data setItemList( itemList.map( item => { if(item.id === modifiedItem.id){ return modifiedItem } return item } ) ) }) .catch(err => console.log(err)) } // DELETE ITEM const deleteItem = item => { axiosWithAuth().delete(`https://reqres.in/api/users/${item.id}`, item) .then( res => { console.log( res) const updateList = itemList.filter( item => item.id !== Number(res.data) ) setItemList(updateList) }) .catch( err => console.log(err)) } const useStyles = makeStyles((theme) => ({ root: { backgroundColor: '#f3f3f3', width:'35%', borderRadius: '25px', margin: 'auto', '& > *': { margin: theme.spacing(1), width: '25ch', }, }, card: { display: 'flex', flexWrap:'wrap', width:'90%', marginLeft:'5%', justifyContent:'space-around', alignItems: 'center' }, button: { backgroundColor: '#1EBA4D', color: 'white' } })); const classes = useStyles(); const params = useParams(); console.log(params) return ( <div> <section className='intro'> <h1>Welcome Back {params.id} !</h1> <h3>Thanks for being a beautiful human</h3> <h5>Let's post a new item to the market</h5> </section> { editing && <EditItem itemToEdit = {itemToEdit} setItemToEdit={setItemToEdit} currentEdit ={currentEdit} setEditing={setEditing} /> } {!editing && <form className={classes.root} onSubmit = {onSubmit}> <TextField id="standard-basic" label="Item Name" name = 'name' type = 'text' value = {item.itemName} onChange = {onChange} /> <TextField id="standard-basic" label = "Category" name = 'category' type = 'text' value = {item.category} onChange = {onChange} /> <TextField id="standard-basic" label = "Price" name = 'price' type = 'text' value = {item.price } onChange = {onChange} /> <TextField id="standard-basic" label = "Description" name = 'description' value = {item.description} onChange = {onChange} multiline /> <Button className={classes.button} variant="contained">Submit</Button> </form> } <section className={classes.card}> {itemList.map( item => ( <ItemCard item={item} editItem={editItem} deleteItem={deleteItem} /> ) )} </section> </div> ) } // const mapStateToProps = state => ({ // items: state.items // }) export default Profile
01ee6101ae6ae176c7ab87d0ebad5260ff20c198
[ "JavaScript" ]
5
JavaScript
african-market-allstars/front-end
d29a3d4fe6e31ba83332e6eb65e794ab994411fe
c7f039b7f80ac15d283e44d79d781f40856efdeb
refs/heads/master
<file_sep>#!/usr/bin/python3 import matplotlib.pyplot import numpy if __name__ == "__main__": x_points = [] y_points = [] data = open("plotpoints.txt", 'r') data_list = list(data) for points in data_list: coordinates = points.strip().split(",") print(coordinates[0] + " , " + coordinates[1]) x_points.append(coordinates[0]) y_points.append(coordinates[1]) matplotlib.pyplot.scatter(x_points, y_points) matplotlib.pyplot.show() <file_sep>#!/usr/bin/python3 import numpy if __name__ == "__main__": y_points = [] x_points = list(range(0,1000)) for x_point in x_points: new_point = 45 * numpy.sin(x_point) y_points.append(new_point) print(y_points) print(x_points) data = open("plotpoints.txt", 'w') for i in range(0, len(x_points)): line = (str(x_points[i]) + "," + str(y_points[i]) + "\n") data.write(line)
e166c6dcd1d5bb353e23c0d31c945e7f79e97ed8
[ "Python" ]
2
Python
mseryn/beginners_programming_workshops
1c57ec94807d8cf262d4b88318e699ba8ff48055
96f96dd93be56a04c0af522cd2b76536947ba977
refs/heads/main
<repo_name>justinnature1/JavaFactoryPattern<file_sep>/src/javaFactoryPattern/Weapon.java package javaFactoryPattern; import java.util.Date; public abstract class Weapon { protected int damage = 0; protected int attackSpeed = 0; protected double criticalHitPercent = 0; private long lastAttack = 0; //Stores the time in milliseconds since the last successful attack protected String description = "Unnamed Weapon"; public double getCriticalHitPercent(){ return criticalHitPercent; } public int getAttackSpeed() { return attackSpeed; } public int getDamage() { return damage; } //Displays the weapons statistics public String weaponStats() { return "\tDamage: " + getDamage() + "\n\tAttackSpeed: " + getAttackSpeed() + "\n\tCritical Hit: " + String.format("%.1f", getCriticalHitPercent() * 100) + "%"; } public String getDescription() { return description; } /*Determines the damage done to an enemy during a successful attack. The attack function would be a good candidate for the Strategy Design Pattern. There can be ranged attacks (a bow) or special attacks/weapons such as magical spells. */ public int attack() { int damage = 0; if (canAttack()) { System.out.print("Attacking! "); if (Math.random()<=getCriticalHitPercent()) { damage = getDamage()*2; System.out.print("Critical Hit! "); } else { damage = getDamage(); } } else { System.out.print("Can't Attack Yet! "); } return damage; } //Determines if the weapon is ready to attack again based on attackSpeed private boolean canAttack() { Date date = new Date(); long currentTime = date.getTime(); //Produces the number of seconds since the last attack. double timeBetweenAttacks = (currentTime - lastAttack)/1000; //An attack speed of 100 represents 1 attack per second. This formula below //is used to calculate the how many seconds must go by before another attack. double rechargeTime = 1000/(getAttackSpeed()*10); //An attack is possible if there is sufficient time between attacks. if (timeBetweenAttacks >= rechargeTime) { lastAttack = currentTime; //If an attack is possible, the lastAttack is reset. return true; } return false; } }
ebdead35ba1cf2adde6848a818313865e70f17d9
[ "Java" ]
1
Java
justinnature1/JavaFactoryPattern
3a8dc0c5ae2f462faa882ef15767f07899980303
81ecb401af217a8d25325047fa3d9a941ce20f6e
refs/heads/master
<file_sep>// client-side js // run by the browser each time your view template is loaded // by default, you've got jQuery, // add other scripts at the bottom of index.html $(function() { console.log('hello world :o'); }); $('.submit').on('click', function() { // $.post('/get-file-size', { field1: "hello", field2 : "hello2"}, // function(returnedData){ // console.log(returnedData); // }); var size = $("#FileInput")[0].files[0].size; console.log(size) $.ajax({ type: "POST", url: '/get-file-size', data: {'file_size': Math.ceil(size/1000)} }).done(function(data) { console.log(data) $(".dreams").html('<h1>File size is ' + data.file_size + 'kb') }); })
1e8aab08725465b1591ee19285958507fb389b4b
[ "JavaScript" ]
1
JavaScript
srichakradhar/file-sizak
79add77eab62d769a89305a9f3c4c6c62e7392b3
9cdc2c1d489417935e87f3cea7d4cd2c1f067fe6
refs/heads/master
<repo_name>Farcek/notc<file_sep>/notc.js var glob = require("glob"); var path = require('path'); var etc = require('etc'); function notc(dir, options) { var etcer = etc(); // find parentDir if (options && options.parentConf) { var findParentDir = require('find-parent-dir'); var pdir = findParentDir.sync(dir, options.parentConf); if (pdir) { etcer.folder(path.join(pdir, options.parentConf)); } } return etcer.toJSON(); } module.exports = notc;<file_sep>/notc.d.ts declare module "notc" { function notc<T>(dir: string, options?: { parentConf: string }): T; namespace notc { } export = notc; }<file_sep>/index.js module.exports = require('./notc');
f4951f23e078fa235534336c9e1dc41c6470ad75
[ "JavaScript", "TypeScript" ]
3
JavaScript
Farcek/notc
e9951a267252ddf9efcd7a2a6c0c9c078444dc92
8af2c3b0379695adbea140f95686704f9730c0f1
refs/heads/master
<repo_name>mirloupa/GenScripts<file_sep>/README.md # General scripts A collection of useful scripts. <file_sep>/SH/multi_rename.sh Rename multiple files from ```*.fasta``` to ```*.cat.fasta```. ``` for file in /data2/scratch2/mirabl/Xf_proj/MLST_201902/MLST_seq/*.fasta; do file_short=$(basename $file | sed s/".fasta"//g) echo $file_short cp /data2/scratch2/mirabl/Xf_proj/MLST_201902/MLST_seq/"$file_short".fasta /data2/scratch2/mirabl/Xf_proj/MLST_201902/MLST_seq/"$file_short".cat.fasta done ```` <file_sep>/SH/extract_effectors.sh # Find effectors in PREFFECTOR output and save in new file with .res extension. for file in /data2/scratch2/mirabl/Xf_proj/Sequences/WGS/DNA_fasta/*.fasta; do file_short=$(basename $file | sed s/".fasta"//g) echo $file_short grep -i ',effector,' /data2/scratch2/mirabl/Xf_proj/Xf_effector_prediction/20190501_preffector-res_ncbi-Xf55/"$file_short".txt > /data2/scratch2/mirabl/Xf_proj/Xf_effector_prediction/20190501_preffector-res_ncbi-Xf55/Effectors/"$file_short".res done <file_sep>/awk_scripts.md # A collection of ```awk``` scripts. Extract FASTA sequence from a list of IDs. ```bash awk -F'>' 'NR==FNR{ids[$0]; next} NF>1{f=($2 in ids)} f' /data2/scratch2/mirabl/Xf_proj/Xf_effector_prediction/20190501_preffector-res_ncbi-Xf55/Effectors/LSMJ01000001.1.res-ID /data2/scratch2/mirabl/Xf_proj/Sequences/WGS/Prot_fasta/GCF_000576405.1_Wufong-1_protein.faa > LSMJ01000001.1.res-ID.faa ``` --- Extract FASTA sequence from a list of IDs for multiple files. ```bash for file in /data2/scratch2/mirabl/Xf_proj/Xf_effector_prediction/20190501_preffector-res_ncbi-Xf55/Effectors/*.res-ID; do awk -F'>' 'NR==FNR{ids[$0]; next} NF>1{f=($2 in ids)} f' $file /data2/scratch2/mirabl/Xf_proj/Sequences/WGS/Prot_fasta/* > "$file".faa done ``` --- <file_sep>/SH/rename_from_list.sh Rename file in a directory to name according to list. ``` for file in ./*; do file_short=$(basename $file | sed s/".txt"//g) grep "$file_short" xf_strains.csv | file_short=$(cut -d, -f3) cp $file $file_short done ``` <file_sep>/sge_scripts.md # A collection of scripts from SGE-HPC. Submit job only after certain conditions are met (BLAST all vs all example). ```bash for file in /data2/scratch2/mirabl/Xf_proj/Xf_effector_prediction/20190125_preffector-res_ncbi-Xf46/Effectors/SEQ/*ID.faa; do file_short=$(basename $file | sed s/".res-ID.faa"//g) Jobs=$(qstat | grep 'blast-allvall' | wc -l) while [ $Jobs -gt 100 ]; do sleep 10 printf "." Jobs=$(qstat | grep 'allvall' | wc -l) done qsub /home/mirabl/SUB_PBS/Xf_proj/blast-allvall.pbs $file "$file"_allvall.crunch done ``` ```bash for file in /data2/scratch2/mirabl/Xf_proj/Xf_effector_prediction/Preffector_results_Xf55/Effectors/All_effector_seq/*faa; do file_short=$(basename $file | sed s/".faa"//g) Jobs=$(qstat | grep 'blast-allvall' | wc -l) while [ $Jobs -gt 100 ]; do sleep 10 printf "." Jobs=$(qstat | grep 'allvall' | wc -l) done qsub /home/mirabl/SUB_PBS/Xf_proj/blast-allvall.pbs $file "$file"_allvall.crunch done ``` --- <file_sep>/SH/blast_scripts.sh # BLAST all vs all. for fasta in /data2/scratch2/mirabl/Xf_proj/Xf_effector_prediction/20190125_preffector-res_ncbi-Xf46/Effectors/SEQ/*ID.faa; do blastall -i $fasta -d $1 -o "$fasta"_allvall.crunch -m 8 done <file_sep>/SH/fasta_subdir.sh # Create a subdirectory for each FASTA file and move FASTA file to said directory. for file in /data2/scratch2/mirabl/Xf_proj/Sequences/WGS/DNA_fasta/*.fasta; do file_short=$(basename $file | sed s/".fasta"//g) echo $file_short cp /data2/scratch2/mirabl/Xf_proj/NCBI_Xf55/Analysis_w_outgr/Annotation/"$file_short"/*.faa /data2/scratch2/mirabl/Xf_proj/NCBI_Xf55/Analysis_w_outgr/Annotation/"$file_short"/"$file_short".faa done <file_sep>/sed_scripts.md # A collection of ```sed``` scripts with description/examples. Remove all characters from beginning of line until '>' Output is echo-ed ``` sed -n 's/^.*>//p' AAAL02000032.1.res ``` --- Remove all characters from beginning of line until '>' Output is saved in new files with '-ID' extension ``` for file in /data2/scratch2/mirabl/Xf_proj/Xf_effector_prediction/20190501_preffector-res_ncbi-Xf55/Effectors/*.res; do sed -n 's/^.*>//p' $file > "$file"-ID done ``` --- Extract accession number from PREFFECTOR results and save to new file. ``` for file in ./*.res-ID; do file_short=$(basename $file | sed s/".res-ID"//g) echo $file_short sed 's/ .*//' $file > $file_short.txt done ``` ---
266ac71134fd962e8332b065ae6b68f9c08906ff
[ "Markdown", "Shell" ]
9
Markdown
mirloupa/GenScripts
4bacbb9a1c715405f51b6b361a156a2fc8ba68db
5f0ac4855cb3cf2caad38207e480e66827acc5b6
refs/heads/master
<repo_name>ArtificialTruth/Factions<file_sep>/src/com/massivecraft/factions/util/HealthBarUtil.java package com.massivecraft.factions.util; import java.util.Map.Entry; import com.massivecraft.factions.ConfServer; import com.massivecraft.mcore.util.Txt; public class HealthBarUtil { public static String getHealthbar(double healthQuota, int barLength) { // Ensure between 0 and 1; healthQuota = fixQuota(healthQuota); // What color is the health bar? String color = getColorFromHealthQuota(healthQuota); // how much solid should there be? int solidCount = (int) Math.ceil(barLength * healthQuota); // The rest is empty int emptyCount = (int) ((barLength - solidCount) / ConfServer.spoutHealthBarSolidsPerEmpty); // Create the non-parsed bar String ret = ConfServer.spoutHealthBarLeft + Txt.repeat(ConfServer.spoutHealthBarSolid, solidCount) + ConfServer.spoutHealthBarBetween + Txt.repeat(ConfServer.spoutHealthBarEmpty, emptyCount) + ConfServer.spoutHealthBarRight; // Replace color tag ret = ret.replace("{c}", color); // Parse amp color codes ret = Txt.parse(ret); return ret; } public static String getHealthbar(double healthQuota) { return getHealthbar(healthQuota, ConfServer.spoutHealthBarWidth); } public static double fixQuota(double healthQuota) { if (healthQuota > 1) { return 1d; } else if (healthQuota < 0) { return 0d; } return healthQuota; } public static String getColorFromHealthQuota(double healthQuota) { Double currentRoof = null; String ret = null; for (Entry<Double, String> entry : ConfServer.spoutHealthBarColorUnderQuota.entrySet()) { double roof = entry.getKey(); String color = entry.getValue(); if (healthQuota <= roof && (currentRoof == null || roof <= currentRoof)) { currentRoof = roof; ret = color; } } return ret; } }<file_sep>/src/com/massivecraft/factions/event/FactionsEventPowerChange.java package com.massivecraft.factions.event; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList; import com.massivecraft.factions.entity.FPlayer; public class FactionsEventPowerChange extends FactionsEventAbstractSender { // -------------------------------------------- // // REQUIRED EVENT CODE // -------------------------------------------- // private static final HandlerList handlers = new HandlerList(); @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } // -------------------------------------------- // // FIELDS // -------------------------------------------- // private final FPlayer fplayer; public FPlayer getFPlayer() { return this.fplayer; } private final PowerChangeReason reason; public PowerChangeReason getReason() { return this.reason; } private double newPower; public double getNewPower() { return this.newPower; } public void setNewPower(double newPower) { this.newPower = newPower; } // -------------------------------------------- // // CONSTRUCT // -------------------------------------------- // public FactionsEventPowerChange(CommandSender sender, FPlayer fplayer, PowerChangeReason reason, double newPower) { super(sender); this.fplayer = fplayer; this.reason = reason; this.newPower = newPower; } // -------------------------------------------- // // REASON ENUM // -------------------------------------------- // public enum PowerChangeReason { TIME, DEATH, UNDEFINED, ; } } <file_sep>/src/com/massivecraft/factions/task/AutoLeaveTask.java package com.massivecraft.factions.task; import com.massivecraft.factions.ConfServer; import com.massivecraft.factions.entity.FPlayerColl; import com.massivecraft.factions.entity.FPlayerColls; import com.massivecraft.mcore.ModuloRepeatTask; import com.massivecraft.mcore.util.TimeUnit; public class AutoLeaveTask extends ModuloRepeatTask { // -------------------------------------------- // // INSTANCE & CONSTRUCT // -------------------------------------------- // private static AutoLeaveTask i = new AutoLeaveTask(); public static AutoLeaveTask get() { return i; } // -------------------------------------------- // // OVERRIDE: MODULO REPEAT TASK // -------------------------------------------- // @Override public long getDelayMillis() { return (long) (ConfServer.autoLeaveRoutineRunsEveryXMinutes * TimeUnit.MILLIS_PER_MINUTE); } @Override public void setDelayMillis(long delayMillis) { throw new RuntimeException("operation not supported"); } @Override public void invoke() { for (FPlayerColl coll : FPlayerColls.get().getColls()) { coll.autoLeaveOnInactivityRoutine(); } } } <file_sep>/src/com/massivecraft/factions/cmd/arg/ARFPlayer.java package com.massivecraft.factions.cmd.arg; import com.massivecraft.factions.entity.FPlayer; import com.massivecraft.factions.entity.FPlayerColls; import com.massivecraft.mcore.cmd.arg.ARSenderEntity; import com.massivecraft.mcore.cmd.arg.ArgReader; public class ARFPlayer { // -------------------------------------------- // // INSTANCE // -------------------------------------------- // public static ArgReader<FPlayer> getFullAny(Object o) { return ARSenderEntity.getFullAny(FPlayerColls.get().get(o)); } public static ArgReader<FPlayer> getStartAny(Object o) { return ARSenderEntity.getStartAny(FPlayerColls.get().get(o)); } public static ArgReader<FPlayer> getFullOnline(Object o) { return ARSenderEntity.getFullOnline(FPlayerColls.get().get(o)); } public static ArgReader<FPlayer> getStartOnline(Object o) { return ARSenderEntity.getStartOnline(FPlayerColls.get().get(o)); } } <file_sep>/src/com/massivecraft/factions/cmd/CmdFactionsPower.java package com.massivecraft.factions.cmd; import com.massivecraft.factions.Perm; import com.massivecraft.factions.cmd.arg.ARFPlayer; import com.massivecraft.factions.entity.FPlayer; import com.massivecraft.mcore.cmd.req.ReqHasPerm; public class CmdFactionsPower extends FCommand { public CmdFactionsPower() { this.addAliases("power", "pow"); this.addOptionalArg("player", "you"); this.addRequirements(ReqHasPerm.get(Perm.POWER.node)); } @Override public void perform() { FPlayer target = this.arg(0, ARFPlayer.getStartAny(fme), fme); if (target == null) return; if (target != fme && ! Perm.POWER_ANY.has(sender, true)) return; double powerBoost = target.getPowerBoost(); String boost = (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? " (bonus: " : " (penalty: ") + powerBoost + ")"; msg("%s<a> - Power / Maxpower: <i>%d / %d %s", target.describeTo(fme, true), target.getPowerRounded(), target.getPowerMaxRounded(), boost); } } <file_sep>/src/com/massivecraft/factions/cmd/CmdFactionsKick.java package com.massivecraft.factions.cmd; import com.massivecraft.factions.ConfServer; import com.massivecraft.factions.FPerm; import com.massivecraft.factions.Factions; import com.massivecraft.factions.Perm; import com.massivecraft.factions.Rel; import com.massivecraft.factions.cmd.arg.ARFPlayer; import com.massivecraft.factions.entity.FPlayer; import com.massivecraft.factions.entity.Faction; import com.massivecraft.factions.entity.FactionColls; import com.massivecraft.factions.entity.MConf; import com.massivecraft.factions.event.FactionsEventMembershipChange; import com.massivecraft.factions.event.FactionsEventMembershipChange.MembershipChangeReason; import com.massivecraft.mcore.cmd.req.ReqHasPerm; public class CmdFactionsKick extends FCommand { public CmdFactionsKick() { this.addAliases("kick"); this.addRequiredArg("player"); this.addRequirements(ReqHasPerm.get(Perm.KICK.node)); } @Override public void perform() { // Arg FPlayer fplayer = this.arg(1, ARFPlayer.getStartAny(sender)); if (fplayer == null) return; // Validate if (fme == fplayer) { msg("<b>You cannot kick yourself."); msg("<i>You might want to: %s", Factions.get().getOuterCmdFactions().cmdFactionsLeave.getUseageTemplate(false)); return; } if (fplayer.getRole() == Rel.LEADER && !(this.senderIsConsole || fme.isUsingAdminMode())) { msg("<b>The leader can not be kicked."); return; } if ( ! ConfServer.canLeaveWithNegativePower && fplayer.getPower() < 0) { msg("<b>You cannot kick that member until their power is positive."); return; } // FPerm Faction fplayerFaction = fplayer.getFaction(); if (!FPerm.KICK.has(sender, fplayerFaction)) return; // Event FactionsEventMembershipChange event = new FactionsEventMembershipChange(sender, fplayer, FactionColls.get().get(fplayer).getNone(), MembershipChangeReason.KICK); event.run(); if (event.isCancelled()) return; // Inform fplayerFaction.msg("%s<i> kicked %s<i> from the faction! :O", fme.describeTo(fplayerFaction, true), fplayer.describeTo(fplayerFaction, true)); fplayer.msg("%s<i> kicked you from %s<i>! :O", fme.describeTo(fplayer, true), fplayerFaction.describeTo(fplayer)); if (fplayerFaction != myFaction) { fme.msg("<i>You kicked %s<i> from the faction %s<i>!", fplayer.describeTo(fme), fplayerFaction.describeTo(fme)); } if (MConf.get().logFactionKick) { Factions.get().log(fme.getDisplayName() + " kicked " + fplayer.getName() + " from the faction " + fplayerFaction.getTag()); } // Apply if (fplayer.getRole() == Rel.LEADER) { fplayerFaction.promoteNewLeader(); } fplayerFaction.setInvited(fplayer, false); fplayer.resetFactionData(); } } <file_sep>/src/com/massivecraft/factions/chat/tag/ChatTagTitle.java package com.massivecraft.factions.chat.tag; import com.massivecraft.factions.chat.ChatTagAbstract; import com.massivecraft.factions.entity.FPlayer; public class ChatTagTitle extends ChatTagAbstract { // -------------------------------------------- // // INSTANCE & CONSTRUCT // -------------------------------------------- // private ChatTagTitle() { super("factions_title"); } private static ChatTagTitle i = new ChatTagTitle(); public static ChatTagTitle get() { return i; } // -------------------------------------------- // // OVERRIDE // -------------------------------------------- // @Override public String getReplacement(FPlayer fsender, FPlayer frecipient) { return fsender.getTitle(); } } <file_sep>/src/com/massivecraft/factions/cmd/CmdFactionsCapeAbstract.java package com.massivecraft.factions.cmd; import java.util.List; import org.bukkit.command.CommandSender; import com.massivecraft.factions.FPerm; import com.massivecraft.factions.cmd.arg.ARFaction; import com.massivecraft.factions.entity.Faction; public abstract class CmdFactionsCapeAbstract extends FCommand { public Faction capeFaction; public String currentCape; public CmdFactionsCapeAbstract() { this.addOptionalArg("faction", "you"); } @Override public boolean validCall(CommandSender sender, List<String> args) { this.capeFaction = null; this.currentCape = null; if (this.myFaction == null && ! this.argIsSet(this.requiredArgs.size())) { msg("<b>You must specify a faction from console."); return false; } this.capeFaction = this.arg(this.requiredArgs.size(), ARFaction.get(myFaction), myFaction); if (this.capeFaction == null) return false; // Do we have permission to manage the cape of that faction? if (fme != null && ! FPerm.CAPE.has(fme, capeFaction)) return false; this.currentCape = this.capeFaction.getCape(); return true; } } <file_sep>/src/com/massivecraft/factions/cmd/CmdFactionsInvite.java package com.massivecraft.factions.cmd; import com.massivecraft.factions.FPerm; import com.massivecraft.factions.Factions; import com.massivecraft.factions.Perm; import com.massivecraft.factions.cmd.arg.ARFPlayer; import com.massivecraft.factions.entity.FPlayer; import com.massivecraft.factions.event.FactionsEventInvitedChange; import com.massivecraft.mcore.cmd.arg.ARBoolean; import com.massivecraft.mcore.cmd.req.ReqHasPerm; import com.massivecraft.mcore.cmd.req.ReqIsPlayer; public class CmdFactionsInvite extends FCommand { public CmdFactionsInvite() { this.addAliases("inv", "invite"); this.addRequiredArg("player"); this.addOptionalArg("yes/no", "toggle"); this.addRequirements(ReqHasPerm.get(Perm.INVITE.node)); this.addRequirements(ReqIsPlayer.get()); } @Override public void perform() { // Args FPlayer fplayer = this.arg(0, ARFPlayer.getStartAny(sender)); if (fplayer == null) return; Boolean newInvited = this.arg(1, ARBoolean.get(), !myFaction.isInvited(fplayer)); if (newInvited == null) return; // Allready member? if (fplayer.getFaction() == myFaction) { msg("%s<i> is already a member of %s", fplayer.getName(), myFaction.getTag()); msg("<i>You might want to: " + Factions.get().getOuterCmdFactions().cmdFactionsKick.getUseageTemplate(false)); return; } // FPerm if ( ! FPerm.INVITE.has(sender, myFaction, true)) return; // Event FactionsEventInvitedChange event = new FactionsEventInvitedChange(sender, fplayer, myFaction, newInvited); event.run(); if (event.isCancelled()) return; newInvited = event.isNewInvited(); // Apply myFaction.setInvited(fplayer, newInvited); // Inform if (newInvited) { fplayer.msg("%s<i> invited you to %s", fme.describeTo(fplayer, true), myFaction.describeTo(fplayer)); myFaction.msg("%s<i> invited %s<i> to your faction.", fme.describeTo(myFaction, true), fplayer.describeTo(myFaction)); } else { fplayer.msg("%s<i> revoked your invitation to <h>%s<i>.", fme.describeTo(fplayer), myFaction.describeTo(fplayer)); myFaction.msg("%s<i> revoked %s's<i> invitation.", fme.describeTo(myFaction), fplayer.describeTo(myFaction)); } } } <file_sep>/src/com/massivecraft/factions/event/FactionsEventAbstractSender.java package com.massivecraft.factions.event; import org.bukkit.command.CommandSender; import com.massivecraft.factions.entity.FPlayer; import com.massivecraft.mcore.event.MCoreEvent; public abstract class FactionsEventAbstractSender extends MCoreEvent { // -------------------------------------------- // // FIELDS // -------------------------------------------- // private final CommandSender sender; public CommandSender getSender() { return this.sender; } public FPlayer getFSender() { return FPlayer.get(this.sender); } // -------------------------------------------- // // CONSTRUCT // -------------------------------------------- // public FactionsEventAbstractSender(CommandSender sender) { this.sender = sender; } } <file_sep>/src/com/massivecraft/factions/chat/tag/ChatTagRoleprefix.java package com.massivecraft.factions.chat.tag; import com.massivecraft.factions.chat.ChatTagAbstract; import com.massivecraft.factions.entity.FPlayer; public class ChatTagRoleprefix extends ChatTagAbstract { // -------------------------------------------- // // INSTANCE & CONSTRUCT // -------------------------------------------- // private ChatTagRoleprefix() { super("factions_roleprefix"); } private static ChatTagRoleprefix i = new ChatTagRoleprefix(); public static ChatTagRoleprefix get() { return i; } // -------------------------------------------- // // OVERRIDE // -------------------------------------------- // @Override public String getReplacement(FPlayer fsender, FPlayer frecipient) { return fsender.getRole().getPrefix(); } }
c1efc6a56400596faf31dc1156b82be653bb961c
[ "Java" ]
11
Java
ArtificialTruth/Factions
61e87304953eba02cbae419eaeb7fa306b84bcc5
731b86a5d58b0ff1bfb26b1f028af3e33df32b0b
refs/heads/master
<file_sep>dreamProject ============ -My !st project repo in which i will succeed for sure <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ $(document).ready(function(){ var arrData = ["a","b","c","d","e","f","g","h","i","j"]; renderEditableGrid(10,arrData); $("#submit").click(function() { getContentFromGrid(); }); function getContentFromGrid() { var list = []; var j = 0; for(j = 0 ; j < 10 ; j ++ ) { var id = $("#"+arrData[j]).text().trim(); var val = $("#tr"+j).text().trim(); var data = { Id:id, Val:val }; list.push(data); //alert( list[j].Id + " = "+ list[j].Val ); } var jsonData = JSON.stringify(list); var obj = jQuery.parseJSON( jsonData ); putJsonDataServletUsingAjax(jsonData); } function putJsonDataServletUsingAjax(jsonData) { $.ajax({ cache: false, type: "POST", url: "TestServlet", data: {theNameOfTheParameter: jsonData}, dataType: "json", success: function (data) { // There is no problem with the validation alert("success\n"+data.test); }, error: function (xhr) { alert(xhr.responseText); alert("Critical Error!. Failed to call the server."); } }); } function renderEditableGrid(size,arrData) { var str = "<table border =1 style=\"border-spacing: 0px; border-collapse:collapse; \"><tbody>"; var i = 0; for( i = 0; i < size ; i ++ ) { str += "<tr><td align=\"center\" id="+ arrData[i] +" width=\"40em\">"+arrData[i]+"</td><td id = \"tr"+i+"\""+" width=\"40em\" contenteditable>"+i+"</td></tr>"; } str += "</tbody></table>"; str += "<input id = \"submit\" type=\"button\" value=\"click\"> </input>"; $("#tableContent").html(str); } }); <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ jQuery(function($){ // simple jQuery validation script $('#login').submit(function(event){ var valid = true; var errormsg = 'This field is required!'; var errorcn = 'error'; $('.' + errorcn, this).remove(); $('.required', this).each(function(){ var parent = $(this).parent(); if( $(this).val() == '' ){ var msg = $(this).attr('title'); msg = (msg != '') ? msg : errormsg; $('<span class="'+ errorcn +'">'+ msg +'</span>') .appendTo(parent).fadeIn('fast').click(function() { $(this).remove(); }) valid = false; }; }); if ( valid != false ) { /* stop form from submitting normally */ event.preventDefault(); var data = { UserName: $('#login_username').val(), Password: <PASSWORD>').val() }; var jsonData = JSON.stringify(data); $.post( "TestServlet", { theNameOfTheParameter: jsonData }, function( data ) { if ( data.IsAuthenticated == "yes" ) { alert(data.InputParam); window.location = "index.jsp"; } else { $('#loginFailed').html('The username or password you entered is incorrect') .fadeIn('fast').click(function(){ $(this).remove(); }) } }); /* $.ajax({ cache: false, type: "POST", url: "TestServlet", data: {theNameOfTheParameter: jsonData}, dataType: "json", success: function (data) { // There is no problem with the validation alert("success\n"+data.test); valid = false; }, error: function (xhr) { valid = false; alert(xhr.responseText); alert("Critical Error!. Failed to call the server."); } }); */ } //.fadeIn('fast').click(function(){ $(this).remove(); }) //valid = false; //return valid; }); }) $(function() { // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore! $( "#dialog:ui-dialog" ).dialog( "destroy" ); var name = $( "#name" ), email = $( "#email" ), password = $( <PASSWORD>" ), allFields = $( [] ).add( name ).add( email ).add( password ), tips = $( ".validateTips" ); function updateTips( t ) { tips .text( t ) .addClass( "ui-state-highlight" ); setTimeout(function() { tips.removeClass( "ui-state-highlight", 1500 ); }, 500 ); } function checkLength( o, n, min, max ) { if ( o.val().length > max || o.val().length < min ) { o.addClass( "ui-state-error" ); updateTips( "Length of " + n + " must be between " + min + " and " + max + "." ); return false; } else { return true; } } function checkRegexp( o, regexp, n ) { if ( !( regexp.test( o.val() ) ) ) { o.addClass( "ui-state-error" ); updateTips( n ); return false; } else { return true; } } $( "#dialog-form" ).dialog({ autoOpen: false, height: 400, width: 350, modal: true, buttons: { "Create an account": function() { var bValid = true; allFields.removeClass( "ui-state-error" ); bValid = bValid && checkLength( name, "username", 3, 16 ); bValid = bValid && checkLength( email, "email", 6, 80 ); bValid = bValid && checkLength( password, "<PASSWORD>", 5, 16 ); bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." ); // From jquery.validate.js (by joern), contributed by <NAME>: http://projects.scottsplayground.com/email_address_validation/ bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. <EMAIL>" ); bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" ); if ( bValid ) { $( "#users tbody" ).append( "<tr>" + "<td>" + name.val() + "</td>" + "<td>" + email.val() + "</td>" + "<td>" + password.val() + "</td>" + "</tr>" ); $( this ).dialog( "close" ); } }, Cancel: function() { $( this ).dialog( "close" ); } }, close: function() { allFields.val( "" ).removeClass( "ui-state-error" ); } }); $( "#create-user" ) .button() .click(function() { $( "#dialog-form" ).dialog( "open" ); }); }); $(function() { // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore! $( "#dialog:ui-dialog" ).dialog( "destroy" ); var name = $( "#name" ), email = $( "#email" ), password = $( <PASSWORD>" ), allFields = $( [] ).add( name ).add( email ).add( password ), tips = $( ".validateTips" ); function updateTips( t ) { tips .text( t ) .addClass( "ui-state-highlight" ); setTimeout(function() { tips.removeClass( "ui-state-highlight", 1500 ); }, 500 ); } function checkLength( o, n, min, max ) { if ( o.val().length > max || o.val().length < min ) { o.addClass( "ui-state-error" ); updateTips( "Length of " + n + " must be between " + min + " and " + max + "." ); return false; } else { return true; } } function checkRegexp( o, regexp, n ) { if ( !( regexp.test( o.val() ) ) ) { o.addClass( "ui-state-error" ); updateTips( n ); return false; } else { return true; } } $( "#dialog-form1" ).dialog({ autoOpen: false, height: 300, width: 350, modal: true, buttons: { "Forgot Password": function() { var bValid = true; allFields.removeClass( "ui-state-error" ); bValid = bValid && checkLength( email, "email", 6, 80 ); bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." ); // From jquery.validate.js (by joern), contributed by <NAME>: http://projects.scottsplayground.com/email_address_validation/ bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. <EMAIL>" ); bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" ); if ( bValid ) { $( "#users tbody" ).append( "<tr>" + "<td>" + name.val() + "</td>" + "<td>" + email.val() + "</td>" + "<td>" + password.val() + "</td>" + "</tr>" ); $( this ).dialog( "close" ); } }, Cancel: function() { $( this ).dialog( "close" ); } }, close: function() { allFields.val( "" ).removeClass( "ui-state-error" ); } }); $( "#forgotpass" ) .button() .click(function() { $( "#dialog-form1" ).dialog( "open" ); }); }); <file_sep>deploy.ant.properties.file=/home/navin/.netbeans/7.1.1/tomcat60.properties j2ee.server.home=/home/navin/apache-tomcat-6.0.35 j2ee.server.instance=tomcat60:home=/home/navin/apache-tomcat-6.0.35 user.properties.file=/home/navin/.netbeans/7.1.1/build.properties
5b83c2d333eca114582b12f488f45f4dfe14d19d
[ "Markdown", "JavaScript", "INI" ]
4
Markdown
gvnavin/dreamProject
1a6048147ae5d5f7256bae8fc6f0761c88c9d097
59998184bf824b97e70e2e3375baff8eb22b0387
refs/heads/master
<file_sep># traveltime Topograpical style map for travel time <file_sep>import requests import json GRIDSIZE = 8 baseURL = 'https://maps.googleapis.com/maps/api/distancematrix/json?' lat = 42.4030636 lon = -71.1256341 home = str(lat)+','+str(lon) dests = [] for x in xrange(GRIDSIZE**2): dests.append(str(lat+0.001*(x//GRIDSIZE))+','+str(lon+0.001*(x%GRIDSIZE))) destinations = '|'.join(dests) call = 'origins='+home+'&destinations='+destinations r = requests.get(baseURL+call) resp = json.loads(r.text) mapjs = '''\ <!DOCTYPE html> <html> <head> <style type="text/css"> html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; } </style> </head> <body> <div id="map"></div> <script type="text/javascript"> "use strict"; var map; function initMap() { var heatMapData = [ ''' mapitem = ' {{location: new google.maps.LatLng({latlon}), weight: {weight}}}' mapjsBot = ''' ]; var pindrop = new google.maps.LatLng({lat}, {lon}); map = new google.maps.Map(document.getElementById('map'), {{ center: pindrop, zoom: 15, mapTypeId: google.maps.MapTypeId.SATELLITE }}); var heatmap = new google.maps.visualization.HeatmapLayer({{ data: heatMapData, dissipating: true, radius: 40 }}); heatmap.setMap(map); }} </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=<KEY>&libraries=visualization&callback=initMap"> </script> </body> </html> '''.format(lat=lat, lon=lon) mapjs += ',\n'.join([mapitem.format(latlon=dests[index], weight=resp["rows"][0]["elements"][index]["duration"]["value"]) for index in xrange(len(resp["rows"][0]["elements"]))]) # for index in xrange(len(resp["rows"][0]["elements"])): # mapjs += mapitem.format(latlon=dests[index], weight=resp["rows"][0]["elements"][index]["duration"]["value"]) mapjs += mapjsBot #print(mapjs) with open('bruh.html', 'w') as f: f.write(mapjs)
bfbe323877324b991939c68cbdac31b8d0c1bbae
[ "Markdown", "Python" ]
2
Markdown
jprMesh/traveltime
c05a87cc35473ff5ba2fc70899a167071e23646f
543ff84624c8cf9e3f416e22fd23784e18a7acc4
refs/heads/master
<repo_name>Fourr/Project2<file_sep>/backend/flaskr/__init__.py import os from flask import Flask, request, abort, jsonify from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS, cross_origin import random from models import setup_db, Question, Category QUESTIONS_PER_PAGE = 10 def paginate(request, selection): page = request.args.get('page', 1 ,type=int) start = (page - 1) * QUESTIONS_PER_PAGE end = start + QUESTIONS_PER_PAGE questions = [question.format() for question in selection] current_questions = questions[start:end] return current_questions #psql -U postgres -d trivia -1 -f trivia.sql def create_app(test_config=None): # create and configure the app app = Flask(__name__) setup_db(app) CORS(app) ''' @TODO: Use the after_request decorator to set Access-Control-Allow ''' # CORS Headers @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') return response ''' @TODO: Create an endpoint to handle GET requests for all available categories. ''' #curl http://localhost:5000/categories @app.route('/categories', methods=['GET']) def getCategories(): selection = Category.query.order_by(Category.id).all() categories = {} for i in range(len(selection)): categories[selection[i].id] = selection[i].type if len(selection) == 0: abort(404) return jsonify({ 'categories': categories }) ''' @TODO: Create an endpoint to handle GET requests for questions, including pagination (every 10 questions). This endpoint should return a list of questions, number of total questions, current category, categories. TEST: At this point, when you start the application you should see questions and categories generated, ten questions per page and pagination at the bottom of the screen for three pages. Clicking on the page numbers should update the questions. ''' #curl http://localhost:5000/questions?page=1 @app.route('/questions', methods=['GET']) def getQuestions(): print(request) selection_categories = Category.query.order_by(Category.id).all() categories = {} for i in range(len(selection_categories)): categories[selection_categories[i].id] = selection_categories[i].type selection_question = Question.query.order_by(Question.id).all() current_questions = paginate(request, selection_question) length = len(selection_question) if len(current_questions) == 0: abort(404) return jsonify({ 'questions': current_questions, 'totalQuestions': length, 'categories': categories, 'currentCategory': None }) ''' @TODO: Create an endpoint to DELETE question using a question ID. TEST: When you click the trash icon next to a question, the question will be removed. This removal will persist in the database and when you refresh the page. ''' #curl http://localhost:5000/questions/24 -X DELETE @app.route('/questions/<int:question_id>', methods=['DELETE']) def delete_question(question_id): try: question = Question.query.filter(Question.id == question_id).one_or_none() if question is None: abort(404) question.delete() return jsonify({ 'deleted': question.id, }) except: abort(422) ''' @TODO: Create an endpoint to POST a new question, which will require the question and answer text, category, and difficulty score. TEST: When you submit a question on the "Add" tab, the form will clear and the question will appear at the end of the last page of the questions list in the "List" tab. ''' #curl -X POST -H "Content-Type: application/json" -d '{"question": "How tall is <NAME>?", "answer": "6-9","category":"6","difficulty": "1"}' http://localhost:5000/questions @app.route('/questions', methods=['POST']) def create_question(): body = request.get_json() new_question = body.get('question') new_answer = body.get('answer') new_category = body.get('category') new_difficulty = body.get('difficulty') if not new_question or not new_answer or not new_category or not new_difficulty: abort(422) try: question= Question(question=new_question, answer=new_answer, category=new_category, difficulty=new_difficulty) question.insert() selection = Question.query.order_by(Question.id).all() current_questions = paginate(request, selection) return jsonify({ 'created': question.id, 'questions': current_questions, 'totalQuestions': len(Question.query.all()) }) except: abort(422) ''' @TODO: Create a POST endpoint to get questions based on a search term. It should return any questions for whom the search term is a substring of the question. TEST: Search by any phrase. The questions list will update to include only question that include that string within their question. Try using the word "title" to start. ''' #curl -X POST -H "Content-Type: application/json" -d '{"searchTerm": "LLebron"}' http://localhost:5000/questions/search @app.route('/questions/search', methods=['POST']) def retrieve_questions_based_on_search(): body = request.get_json() new_search = body.get('searchTerm', None) try: selection = Question.query.filter(Question.question.contains(new_search)).all() #current_questions = [question.format() for question in selection] current_questions = paginate(request, selection) if not current_questions: abort(422) return jsonify({ 'questions': current_questions, 'totalQuestions': len(current_questions), 'currentCategory': None }) except: abort(422) ''' @TODO: Create a GET endpoint to get questions based on category. TEST: In the "List" tab / main screen, clicking on one of the categories in the left column will cause only questions of that category to be shown. ''' #curl http://localhost:5000/category/2/questions @app.route('/categories/<int:category_id>/questions', methods=['GET']) def retrieve_questions_based_on_category(category_id): selection = Question.query.order_by(Question.id).filter_by(category=category_id).all() current_questions = paginate(request, selection) if len(current_questions) == 0: abort(404) return jsonify({ 'questions': current_questions, 'totalQuestions': len(current_questions) }) ''' @TODO: Create a POST endpoint to get questions to play the quiz. This endpoint should take category and previous question parameters and return a random questions within the given category, if provided, and that is not one of the previous questions. TEST: In the "Play" tab, after a user selects "All" or a category, one question at a time is displayed, the user is allowed to answer and shown whether they were correct or not. ''' #curl -X POST -H "Content-Type: application/json" -d '{"previous_questions": [21,22], "quiz_category": {"type": "Science", "id": 1}}' http://localhost:5000/quizzes @app.route('/quizzes', methods=['POST']) def play(): body = request.get_json() new_previous_questions = body.get('previous_questions', None) new_quiz_category = body.get('quiz_category', None) selection = '' wentThrough = False try: if not new_previous_questions and new_quiz_category['id']==0: selection = Question.query.all() wentThrough = True elif not new_previous_questions and new_quiz_category['id']: selection = Question.query.filter_by(category=new_quiz_category['id']).all() wentThrough = True elif new_previous_questions and new_quiz_category['id']==0: selection = Question.query.filter(~Question.id.in_(new_previous_questions)).all() wentThrough = True elif new_previous_questions and new_quiz_category['id']: selection = Question.query.filter(~Question.id.in_(new_previous_questions)).filter_by(category=new_quiz_category['id']).all() wentThrough = True else: abort(500) if not selection and wentThrough: final_question = '' elif selection and wentThrough: final_question = random.choice(selection).format() else: abort(500) return jsonify({ 'question': final_question, }) except: abort(422) ''' @TODO: Create error handlers for all expected errors including 404 and 422. ''' @app.errorhandler(404) def not_found(error): return jsonify({ 'error': 404, 'message': 'resource not found' }), 404 @app.errorhandler(422) def not_found(error): return jsonify({ 'error': 422, 'message': 'unprocessable' }), 422 @app.errorhandler(400) def not_found(error): return jsonify({ 'error': 400, 'message': 'bad request' }), 400 @app.errorhandler(500) def not_found(error): return jsonify({ 'error': 500, 'message': 'internal server error' }), 500 return app <file_sep>/backend/README.md # Full Stack Trivia API Backend ## Getting Started ### Installing Dependencies #### Python 3.7 Follow instructions to install the latest version of python for your platform in the [python docs](https://docs.python.org/3/using/unix.html#getting-and-installing-the-latest-version-of-python) #### Virtual Enviornment We recommend working within a virtual environment whenever using Python for projects. This keeps your dependencies for each project separate and organaized. Instructions for setting up a virual enviornment for your platform can be found in the [python docs](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/) #### PIP Dependencies Once you have your virtual environment setup and running, install dependencies by naviging to the `/backend` directory and running: ```bash pip install -r requirements.txt ``` This will install all of the required packages we selected within the `requirements.txt` file. ##### Key Dependencies - [Flask](http://flask.pocoo.org/) is a lightweight backend microservices framework. Flask is required to handle requests and responses. - [SQLAlchemy](https://www.sqlalchemy.org/) is the Python SQL toolkit and ORM we'll use handle the lightweight sqlite database. You'll primarily work in app.py and can reference models.py. - [Flask-CORS](https://flask-cors.readthedocs.io/en/latest/#) is the extension we'll use to handle cross origin requests from our frontend server. ## Database Setup With Postgres running, restore a database using the trivia.psql file provided. From the backend folder in terminal run: ```bash psql trivia < trivia.psql ``` ## Running the server From within the `backend` directory first ensure you are working using your created virtual environment. To run the server, execute: ```bash export FLASK_APP=flaskr export FLASK_ENV=development flask run ``` Setting the `FLASK_ENV` variable to `development` will detect file changes and restart the server automatically. Setting the `FLASK_APP` variable to `flaskr` directs flask to use the `flaskr` directory and the `__init__.py` file to find the application. ## Error Handling Errors are returned as JSON objects in the following format: ``` { "error": 404, 'message': 'resource not found' } ``` The API will return four types of errors when requests fail: - 404: resource not found - 422: unprocessable - 400: bad request - 500: internal server error ### Endpoints #### GET '/categories' - General: - Fetches a dictionary of categories in which the keys are the ids and the value is the corresponding string of the category - Request Arguments: None - Returns: An object with a single key, categories, that contains a object of id: category_string key:value pairs. - Sample `curl http://localhost:5000/categories` ``` { '1' : "Science", '2' : "Art", '3' : "Geography", '4' : "History", '5' : "Entertainment", '6' : "Sports" } ``` #### GET '/questions' - General: - Fetches a list of question objects, the total number of questions, categories, and the current category - Request Arguments: None - Results are paginated in groups of 10. Include a request argument to choose a page number, starting from 1 - Sample `curl http://localhost:5000/questions` ``` { "categories": { "1": "Science", "2": "Art", "3": "Geography", "4": "History", "5": "Entertainment", "6": "Sports" }, "currentCategory": null, "questions": [ { "answer": "<NAME>", "category": 5, "difficulty": 3, "id": 6, "question": "What was the title of the 1990 fantasy directed by <NAME> about a young man with multi-bladed appendages?" }, { "answer": "<NAME>", "category": 4, "difficulty": 1, "id": 9, "question": "What boxer's original name is <NAME>?" }, { "answer": "Brazil", "category": 6, "difficulty": 3, "id": 10, "question": "Which is the only team to play in every soccer World Cup tournament?" }, { "answer": "Uruguay", "category": 6, "difficulty": 4, "id": 11, "question": "Which country won the first ever soccer World Cup in 1930?" }, { "answer": "<NAME>", "category": 4, "difficulty": 2, "id": 12, "question": "Who invented Peanut Butter?" }, { "answer": "Lake Victoria", "category": 3, "difficulty": 2, "id": 13, "question": "What is the largest lake in Africa?" }, { "answer": "The Palace of Versailles", "category": 3, "difficulty": 3, "id": 14, "question": "In which royal palace would you find the Hall of Mirrors?" }, { "answer": "Agra", "category": 3, "difficulty": 2, "id": 15, "question": "The Taj Mahal is located in which Indian city?" }, { "answer": "Escher", "category": 2, "difficulty": 1, "id": 16, "question": "Which Dutch graphic artist\u2013initials M C was a creator of optical illusions?" }, { "answer": "<NAME>", "category": 2, "difficulty": 3, "id": 17, "question": "La Giaconda is better known as what?" } ], "totalQuestions": 30 } ``` #### DELETE /questions/{question_id} - General: - Deletes the question of the given ID if it exists. Returns the id of the deleted question. - Sample: `curl -X DELETE http://127.0.0.1:5000/question/16` ``` { "deleted": 24 } ``` #### POST /questions - General: - Creates a new question using the submitted question, answer, category and difficulty. Returns the id of the created question, question list based on current page number to update the frontend, and total questions. - Sample: `curl -X POST -H "Content-Type: application/json" -d '{"question": "How tall is <NAME>?", "answer": "6-9","category":"6","difficulty": "1"}' http://localhost:5000/questions?page=2` ``` { "created": 47, "questions": [ { "answer": "<NAME>", "category": 1, "difficulty": 3, "id": 21, "question": "Who discovered penicillin?" }, { "answer": "Blood", "category": 1, "difficulty": 4, "id": 22, "question": "Hematology is a branch of medicine involving the study of what?" }, { "answer": "Scarab", "category": 4, "difficulty": 4, "id": 23, "question": "Which dung beetle was worshipped by the ancient Egyptians?" }, { "answer": "6'9", "category": 6, "difficulty": 1, "id": 45, "question": "How Tall is Lebron?" }, { "answer": "6-9", "category": 6, "difficulty": 1, "id": 46, "question": "How tall is <NAME>?" }, { "answer": "6-9", "category": 6, "difficulty": 1, "id": 47, "question": "How tall is <NAME>?" } ], "totalQuestions": 16 } ``` #### POST /questions/search - General: Searches questions through key word (exact match) - Sample: `curl -X POST -H "Content-Type: application/json" -d '{"searchTerm": "title"}' http://localhost:5000/questions/search` ``` { "currentCategory": null, "questions": [ { "answer": "<NAME>", "category": 5, "difficulty": 3, "id": 6, "question": "What was the title of the 1990 fantasy directed by <NAME> about a young man with multi-bladed appendages?" } ], "totalQuestions": 1 } ``` #### GET /categories/{category_id}/questions - General: Returns a list of questions based off of the category ID - Sample `curl http://localhost:5000/categories/2/questions` ``` { "questions": [ { "answer": "Escher", "category": 2, "difficulty": 1, "id": 16, "question": "Which Dutch graphic artist\u2013initials M C was a creator of optical illusions?" }, { "answer": "<NAME>", "category": 2, "difficulty": 3, "id": 17, "question": "La Giaconda is better known as what?" }, { "answer": "<NAME>", "category": 2, "difficulty": 2, "id": 19, "question": "Which American artist was a pioneer of Abstract Expressionism, and a leading exponent of action painting?" } ], "totalQuestions": 3 } ``` #### POST /quizzes - General: - Provides a new question using the submitted previous questions and category. Returns a random question within the category and if the question is not in the previous questions array - Sample: `curl -X POST -H "Content-Type: application/json" -d '{"previous_questions": [21], "quiz_category": {"type": "Science", "id": 1}}' http://localhost:5000/quizzes` ``` { "question": { "answer": "Blood", "category": 1, "difficulty": 4, "id": 22, "question": "Hematology is a branch of medicine involving the study of what?" } } ``` ## Testing To run the tests, run ``` dropdb trivia_test createdb trivia_test psql trivia_test < trivia.psql python test_flaskr.py ```<file_sep>/backend/test_flaskr.py import os import unittest import json from flask_sqlalchemy import SQLAlchemy from flaskr import create_app from models import setup_db, Question, Category class TriviaTestCase(unittest.TestCase): """This class represents the trivia test case""" def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.database_name = "trivia_test" self.database_path = "postgres://postgres/password".format('localhost:5432', self.database_name) setup_db(self.app, self.database_path) self.new_question = { "question": "How tall is <NAME>?", "answer": "6-9", "category":"6", "difficulty": "1" } self.new_bad_question = { "questions": "How tall is <NAME>?", "answer": "6-9", "category":"6", "difficulty": "1" } self.new_search = { "searchTerm": "Lebron" } self.new_bad_search = { "searchTerm": "LLebron" } self.new_play = { "previous_questions": [], "quiz_category": { "type": "Science", "id": 1 } } self.new_bad_play = { "previous_questions": [], "quiz_category": { "type": "Science", "idd": 7 } } # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all() def tearDown(self): """Executed after reach test""" pass """ TODO Write at least one test for each test for successful operation and for expected errors. """ def test_catgeories(self): res = self.client().get('/categories') data = json.loads(res.data) self.assertEqual(res.status_code,200) self.assertTrue(data['categories']) def test_catgeories_failure(self): res = self.client().get('/categories/') data = json.loads(res.data) self.assertEqual(res.status_code,404) self.assertEqual(data['message'],'resource not found') def test_questions(self): res = self.client().get('/questions') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertTrue(data['questions']) self.assertTrue(data['totalQuestions']) self.assertTrue(data['categories']) #self.assertTrue(data['currentCategory']) def test_questions_failure(self): res = self.client().get('/questions?page=200') data = json.loads(res.data) self.assertEqual(res.status_code,404) self.assertEqual(data['message'],'resource not found') # def test_delete_question(self): # res = self.client().delete('/questions/5') # data = json.loads(res.data) # self.assertEqual(res.status_code, 200) # self.assertEqual(data['deleted'],5) def test_delete_question_failure(self): res = self.client().delete('/questions/100') data = json.loads(res.data) self.assertEqual(res.status_code,422) self.assertEqual(data['message'],'unprocessable') def test_create_question(self): res = self.client().post('/questions', json=self.new_question) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertTrue(data['created']) self.assertTrue(data['questions']) self.assertTrue(data['totalQuestions']) def test_create_question_failure(self): res = self.client().post('/questions', json=self.new_bad_question) data = json.loads(res.data) self.assertEqual(res.status_code, 422) self.assertEqual(data['message'],'unprocessable') def test_search_question(self): res = self.client().post('/questions/search', json=self.new_search) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertTrue(data['questions']) self.assertTrue(data['questions']) self.assertTrue(data['totalQuestions']) def test_search_question_failure(self): res = self.client().post('/questions/search', json=self.new_bad_search) data = json.loads(res.data) self.assertEqual(res.status_code, 422) self.assertEqual(data['message'],'unprocessable') def test_question_catgeories(self): res = self.client().get('/categories/2/questions') data = json.loads(res.data) self.assertEqual(res.status_code,200) self.assertTrue(data['questions']) self.assertTrue(data['totalQuestions']) def test_question_catgeories_failure(self): res = self.client().get('/categories/7/questions') data = json.loads(res.data) self.assertEqual(res.status_code,404) self.assertEqual(data['message'],'resource not found') def test_play(self): res = self.client().post('/quizzes', json=self.new_play) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertTrue(data['question']) def test_play_failure(self): res = self.client().post('/quizzes', json=self.new_bad_play) data = json.loads(res.data) self.assertEqual(res.status_code, 422) self.assertEqual(data['message'],'unprocessable') # Make the tests conveniently executable if __name__ == "__main__": unittest.main()
cac9d48e83c1067442e6febbacfd910a5054ca19
[ "Markdown", "Python" ]
3
Python
Fourr/Project2
8998fb817b21326e28f4c4e410a61ed74eb47fc6
ac7053bd5e01e8ae6e781ef697bdfca2f7ea3803
refs/heads/main
<repo_name>RichardRamos1120/guessing_game<file_sep>/index.php <?php session_start(); if(empty($_SESSION["guess"])){ $_SESSION["guess"] = rand(1,100); } function displayResult($rand,$guess){ $_SESSION["block"] = "block"; if($rand == $guess){ echo "<h2 class='forCorrect'>You Are Correct!</h2>"; echo "<form method='post' action='index.php'><input type='hidden' name='restart' value='yes'><input type='submit' value='Play Again'></form>"; } if($rand < $guess){ echo "<h2 class='forHigh'>Too High</h2>"; } if($rand > $guess){ echo "<h2 class='forLow'>Too Low!</h2>"; } } if(isset($_POST["restart"])){ session_destroy(); } include ("header.php"); ?> <section> <h1>Welcome to the great number game!</h1> <p>I'm thinking of a number between 1 and 100</p> <p>take a guess!</p> <div class="result"> <?php if(isset($_POST["guess"])){ displayResult($_SESSION["guess"],$_POST["guess"]); } ?> </div> <form action="index.php" method="post"> <label> <input type="text" name="guess" autofocus> </label> <input type="submit"> </form> </section> <?php include ("footer.php")?>
2af2d721faa4901eb2cb2a44113bf0caf9853f9f
[ "PHP" ]
1
PHP
RichardRamos1120/guessing_game
51abe3b4d28576a0ee0d9fa9145b4212e119e8f4
996139cff3b6092600758b5868b35121bb737a1b
refs/heads/master
<repo_name>hulken1/Curso-React-COD3R<file_sep>/todo-app/frontend/src/template/IconButton.js import React from 'react' import { Button } from 'react-bootstrap' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import If from './If' export default props => ( <If teste={!props.hide}> <Button variant={props.variant} onClick={props.onClick} > <FontAwesomeIcon icon={props.icon}></FontAwesomeIcon> </Button> </If> )<file_sep>/todo-app/frontend/src/template/Menu.js import React from 'react' import { Navbar, Nav, Container } from 'react-bootstrap' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faCalendarCheck } from "@fortawesome/free-solid-svg-icons"; export default class Menu extends React.Component { render() { return ( <Navbar className='navbar-dark bg-dark'> <Container> <Navbar> <Navbar.Brand href='/todos'> <FontAwesomeIcon icon={faCalendarCheck} /> TodoApp </Navbar.Brand> </Navbar> <Navbar.Collapse id='navbar'> <Nav> <Nav.Link href='/todos'>Tarefas</Nav.Link> <Nav.Link href='/about'>Sobre</Nav.Link> </Nav> </Navbar.Collapse> </Container> </Navbar> ) } } <file_sep>/todo-app/frontend/src/todo/TodoActions.js import axios from 'axios' const URL = 'http://localhost:3005/api/todos' export const changeDescription = event => ({ type: 'DESCRIPTION_CHANGED', payload: event.target.value }) export const search = () => { return(dispatch, getState) => { const description = getState().todo.description const search = description ? `&description__regex=/${description}/` : '' const request = axios.get(`${URL}?sort=-createdAt${search}`) .then(resp => dispatch({ type: 'TODO_SEARCHED', payload: resp.data})) } } export const add = (description) => { return dispatch => { axios.post(URL, { description }) .then(resp => dispatch(clear())) } } export const deleteTodo = todo => { return dispatch => { const request = axios.delete(`${URL}/${todo._id}`) .then(resp => dispatch({ type: 'TODO_DELETE', todo: request.data})) .then(resp => dispatch(search())) } } export const TOOGLE_IS_DONE = 'TOOGLE_IS_DONE' export const toogleIsDone = todo => { return async dispatch => { const request = await axios.put(`${URL}/${todo._id}`, {...todo, done: !todo.done}) dispatch({type: TOOGLE_IS_DONE, todo: request.data}) dispatch(search()) } } export const clear = () => { return [{ type: 'TODO_CLEAR'}, search()] }<file_sep>/todo-app/frontend/src/todo/TodoForm.js import React, { Component } from 'react' import { Form, FormControl, Row, Col } from 'react-bootstrap' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { faPlus, faSearch, faWindowClose } from '@fortawesome/free-solid-svg-icons' import IconButton from '../template/IconButton' import { changeDescription, search, add, clear } from './TodoActions' class TodoForm extends Component { constructor(props) { super(props) this.keyHandlerTodo = this.keyHandlerTodo.bind(this) } UNSAFE_componentWillMount() { this.props.search() } keyHandlerTodo = (e) => { const { add, search, description } = this.props if (e.key === 'Enter') { e.shiftKey ? search() : add(description) } } render() { const { add, search, description } = this.props return ( <Form className='todoForm'> <Row> <Col xs={12} sm={9} md={10}> <FormControl id='description' placeholder='Adicione uma tarefa' onChange={this.props.changeDescription} onKeyPress={this.keyHandlerTodo} value={this.props.description} ></FormControl> </Col> <Col xs={12} sm={3} md={2}> <IconButton variant='primary' icon={faPlus} onClick={() => add(description)} > </IconButton> <IconButton variant='info' icon={faSearch} onClick={search()} > </IconButton> <IconButton variant='light' icon={faWindowClose} onClick={this.props.clear} > </IconButton> </Col> </Row> </Form> ) } } const mapStateToProps = state => ({ description: state.todo.description }) const mapDispatchToProps = dispatch => bindActionCreators({ add, clear, search, changeDescription }, dispatch) export default connect(mapStateToProps, mapDispatchToProps)(TodoForm)<file_sep>/exercicios-react/src/components/FamiliaDognini.jsx import React from "react"; import Membro from "./Membro"; export default props => ( <div> <Membro nome="Guto" sobrenome='Dognini'/> <Membro nome='Larissa' sobrenome='Dognini'/> </div> );
e786be02c67d24739a048b91137d4aa46a275bc7
[ "JavaScript" ]
5
JavaScript
hulken1/Curso-React-COD3R
4caf6ddcddfd012c7076d4e69c4ce58fb9355e74
08adf9eb19892f8d6d259d11ff1123ab0cac5de2
refs/heads/master
<repo_name>nathanmcunha/CPP<file_sep>/requirements.txt click==6.7 Flask==0.12.2 Flask-SQLAlchemy==2.3.2 Flask-WTF==0.14.2 itsdangerous==0.24 Jinja2==2.10 MarkupSafe==1.0 numpy==1.13.0 pandas==0.22.0 python-dateutil==2.6.1 pytz==2017.3 six==1.11.0 SQLAlchemy==1.2.0 Werkzeug==0.14.1 WTForms==2.1<file_sep>/cpp_web/app/app.py from flask import Flask, render_template, request, url_for from Multicriteria import TopSis as tp app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/uploadTopsis', methods=['POST', 'GET']) def uploadTopsis(): if request.method == 'POST': file = request.files['file'] df = tp.calcule(file) return df.to_html()
a07997ae6a44c86e90044107d910514288d4bd0b
[ "Python", "Text" ]
2
Text
nathanmcunha/CPP
35001e81ef955d0b849c8991f2cb87db1482ab84
64ab3d93a8d722c01324ecdc87bd8bdca865aee3
refs/heads/main
<file_sep>#include <SI_EFM8BB2_Register_Enums.h> #include "stdint.h" #include "rtc6705.h" #include <absacc.h> #define FLASH_ADDR 0x1000 SI_SBIT(LED, SFR_P1, 0); extern uint8_t UART_Buffer[12]; extern uint8_t channel_vtx; extern uint8_t channel_vtx_changed; extern void delayS(uint8_t); extern void delayMS(uint8_t); extern void set_chan(uint8_t); extern void enter_DefaultMode_from_RESET(void); uint8_t read_chan_from_mem() { uint8_t chan; IE_EA = 0; chan = CBYTE[FLASH_ADDR]; if (chan > 39) chan = 0; IE_EA = 1; return chan; } void write_chan_to_mem(uint8_t chan) { IE_EA = 0; VDM0CN = 0x80; RSTSRC = 0x02; FLKEY = 0xA5; FLKEY = 0xF1; PSCTL = 3; XBYTE[FLASH_ADDR] = chan; PSCTL = 0; FLKEY = 0xA5; FLKEY = 0xF1; PSCTL = 1; XBYTE[FLASH_ADDR] = chan; PSCTL = 0; IE_EA = 1; } void main(void) { uint8_t i = 0; uint8_t band = 0; uint8_t chan = 0; enter_DefaultMode_from_RESET(); delayMS(150); channel_vtx = read_chan_from_mem(); set_chan(channel_vtx); SCON0 |= SCON0_REN__RECEIVE_ENABLED; LED = 1; while(1) { if (channel_vtx_changed) { write_chan_to_mem(channel_vtx); set_chan(channel_vtx); channel_vtx_changed = 0; } band = channel_vtx / 8; chan = channel_vtx % 8; delayS(2); if (band != 4) { for (i=0;i<band+1;++i) { if (channel_vtx_changed) break; LED = 0; delayS(1); LED = 1; delayMS(300); } } for (i=0;i<chan+1;++i) { if (channel_vtx_changed) break; LED = 0; delayMS(300); LED = 1; delayMS(300); } } } <file_sep>#include <SI_EFM8BB2_Register_Enums.h> uint8_t UART_Buffer[10] = {0}; uint8_t UART_Buffer_Size = 0; uint8_t channel_vtx = 0; uint8_t channel_vtx_changed = 0; extern uint8_t CRC8(uint8_t *, uint8_t); SI_INTERRUPT (UART0_ISR, UART0_IRQn) { uint8_t byte = 0; if (SCON0_RI == 1) { byte = SBUF0; if (UART_Buffer_Size == 1 && byte != 0x55) { UART_Buffer_Size = 0; return; } if (UART_Buffer_Size == 3 && byte > 5) { UART_Buffer_Size = 0; return; } if (UART_Buffer_Size == 0 && byte == 0xAA || UART_Buffer_Size == 1 && byte == 0x55 || UART_Buffer_Size > 1) { UART_Buffer[UART_Buffer_Size] = byte; UART_Buffer_Size++; } if (UART_Buffer_Size > 3 && UART_Buffer_Size == (UART_Buffer[3] + 5)) { UART_Buffer_Size = 0; if (UART_Buffer[2] == 0x07 && CRC8(&UART_Buffer, 5) == UART_Buffer[5] && UART_Buffer[4] < 40 && UART_Buffer[4] != channel_vtx) { channel_vtx = UART_Buffer[4]; channel_vtx_changed = 1; } } if (UART_Buffer_Size > 9) UART_Buffer_Size = 0; } } <file_sep>/**************************************************************************//** * Copyright (c) 2015 by Silicon Laboratories Inc. All rights reserved. * * http://developer.silabs.com/legal/version/v11/Silicon_Labs_Software_License_Agreement.txt *****************************************************************************/ #ifndef __ENDIAN_H__ #define __ENDIAN_H__ #define bswapu16(x) (((x) >> 8) | ((x) << 8)) #define bswapu32(x) (((x) >> 24) | (((x) & 0x00FF0000) >> 8) \ | (((x) & 0x0000FF00) << 8) | ((x) << 24)) #define bswap16(x) bswapu16((uint16_t)(x)) #define bswap32(x) bswapu32((uint32_t)(x)) // Big Endian Compilers #if ((defined __C51__) || (defined __RC51__) || (defined _CC51)) #define htobe16(x) (x) #define htobe32(x) (x) #define be16toh(x) (x) #define be32toh(x) (x) #define htole16(x) bswap16(x) #define htole32(x) bswap32(x) #define le16toh(x) bswap16(x) #define le32toh(x) bswap32(x) #elif ((defined SDCC) || (defined HI_TECH_C) || (defined __ICC8051__)) #define htobe16(x) bswap16(x) #define htobe32(x) bswap32(x) #define be16toh(x) bswap16(x) #define be32toh(x) bswap32(x) #define htole16(x) (x) #define htole32(x) (x) #define le16toh(x) (x) #define le32toh(x) (x) #else #define htobe16(x) (x) #define htobe32(x) (x) #define be16toh(x) (x) #define be32toh(x) (x) #define htole16(x) (x) #define htole32(x) (x) #define le16toh(x) (x) #define le32toh(x) (x) #endif // Compiler Definitions #endif // __ENDIAN_H__ <file_sep>#ifndef rtc6705_h #define rtc6705_h #define RTC6705_REG0_HEAD 0x10 #define RTC6705_REG0_BODY 404 //fine-tuning, fixing hardware issue #define RTC6705_REG1_HEAD 0x11 //10001b to write to reg #define POLYGEN 0xd5 #endif //rtc6705_h<file_sep>/**************************************************************************//** * Copyright (c) 2015 by Silicon Laboratories Inc. All rights reserved. * * http://developer.silabs.com/legal/version/v11/Silicon_Labs_Software_License_Agreement.txt *****************************************************************************/ #ifndef STDINT_H #define STDINT_H #if defined __C51__ typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned long uint32_t; typedef uint32_t uint64_t[2]; typedef signed char int8_t; typedef short int16_t; typedef long int32_t; typedef int32_t int64_t[2]; #elif defined __ICC8051__ /* Fixed size types. These are all optional. */ #ifdef __INT8_T_TYPE__ typedef __INT8_T_TYPE__ int8_t; typedef __UINT8_T_TYPE__ uint8_t; #endif /* __INT8_T_TYPE__ */ #ifdef __INT16_T_TYPE__ typedef __INT16_T_TYPE__ int16_t; typedef __UINT16_T_TYPE__ uint16_t; #endif /* __INT16_T_TYPE__ */ #ifdef __INT32_T_TYPE__ typedef __INT32_T_TYPE__ int32_t; typedef __UINT32_T_TYPE__ uint32_t; #endif /* __INT32_T_TYPE__ */ #ifdef __INT64_T_TYPE__ #pragma language=save #pragma language=extended typedef __INT64_T_TYPE__ int64_t; typedef __UINT64_T_TYPE__ uint64_t; #pragma language=restore #endif /* __INT64_T_TYPE__ */ #endif #endif <file_sep>/****************************************************************************** * Copyright (c) 2015 by Silicon Laboratories Inc. All rights reserved. * * http://developer.silabs.com/legal/version/v11/Silicon_Labs_Software_License_Agreement.txt *****************************************************************************/ #ifndef __SI_TOOLCHAIN_H__ #define __SI_TOOLCHAIN_H__ #include <stdint.h> #include <stdbool.h> /**************************************************************************//** * * @addtogroup toolchain_group Toolchain Abstraction * * @brief Macros for toolchain abstraction. * * # Introduction # * * This header file contains macros that are used to provide an abstraction * for toolchain use in source code. The 8051 compiler requires C-language * extensions in order to fully use features of the 8051 architecture. All * compilers for 8051 implement a set of extensions but use different names * and ways of implementing those extensions. This header file provides * macros that are defined for each supported toolchain and can be used in * the source code. This allows the source code to use 8051 extensions and * remain independent of which toolchain is used for compilation. * * ## Variable and Pointer Declarations ## * * It is often useful to specify the memory area (or segment) of a variable, * pointer, or pointer target. For example, you may wish to place all * variables in XDATA by default, but for variables used in time-sensitive * code you use DATA for efficient access. In this case you declare the * XDATA variable in the normal C way, but declare the variables to be located * in the DATA segment using @ref SI_SEGMENT_VARIABLE. * * Pointers are more complicated because there are two memory spaces * associated with a pointer, the pointer target, and the pointer variable * itself. When using default memory segment for the pointer location and * target, then no special macro is needed. But if you wish to specify the * pointer variable location, or target memory segment, then you can use one * of the following macros to do this in a toolchain-independent way. * * |Pointer segment|Target segment|Macro | * |---------------|--------------|----------------------------------------| * |default |generic |None | * |default |specific |@ref SI_VARIABLE_SEGMENT_POINTER | * |specific |generic |@ref SI_SEGMENT_POINTER | * |specific |specific |@ref SI_SEGMENT_VARIABLE_SEGMENT_POINTER| * * ## Prior Toolchain Abstraction Header File ## * * This file supercedes an earlier header file named `compiler_defs.h`. We * are deprecating the use of compiler_defs.h, however it will remain for * backwards compatibility. This file was created to normalize macro names, * remove unused macros, and to provide documentation. * * ## Supported Toolchains ## * * - Keil/ARM C51 * * @{ * *****************************************************************************/ // Make sure there is a NULL defined if the toolchain does not provide it. #ifndef NULL #define NULL ((void *)0) #endif // ------------------------------- // Keil/ARM C51 // #if defined(__C51__) /// Used with pointers, declares a generic pointer. Generic pointers /// work with any memory space but are inefficient. #define SI_SEG_GENERIC /// Declares a variable to be located in 8051 DATA space. #define SI_SEG_DATA data /// Declares a variable to be located in 8051 IDATA space. #define SI_SEG_IDATA idata /// Declares a variable to be located in 8051 XDATA space. #define SI_SEG_XDATA xdata /// Declares a variable to be located in 8051 PDATA space. #define SI_SEG_PDATA pdata /// Declares a variable to be located in 8051 BDATA (bit-addressable) space. #define SI_SEG_BDATA bdata /// Declares a variable to be located in 8051 CODE space. #define SI_SEG_CODE code /**************************************************************************//** * Declares a bit variable in a bit-addressable memory space. * * @param name The name of the bit variable. *****************************************************************************/ #define SI_BIT(name) bit name /**************************************************************************//** * Declares a bit variable in a bit-addressable SFR or memory space. * * @param name The name of the bit variable. * @param address The address of the byte containing the bit. * @param bitnum The bit number (0-7) within the byte. * * This cannot be used to make any arbitrary SFR or variable into * a bit variable. The underlying memory must support bit-addressability. *****************************************************************************/ #define SI_SBIT(name, address, bitnum) sbit name = address^bitnum /**************************************************************************//** * Declares an 8-bit special function register (SFR) variable. * * @param name The name of the SFR variable. * @param address The address of the SFR. * * This creates a C variable (8-bit) that maps to a physical special function * register of the 8051. This cannot be used to make any arbitrary memory * location into an SFR. The _address_ must map to a real SFR in the memory * map. *****************************************************************************/ #define SI_SFR(name, address) sfr name = address /**************************************************************************//** * Declares a 16-bit special function register (SFR) variable. * * @param name The name of the SFR variable. * @param address The address of the 16-bit SFR. * * This creates a C variable (16-bit) that maps to a physical special function * register of the 8051. This cannot be used to make any arbitrary memory * location into an SFR. The _address_ must map to a real 16-bit SFR in the * memory map. *****************************************************************************/ #define SI_SFR16(name, address) sfr16 name = address #ifndef __SLS_IDE__ /**************************************************************************//** * Define an interrupt handler function for an interrupt vector. * * @param name The name of the interrupt handler function. * @param vector The interrupt vector number. * * This macro defines a function to be an interrupt handler. The _vector_ * parameter is the 8051 interrupt vector number, not the address. This * will cause the compiler to treat the function as the interrupt handler * and generate the appropriate prolog/epilog code. * * @note This macro is used to define the function implementation. To declare * the interrupt function prototype, use @ref SI_INTERRUPT_PROTO. *****************************************************************************/ #define SI_INTERRUPT(name, vector) void name (void) interrupt vector /**************************************************************************//** * Define an interrupt handler function using a specific register bank. * * @param name The name of the interrupt handler function. * @param vector The interrupt vector number. * @param regnum The register bank number (0-3). * * This macro defines a function to be an interrupt handler, using a specific * register bank for the interrupt code. The _vector_ parameter is the 8051 * interrupt vector number, not the address. The _regnum_ parameter is the * register bank number (0-3) that will be used as general purpose registers * for the instructions in the compiled code. Using dedicated register banks * for interrupt handlers allows the prolog code to just switch banks instead * of saving and restoring all the general purpose registers. This can make * interrupt entry/exit faster but requires dedicating a register bank for * the interrupt handler. * * @note This macro is used to define the function implementation. To declare * the interrupt function prototype, use @ref SI_INTERRUPT_PROTO_USING. *****************************************************************************/ #define SI_INTERRUPT_USING(name, vector, regnum) \ void name (void) interrupt vector using regnum /**************************************************************************//** * Declare an interrupt handler prototype for an interrupt vector. * * @param name The name of the interrupt handler function. * @param vector The interrupt vector number. * * This macro declares a function prototype for an interrupt handler. The * _vector_ parameter is the 8051 interrupt vector number, not the address. * Declaring the function prototype this way will cause the compiler to * recognize that the function is an interrupt handler and not a normal C * function. * * @note This macro is used to declare a prototype for the interrupt function. * To define the interrupt function implementation, use @ref SI_INTERRUPT. *****************************************************************************/ #define SI_INTERRUPT_PROTO(name, vector) void name (void) /**************************************************************************//** * Declare an interrupt handler prototype using a specific register bank. * * @param name The name of the interrupt handler function. * @param vector The interrupt vector number. * @param regnum The register bank number (0-3). * * This macro declares a function prototype for an interrupt handler, for a * function that uses a specific register bank for the interrupt code. The * _vector_ parameter is the 8051 interrupt vector number, not the address. * The _regnum_ parameter is the register bank number (0-3) that will be used * as general purpose registers in the function. Declaring the function * prototype this way will cause the compiler to recognize that the function * is an interrupt handler and is not a normal C function. * * @note This macro is used to declare a prototype for the interrupt function. * To define the interrupt function implementation, * use @ref SI_INTERRUPT_USING. *****************************************************************************/ #define SI_INTERRUPT_PROTO_USING(name, vector, regnum) void name (void) /**************************************************************************//** * Define a function to be reentrant (store local variables on the stack). * * @param name The name of the function. * @param return_type The data type of the function return value * (void, int, etc). * @param parameter One C function parameter (or "void") (type and name). * * This macro defines a function to be reentrant. * * You must specify the _return_type_ which is the type of the function. It * can be `void` or any other C type or typedef. The _parameters_ argument * is the list of function parameters. It can be `void` or else it must be * a parameter data type and name. It can also be multiple parameters but * they must be enclosed in parentheses and separated by commas. * * __Example__ * * ~~~~~~~~.c * // The following is used to implement a function with the following * // signature... * uint16_t myFunction(uint8_t parm1, uint8_t parm2); * * SI_REENTRANT_FUNCTION(myFunction, uint16_t, (uint8_t parm1, uint8_t parm2)) * { * // Function implementation body * } * ~~~~~~~~ * * @note This macro is used to define the function implementation. To declare * the function prototype, use @ref SI_REENTRANT_FUNCTION_PROTO. *****************************************************************************/ #define SI_REENTRANT_FUNCTION(name, return_type, parameter) \ return_type name parameter reentrant /**************************************************************************//** * Declare a function to be reentrant (store local variables on the stack). * * @param name The name of the function. * @param return_type The data type of the function return value * (void, int, etc). * @param parameter One C function parameter (or "void") (type and name). * * This macro declares a function prototype for a C function that is reentrant. * See the documentation for @ref SI_REENTRANT_FUNCTION for an explanation of * the macro arguments. This is an advanced feature. * * @note This macro is used to declare a prototype for the function. To * define the function implementation, use @ref SI_REENTRANT_FUNCTION. *****************************************************************************/ #define SI_REENTRANT_FUNCTION_PROTO(name, return_type, parameter) \ return_type name parameter reentrant /**************************************************************************//** * Define a function to use a specific register bank. * * @param name The name of the function. * @param return_value The data type of the function return value * (void, int, etc). * @param parameter One C function parameter (or "void") (type and name). * @param regnum The register bank number (0-3). * * This macro defines a function that uses a specific register bank. The * _regnum_ parameter is the register bank number (0-3) that will be used as * general purpose registers for the instructions in the compiled function * code. Using dedicated register banks for a function can reduce the amount * of registers saving and restoring needed on entry and exit to the * function. However, this is an advanced feature and you should not use it * unless you fully understand how and when to use register banking. * * You must specify the _return_value_ which is the type of the function. It * can be `void` or any other C type or typedef. The _parameters_ argument * is the list of function parameters. It can be `void` or else it must be * a parameter data type and name. It can also be multiple parameters but * they must be enclosed in parentheses and separated by commas. * * __Example__ * * ~~~~~~~~.c * // The following is used to implement a function with the following * // signature, and that uses register bank 3 ... * uint16_t myFunction(uint8_t parm1, uint8_t parm2); * * SI_FUNCTION_USING(myFunction, uint16_t, (uint8_t parm1, uint8_t parm2), 3) * { * // Function implementation body * } * ~~~~~~~~ * * @note This macro is used to define the function implementation. To declare * the function prototype, use @ref SI_FUNCTION_PROTO_USING. *****************************************************************************/ #define SI_FUNCTION_USING(name, return_value, parameter, regnum) \ return_value name parameter using regnum /**************************************************************************//** * Declare a function that uses a specific register bank. * * @param name The name of the function. * @param return_value The data type of the function return value * (void, int, etc). * @param parameter One C function parameter (or "void") (type and name). * @param regnum The register bank number (0-3). * * This macro declares a function prototype for a C function that uses a * specific register its working registers. See the documentation for * @ref SI_FUNCTION_USING for an explanation of the macro arguments. This is * an advanced feature. * * @note This macro is used to declare a prototype for the function. To * define the function implementation, use @ref SI_FUNCTION_USING. *****************************************************************************/ #define SI_FUNCTION_PROTO_USING(name, return_value, parameter, regnum) \ return_value name parameter /**************************************************************************//** * Declare a variable to be located in a specific memory segment. * * @param name The variable name. * @param vartype The variable data type.* @param memseg The memory segment to use for the variable. * * This macro declares a variable to be located in a specific memory area * (or segment) of the 8051 memory space. It is only necessary to use this * macro if you want to force the variable into a specific memory space instead * of the default memory space used by the compiler. The segment can be * one of the following: * * - @ref SI_SEG_DATA * - @ref SI_SEG_IDATA * - @ref SI_SEG_BDATA * - @ref SI_SEG_PDATA * - @ref SI_SEG_XDATA * - @ref SI_SEG_CODE * * __Example__ * * ~~~~~~~~.c * // The following macro can be used to create a variable located in * // XDATA with the following signature: * uint8_t myVar; * * SI_SEGMENT_VARIABLE(myVar, uint8_t, SEG_XDATA); * ~~~~~~~~ *****************************************************************************/ #define SI_SEGMENT_VARIABLE(name, vartype, memseg) vartype memseg name /**************************************************************************//** * Declare a memory segment specific pointer variable. * * @param name The pointer variable name. * @param vartype The pointer data type. * @param targseg The target memory segment for the pointer. * * This macro declares a pointer that points at a specific memory area * (or segment). The memory segment of the pointer variable itself is not * specified and the default is used. The segment can be one of the following: * * - @ref SI_SEG_DATA * - @ref SI_SEG_IDATA * - @ref SI_SEG_BDATA * - @ref SI_SEG_PDATA * - @ref SI_SEG_XDATA * - @ref SI_SEG_CODE * * __Example__ * * ~~~~~~~~.c * // The following macro can be used to create a pointer that points to * // a location in XDATA with the following signature: * uint8_t *pVar; // where pVar is pointing at XDATA * * SI_VARIABLE_SEGMENT_POINTER(pVar, uint8_t, SEG_XDATA); * ~~~~~~~~ *****************************************************************************/ #define SI_VARIABLE_SEGMENT_POINTER(name, vartype, targseg) \ vartype targseg * name /**************************************************************************//** * Declare a memory segment specific pointer variable, in a specific segment. * * @param name The pointer variable name. * @param vartype The pointer data type. * @param targseg The target memory segment for the pointer. * @param memseg The memory segment to use for the pointer variable. * * This macro declares a pointer that points at a specific memory area * (or segment). The pointer variable itself is also located in a specified * memory segment by _memseg_. The arguments _targseg_ and _memseg_ can be * one of the following: * * - @ref SI_SEG_DATA * - @ref SI_SEG_IDATA * - @ref SI_SEG_BDATA * - @ref SI_SEG_PDATA * - @ref SI_SEG_XDATA * - @ref SI_SEG_CODE * * __Example__ * * ~~~~~~~~.c * // The following macro can be used to create a pointer that points to * // a location in XDATA while the pointer itself is located in DATA, with * // the following signature: * uint8_t *pVar; // where pVar is located in DATA and is pointing at XDATA * * SI_SEGMENT_VARIABLE_SEGMENT_POINTER(pVar, uint8_t, SEG_XDATA, SEG_DATA); * ~~~~~~~~ *****************************************************************************/ #define SI_SEGMENT_VARIABLE_SEGMENT_POINTER(name, vartype, targseg, memseg) \ vartype targseg * memseg name /**************************************************************************//** * Declare a generic pointer variable that is located in a specific segment. * * @param name The pointer variable name. * @param vartype The pointer data type. * @param memseg The memory segment to use for the pointer variable. * * This macro declares a pointer that is a generic pointer. This means it can * point at any kind of memory location. However the pointer variable itself * is located in a specific memory segment by _memseg_, which can be one of * the following: * * - @ref SI_SEG_DATA * - @ref SI_SEG_IDATA * - @ref SI_SEG_BDATA * - @ref SI_SEG_PDATA * - @ref SI_SEG_XDATA * - @ref SI_SEG_CODE * * __Example__ * * ~~~~~~~~.c * // The following macro can be used to create a generic pointer that * // is located in DATA and points at any memory type, with the * // following signature: * uint8_t *pVar; // where pVar is located in DATA and is a generic pointer * * SI_SEGMENT_POINTER(pVar, uint8_t, SEG_DATA); * ~~~~~~~~ *****************************************************************************/ #define SI_SEGMENT_POINTER(name, vartype, memseg) vartype * memseg name /**************************************************************************//** * Declare an uninitialized variable that is located at a specific address. * * @param name The variable name. * @param vartype The variable data type. * @param memseg The memory segment to use for the variable. * @param address The memory address of the variable. * * This macro allows declaring a variable that can be placed at a specific * location in memory. This can only be used for variables that do not need * initializers. The _address_ is the memory address within the specified * segment. The memory segment, _memseg_, can be one of the following: * * - @ref SI_SEG_DATA * - @ref SI_SEG_IDATA * - @ref SI_SEG_BDATA * - @ref SI_SEG_PDATA * - @ref SI_SEG_XDATA * - @ref SI_SEG_CODE * * __Example__ * * ~~~~~~~~.c * // The following declares a variable located at 0x4000 in XDATA with * // the following signature: * uint8_t myMemVar; * * SI_LOCATED_VARIABLE_NO_INIT(myMemVar, uint8_t, SEG_DATA, 0x4000); * ~~~~~~~~ *****************************************************************************/ #define SI_LOCATED_VARIABLE_NO_INIT(name, vartype, memseg, address) \ vartype memseg name _at_ address #else // __SLS_IDE__ : Macros defined to remove syntax errors within Simplicity Studio #define SI_INTERRUPT(name, vector) void name (void) #define SI_INTERRUPT_USING(name, vector, regnum) void name (void) #define SI_INTERRUPT_PROTO(name, vector) void name (void) #define SI_INTERRUPT_PROTO_USING(name, vector, regnum) void name (void) #define SI_REENTRANT_FUNCTION(name, return_value, parameter, regnum) return_value name (parameter) #define SI_REENTRANT_FUNCTION_PROTO(name, return_value, parameter, regnum) return_value name (parameter) #define SI_FUNCTION_USING(name, return_value, parameter, regnum) return_value name (parameter) #define SI_FUNCTION_PROTO_USING(name, return_value, parameter, regnum) return_value name (parameter) // Note: Parameter must be either 'void' or include a variable type and name. (Ex: char temp_variable) #define SI_SEGMENT_VARIABLE(name, vartype, locsegment) vartype name #define SI_VARIABLE_SEGMENT_POINTER(name, vartype, targsegment) vartype * name #define SI_SEGMENT_VARIABLE_SEGMENT_POINTER(name, vartype, targsegment, locsegment) vartype * name #define SI_SEGMENT_POINTER(name, vartype, locsegment) vartype * name #define SI_LOCATED_VARIABLE_NO_INIT(name, vartype, locsegment, addr) vartype name #endif // __SLS_IDE__ // The following are used for byte ordering when referring to individual // bytes within a SI_UU32_t. B0 is the least significant byte. #define B0 3 ///< Least significant byte of a 4 byte word #define B1 2 ///< Byte 1 of a 4-byte word, where byte 0 is LSB #define B2 1 ///< Byte 2 of a 4-byte word, where byte 0 is LSB #define B3 0 ///< Most significant byte of a 4-byte word #define LSB 1 ///< Index to least significant bit of a 2 byte word #define MSB 0 ///< Index to most significant bit of a 2 byte word /// A union type to make it easier to access individual bytes of a 16-bit /// word, and to use as signed or unsigned type. typedef union SI_UU16 { uint16_t u16; ///< The two byte value as a 16-bit unsigned integer. int16_t s16; ///< The two byte value as a 16-bit signed integer. uint8_t u8[2]; ///< The two byte value as two unsigned 8-bit integers. int8_t s8[2]; ///< The two byte value as two signed 8-bit integers. } SI_UU16_t; /// A union type to make it easier to access individual bytes within a /// 32-bit word, or to access it as variations of 16-bit words, or to /// use as signed or unsigned type. typedef union SI_UU32 { uint32_t u32; ///< The 4-byte value as a 32-bit unsigned integer. int32_t s32; ///< The 4-byte value as a 32-bit signed integer. SI_UU16_t uu16[2]; ///< The 4-byte value as a SI_UU16_t. uint16_t u16[2]; ///< The 4-byte value as two unsigned 16-bit integers. int16_t s16[2]; ///< The 4-byte value as two signed 16-bit integers. uint8_t u8[4]; ///< The 4-byte value as 4 unsigned 8-bit integers. int8_t s8[4]; ///< The 4-byte value as 4 signed 8-bit integers. } SI_UU32_t; // Generic pointer memory segment constants. #define SI_GPTR ///< Generic pointer indeterminate type. #define SI_GPTR_MTYPE_DATA 0x00 ///< Generic pointer for DATA segment. #define SI_GPTR_MTYPE_IDATA 0x00 ///< Generic pointer for IDATA segment. #define SI_GPTR_MTYPE_BDATA 0x00 ///< Generic pointer for BDATA segment. #define SI_GPTR_MTYPE_PDATA 0xFE ///< Generic pointer for PDATA segment. #define SI_GPTR_MTYPE_XDATA 0x01 ///< Generic pointer for XDATA segment. #define SI_GPTR_MTYPE_CODE 0xFF ///< Generic pointer for CODE segment. /// Generic pointer structure containing the type and address. typedef struct { uint8_t memtype; ///< The type of memory of the generic pointer. SI_UU16_t address; ///< The address of the generic pointer. } GPTR_t; /// A union type to allow access to the fields of a generic pointer. /// A generic pointer has a field indicating the type of memory and an /// address within the memory. typedef union SI_GEN_PTR { uint8_t u8[3]; ///< 3-byte generic pointer as 3 unsigned 8-bit integers. GPTR_t gptr; ///< 3-byte generic pointer as pointer structure } SI_GEN_PTR_t; // Declaration of Keil intrinisc extern void _nop_(void); /// Macro to insert a no-operation (NOP) instruction. #define NOP() _nop_() // ------------------------------- // GCC for ARM Cortex-M // Provides support for code that can be compiled for 8 or 32-bit // #elif defined (__GNUC__) #if defined(__ARMEL__) && ((__ARMEL__ == 1) && ((__ARM_ARCH == 6) || (__ARM_ARCH == 7))) // these ignore any memory segment directives #define SI_SEG_GENERIC #define SI_SEG_DATA #define SI_SEG_IDATA #define SI_SEG_XDATA #define SI_SEG_PDATA #define SI_SEG_BDATA #define SI_SEG_CODE // the following create a variable of the specified name but ignore the // address and bit number. If the using-code cares about the actual // address or bit number, this probably will break it #define SI_SBIT(name, address, bitnum) uint8_t name #define SI_SFR(name, address) uint8_t name #define SI_SFR16(name, address) uint16_t name // the following create function and variable names of the specified types // but the 8051-specific aspects (like memory segment) are ignored #define SI_INTERRUPT(name, vector) void name (void) #define SI_INTERRUPT_USING(name, vector, regnum) void name (void) #define SI_INTERRUPT_PROTO(name, vector) void name (void) #define SI_INTERRUPT_PROTO_USING(name, vector, regnum) void name (void) #define SI_FUNCTION_USING(name, return_value, parameter, regnum) \ return_value name (parameter) #define SI_FUNCTION_PROTO_USING(name, return_value, parameter, regnum) \ return_value name (parameter) #define SI_SEGMENT_VARIABLE(name, vartype, memseg) vartype name #define SI_VARIABLE_SEGMENT_POINTER(name, vartype, targseg) \ vartype * name #define SI_SEGMENT_VARIABLE_SEGMENT_POINTER(name, vartype, targseg, memseg) \ vartype * name #define SI_SEGMENT_POINTER(name, vartype, memseg) vartype * name #define SI_LOCATED_VARIABLE_NO_INIT(name, vartype, memseg, address) \ vartype name #define B0 0 #define B1 1 #define B2 2 #define B3 3 #define LSB 0 #define MSB 1 typedef union SI_UU16 { uint16_t u16; int16_t s16; uint8_t u8[2]; int8_t s8[2]; } SI_UU16_t; typedef union SI_UU32 { uint32_t u32; int32_t s32; SI_UU16_t uu16[2]; uint16_t u16[2]; int16_t s16[2]; uint8_t u8[4]; int8_t s8[4]; } SI_UU32_t; // Generic pointer stuff is left out because if you are accessing // generic pointer fields then it will need to be rewritten for 32-bit // __NOP should be declared in cmsis header core_cmInstr.h extern void __NOP(void); /// Macro to insert a no-operation (NOP) instruction. #define NOP() __NOP() #else // ARM_ARCH 6 | 7 #error unsupported ARM arch #endif //----------------------------------------------------------------------------- // IAR 8051 // http://www.iar.com #elif defined __ICC8051__ #include <intrinsics.h> #define SI_BIT(name) __no_init bool __bit name #define SI_SBIT(name, addr, bit) __bit __no_init volatile bool name @ (addr+bit) #define SI_SFR(name, addr) __sfr __no_init volatile unsigned char name @ addr #define SI_SFR16(name, addr) __sfr __no_init volatile unsigned int name @ addr #define SI_SEG_GENERIC __generic #define SI_SEG_FAR __xdata #define SI_SEG_DATA __data #define SI_SEG_NEAR __data #define SI_SEG_IDATA __idata #define SI_SEG_XDATA __xdata #define SI_SEG_PDATA __pdata #define SI_SEG_CODE __code #define SI_SEG_BDATA __bdata #define _PPTOSTR_(x) #x #define _PPARAM_(address) _PPTOSTR_(vector=address * 8 + 3) #define _PPARAM2_(regbank) _PPTOSTR_(register_bank=regbank) #define SI_INTERRUPT(name, vector) _Pragma(_PPARAM_(vector)) __interrupt void name(void) #define SI_INTERRUPT_PROTO(name, vector) __interrupt void name(void) #define SI_INTERRUPT_USING(name, vector, regnum) _Pragma(_PPARAM2_(regnum)) _Pragma(_PPARAM_(vector)) __interrupt void name(void) #define SI_INTERRUPT_PROTO_USING(name, vector, regnum) __interrupt void name(void) #if (__DATA_MODEL__ == 0) /* TINY */ || \ (__DATA_MODEL__ == 1) /* SMALL */ #define SI_REENTRANT_FUNCTION(name, return_type, parameter) \ __idata_reentrant return_type name parameter #define SI_REENTRANT_FUNCTION_PROTO(name, return_type, parameter) \ __idata_reentrant return_type name parameter #elif (__DATA_MODEL__ == 2) /* LARGE */ || \ (__DATA_MODEL__ == 3) /* GENERIC */ || \ (__DATA_MODEL__ == 4) /* FAR */ #define SI_REENTRANT_FUNCTION(name, return_type, parameter) \ __xdata_reentrant return_type name parameter #define SI_REENTRANT_FUNCTION_PROTO(name, return_type, parameter) \ __xdata_reentrant return_type name (parameter) #else #error "Illegal memory model setting." #endif // Note: IAR does not support functions using different register banks. Register // banks can only be specified in interrupts. If a function is called from // inside an interrupt, it will use the same register bank as the interrupt. #define SI_FUNCTION_USING(name, return_value, parameter, regnum) \ return_value name parameter #define SI_FUNCTION_PROTO_USING(name, return_value, parameter, regnum) \ return_value name parameter #define SI_SEGMENT_VARIABLE(name, vartype, locsegment) vartype locsegment name #define SI_VARIABLE_SEGMENT_POINTER(name, vartype, targsegment) vartype targsegment * name #define SI_SEGMENT_VARIABLE_SEGMENT_POINTER(name, vartype, targsegment, locsegment) vartype targsegment * locsegment name #define SI_SEGMENT_POINTER(name, vartype, ptrseg) vartype __generic * ptrseg name #define SI_LOCATED_VARIABLE(name, vartype, locsegment, addr, init) locsegment __no_init vartype name @ addr #define SI_LOCATED_VARIABLE_NO_INIT(name, vartype, locsegment, addr) locsegment __no_init vartype name @ addr // The following are used for byte ordering when referring to individual // bytes within a SI_UU32_t. B0 is the least significant byte. #define B0 0 ///< Least significant byte of a 4 byte word #define B1 1 ///< Byte 1 of a 4-byte word, where byte 0 is LSB #define B2 2 ///< Byte 2 of a 4-byte word, where byte 0 is LSB #define B3 3 ///< Most significant byte of a 4-byte word #define LSB 0 ///< Index to least significant bit of a 2 byte word #define MSB 1 ///< Index to most significant bit of a 2 byte word /// A union type to make it easier to access individual bytes of a 16-bit /// word, and to use as signed or unsigned type. typedef union SI_UU16 { uint16_t u16; ///< The two byte value as a 16-bit unsigned integer. int16_t s16; ///< The two byte value as a 16-bit signed integer. uint8_t u8[2]; ///< The two byte value as two unsigned 8-bit integers. int8_t s8[2]; ///< The two byte value as two signed 8-bit integers. } SI_UU16_t; /// A union type to make it easier to access individual bytes within a /// 32-bit word, or to access it as variations of 16-bit words, or to /// use as signed or unsigned type. typedef union SI_UU32 { uint32_t u32; ///< The 4-byte value as a 32-bit unsigned integer. int32_t s32; ///< The 4-byte value as a 32-bit signed integer. SI_UU16_t uu16[2]; ///< The 4-byte value as a SI_UU16_t. uint16_t u16[2]; ///< The 4-byte value as two unsigned 16-bit integers. int16_t s16[2]; ///< The 4-byte value as two signed 16-bit integers. uint8_t u8[4]; ///< The 4-byte value as 4 unsigned 8-bit integers. int8_t s8[4]; ///< The 4-byte value as 4 signed 8-bit integers. } SI_UU32_t; // Generic pointer memory segment constants. #define SI_GPTR ///< Generic pointer indeterminate type. #define SI_GPTR_MTYPE_DATA 0x01 ///< Generic pointer for DATA segment. #define SI_GPTR_MTYPE_IDATA 0x01 ///< Generic pointer for IDATA segment. #define SI_GPTR_MTYPE_BDATA 0x01 ///< Generic pointer for BDATA segment. #define SI_GPTR_MTYPE_PDATA 0x00 ///< Generic pointer for PDATA segment. #define SI_GPTR_MTYPE_XDATA 0x00 ///< Generic pointer for XDATA segment. #define SI_GPTR_MTYPE_CODE 0x80 ///< Generic pointer for CODE segment. /// Generic pointer structure containing the type and address. typedef struct { SI_UU16_t address; ///< The address of the generic pointer. uint8_t memtype; ///< The type of memory of the generic pointer. } GPTR_t; /// A union type to allow access to the fields of a generic pointer. /// A generic pointer has a field indicating the type of memory and an /// address within the memory. typedef union SI_GEN_PTR { uint8_t u8[3]; ///< 3-byte generic pointer as 3 unsigned 8-bit integers. GPTR_t gptr; ///< 3-byte generic pointer as pointer structure } SI_GEN_PTR_t; /// Macro to insert a no-operation (NOP) instruction. #define NOP() __no_operation() #else // unknown toolchain #error Unrecognized toolchain in si_toolchain.h #endif /** @} */ #endif <file_sep>//------------------------------------------------------------------------------ // Copyright 2014 Silicon Laboratories, Inc. // All rights reserved. This program and the accompanying materials // are made available under the terms of the Silicon Laboratories End User // License Agreement which accompanies this distribution, and is available at // http://developer.silabs.com/legal/version/v11/Silicon_Labs_Software_License_Agreement.txt // Original content and implementation provided by Silicon Laboratories. //------------------------------------------------------------------------------ //Supported Devices: // EFM8BB21F16A_QFN20 // EFM8BB21F16G_QFN20 // EFM8BB21F16G_QSOP24 // EFM8BB21F16I_QFN20 // EFM8BB21F16I_QSOP24 // EFM8BB22F16A_QFN28 // EFM8BB22F16G_QFN28 // EFM8BB22F16I_QFN28 #ifndef SI_EFM8BB2_DEFS_H #define SI_EFM8BB2_DEFS_H #include <si_toolchain.h> //----------------------------------------------------------------------------- // Register Definitions //----------------------------------------------------------------------------- SI_SFR (ACC, 0xE0); ///< Accumulator SI_SFR (ADC0AC, 0xB3); ///< ADC0 Accumulator Configuration SI_SFR (ADC0CF, 0xBC); ///< ADC0 Configuration SI_SFR (ADC0CN0, 0xE8); ///< ADC0 Control 0 SI_SFR (ADC0CN1, 0xB2); ///< ADC0 Control 1 SI_SFR (ADC0GTH, 0xC4); ///< ADC0 Greater-Than High Byte SI_SFR (ADC0GTL, 0xC3); ///< ADC0 Greater-Than Low Byte SI_SFR (ADC0H, 0xBE); ///< ADC0 Data Word High Byte SI_SFR (ADC0L, 0xBD); ///< ADC0 Data Word Low Byte SI_SFR (ADC0LTH, 0xC6); ///< ADC0 Less-Than High Byte SI_SFR (ADC0LTL, 0xC5); ///< ADC0 Less-Than Low Byte SI_SFR (ADC0MX, 0xBB); ///< ADC0 Multiplexer Selection SI_SFR (ADC0PWR, 0xDF); ///< ADC0 Power Control SI_SFR (ADC0TK, 0xB9); ///< ADC0 Burst Mode Track Time SI_SFR (B, 0xF0); ///< B Register SI_SFR (CKCON0, 0x8E); ///< Clock Control 0 SI_SFR (CKCON1, 0xA6); ///< Clock Control 1 SI_SFR (CLKSEL, 0xA9); ///< Clock Select SI_SFR (CMP0CN0, 0x9B); ///< Comparator 0 Control 0 SI_SFR (CMP0CN1, 0x99); ///< Comparator 0 Control 1 SI_SFR (CMP0MD, 0x9D); ///< Comparator 0 Mode SI_SFR (CMP0MX, 0x9F); ///< Comparator 0 Multiplexer Selection SI_SFR (CMP1CN0, 0xBF); ///< Comparator 1 Control 0 SI_SFR (CMP1CN1, 0xAC); ///< Comparator 1 Control 1 SI_SFR (CMP1MD, 0xAB); ///< Comparator 1 Mode SI_SFR (CMP1MX, 0xAA); ///< Comparator 1 Multiplexer Selection SI_SFR (CRC0CN0, 0xCE); ///< CRC0 Control 0 SI_SFR (CRC0CN1, 0x86); ///< CRC0 Control 1 SI_SFR (CRC0CNT, 0xD3); ///< CRC0 Automatic Flash Sector Count SI_SFR (CRC0DAT, 0xDE); ///< CRC0 Data Output SI_SFR (CRC0FLIP, 0xCF); ///< CRC0 Bit Flip SI_SFR (CRC0IN, 0xDD); ///< CRC0 Data Input SI_SFR (CRC0ST, 0xD2); ///< CRC0 Automatic Flash Sector Start SI_SFR (DERIVID, 0xAD); ///< Derivative Identification SI_SFR (DEVICEID, 0xB5); ///< Device Identification SI_SFR (DPH, 0x83); ///< Data Pointer High SI_SFR (DPL, 0x82); ///< Data Pointer Low SI_SFR (EIE1, 0xE6); ///< Extended Interrupt Enable 1 SI_SFR (EIE2, 0xCE); ///< Extended Interrupt Enable 2 SI_SFR (EIP1, 0xF3); ///< Extended Interrupt Priority 1 Low SI_SFR (EIP1H, 0xF5); ///< Extended Interrupt Priority 1 High SI_SFR (EIP2, 0xF4); ///< Extended Interrupt Priority 2 SI_SFR (EIP2H, 0xF6); ///< Extended Interrupt Priority 2 High SI_SFR (EMI0CN, 0xE7); ///< External Memory Interface Control SI_SFR (FLKEY, 0xB7); ///< Flash Lock and Key SI_SFR (HFO0CAL, 0xC7); ///< High Frequency Oscillator 0 Calibration SI_SFR (HFO1CAL, 0xD6); ///< High Frequency Oscillator 1 Calibration SI_SFR (HFOCN, 0xEF); ///< High Frequency Oscillator Control SI_SFR (I2C0CN0, 0xBA); ///< I2C0 Control SI_SFR (I2C0DIN, 0xBC); ///< I2C0 Received Data SI_SFR (I2C0DOUT, 0xBB); ///< I2C0 Transmit Data SI_SFR (I2C0FCN0, 0xAD); ///< I2C0 FIFO Control 0 SI_SFR (I2C0FCN1, 0xAB); ///< I2C0 FIFO Control 1 SI_SFR (I2C0FCT, 0xF5); ///< I2C0 FIFO Count SI_SFR (I2C0SLAD, 0xBD); ///< I2C0 Slave Address SI_SFR (I2C0STAT, 0xB9); ///< I2C0 Status SI_SFR (IE, 0xA8); ///< Interrupt Enable SI_SFR (IP, 0xB8); ///< Interrupt Priority SI_SFR (IPH, 0xF2); ///< Interrupt Priority High SI_SFR (IT01CF, 0xE4); ///< INT0/INT1 Configuration SI_SFR (LFO0CN, 0xB1); ///< Low Frequency Oscillator Control SI_SFR (P0, 0x80); ///< Port 0 Pin Latch SI_SFR (P0MASK, 0xFE); ///< Port 0 Mask SI_SFR (P0MAT, 0xFD); ///< Port 0 Match SI_SFR (P0MDIN, 0xF1); ///< Port 0 Input Mode SI_SFR (P0MDOUT, 0xA4); ///< Port 0 Output Mode SI_SFR (P0SKIP, 0xD4); ///< Port 0 Skip SI_SFR (P1, 0x90); ///< Port 1 Pin Latch SI_SFR (P1MASK, 0xEE); ///< Port 1 Mask SI_SFR (P1MAT, 0xED); ///< Port 1 Match SI_SFR (P1MDIN, 0xF2); ///< Port 1 Input Mode SI_SFR (P1MDOUT, 0xA5); ///< Port 1 Output Mode SI_SFR (P1SKIP, 0xD5); ///< Port 1 Skip SI_SFR (P2, 0xA0); ///< Port 2 Pin Latch SI_SFR (P2MASK, 0xFC); ///< Port 2 Mask SI_SFR (P2MAT, 0xFB); ///< Port 2 Match SI_SFR (P2MDIN, 0xF3); ///< Port 2 Input Mode SI_SFR (P2MDOUT, 0xA6); ///< Port 2 Output Mode SI_SFR (P2SKIP, 0xCC); ///< Port 2 Skip SI_SFR (P3, 0xB0); ///< Port 3 Pin Latch SI_SFR (P3MDIN, 0xF4); ///< Port 3 Input Mode SI_SFR (P3MDOUT, 0x9C); ///< Port 3 Output Mode SI_SFR (PCA0CENT, 0x9E); ///< PCA Center Alignment Enable SI_SFR (PCA0CLR, 0x9C); ///< PCA Comparator Clear Control SI_SFR (PCA0CN0, 0xD8); ///< PCA Control SI_SFR (PCA0CPH0, 0xFC); ///< PCA Channel 0 Capture Module High Byte SI_SFR (PCA0CPH1, 0xEA); ///< PCA Channel 1 Capture Module High Byte SI_SFR (PCA0CPH2, 0xEC); ///< PCA Channel 2 Capture Module High Byte SI_SFR (PCA0CPL0, 0xFB); ///< PCA Channel 0 Capture Module Low Byte SI_SFR (PCA0CPL1, 0xE9); ///< PCA Channel 1 Capture Module Low Byte SI_SFR (PCA0CPL2, 0xEB); ///< PCA Channel 2 Capture Module Low Byte SI_SFR (PCA0CPM0, 0xDA); ///< PCA Channel 0 Capture/Compare Mode SI_SFR (PCA0CPM1, 0xDB); ///< PCA Channel 1 Capture/Compare Mode SI_SFR (PCA0CPM2, 0xDC); ///< PCA Channel 2 Capture/Compare Mode SI_SFR (PCA0H, 0xFA); ///< PCA Counter/Timer High Byte SI_SFR (PCA0L, 0xF9); ///< PCA Counter/Timer Low Byte SI_SFR (PCA0MD, 0xD9); ///< PCA Mode SI_SFR (PCA0POL, 0x96); ///< PCA Output Polarity SI_SFR (PCA0PWM, 0xF7); ///< PCA PWM Configuration SI_SFR (PCON0, 0x87); ///< Power Control SI_SFR (PCON1, 0x9A); ///< Power Control 1 SI_SFR (PFE0CN, 0xC1); ///< Prefetch Engine Control SI_SFR (PRTDRV, 0xF6); ///< Port Drive Strength SI_SFR (PSCTL, 0x8F); ///< Program Store Control SI_SFR (PSW, 0xD0); ///< Program Status Word SI_SFR (REF0CN, 0xD1); ///< Voltage Reference Control SI_SFR (REG0CN, 0xC9); ///< Voltage Regulator 0 Control SI_SFR (REG1CN, 0xC6); ///< Voltage Regulator 1 Control SI_SFR (REVID, 0xB6); ///< Revision Identifcation SI_SFR (RSTSRC, 0xEF); ///< Reset Source SI_SFR (SBCON1, 0x94); ///< UART1 Baud Rate Generator Control SI_SFR (SBRLH1, 0x96); ///< UART1 Baud Rate Generator High Byte SI_SFR (SBRLL1, 0x95); ///< UART1 Baud Rate Generator Low Byte SI_SFR (SBUF0, 0x99); ///< UART0 Serial Port Data Buffer SI_SFR (SBUF1, 0x92); ///< UART1 Serial Port Data Buffer SI_SFR (SCON0, 0x98); ///< UART0 Serial Port Control SI_SFR (SCON1, 0xC8); ///< UART1 Serial Port Control SI_SFR (SFRPAGE, 0xA7); ///< SFR Page SI_SFR (SFRPGCN, 0xCF); ///< SFR Page Control SI_SFR (SFRSTACK, 0xD7); ///< SFR Page Stack SI_SFR (SMB0ADM, 0xD6); ///< SMBus 0 Slave Address Mask SI_SFR (SMB0ADR, 0xD7); ///< SMBus 0 Slave Address SI_SFR (SMB0CF, 0xC1); ///< SMBus 0 Configuration SI_SFR (SMB0CN0, 0xC0); ///< SMBus 0 Control SI_SFR (SMB0DAT, 0xC2); ///< SMBus 0 Data SI_SFR (SMB0FCN0, 0xC3); ///< SMBus 0 FIFO Control 0 SI_SFR (SMB0FCN1, 0xC4); ///< SMBus 0 FIFO Control 1 SI_SFR (SMB0FCT, 0xEF); ///< SMBus 0 FIFO Count SI_SFR (SMB0RXLN, 0xC5); ///< SMBus 0 Receive Length Counter SI_SFR (SMB0TC, 0xAC); ///< SMBus 0 Timing and Pin Control SI_SFR (SMOD1, 0x93); ///< UART1 Mode SI_SFR (SP, 0x81); ///< Stack Pointer SI_SFR (SPI0CFG, 0xA1); ///< SPI0 Configuration SI_SFR (SPI0CKR, 0xA2); ///< SPI0 Clock Rate SI_SFR (SPI0CN0, 0xF8); ///< SPI0 Control SI_SFR (SPI0DAT, 0xA3); ///< SPI0 Data SI_SFR (SPI0FCN0, 0x9A); ///< SPI0 FIFO Control 0 SI_SFR (SPI0FCN1, 0x9B); ///< SPI0 FIFO Control 1 SI_SFR (SPI0FCT, 0xF7); ///< SPI0 FIFO Count SI_SFR (TCON, 0x88); ///< Timer 0/1 Control SI_SFR (TH0, 0x8C); ///< Timer 0 High Byte SI_SFR (TH1, 0x8D); ///< Timer 1 High Byte SI_SFR (TL0, 0x8A); ///< Timer 0 Low Byte SI_SFR (TL1, 0x8B); ///< Timer 1 Low Byte SI_SFR (TMOD, 0x89); ///< Timer 0/1 Mode SI_SFR (TMR2CN0, 0xC8); ///< Timer 2 Control 0 SI_SFR (TMR2CN1, 0xFD); ///< Timer 2 Control 1 SI_SFR (TMR2H, 0xCD); ///< Timer 2 High Byte SI_SFR (TMR2L, 0xCC); ///< Timer 2 Low Byte SI_SFR (TMR2RLH, 0xCB); ///< Timer 2 Reload High Byte SI_SFR (TMR2RLL, 0xCA); ///< Timer 2 Reload Low Byte SI_SFR (TMR3CN0, 0x91); ///< Timer 3 Control 0 SI_SFR (TMR3CN1, 0xFE); ///< Timer 3 Control 1 SI_SFR (TMR3H, 0x95); ///< Timer 3 High Byte SI_SFR (TMR3L, 0x94); ///< Timer 3 Low Byte SI_SFR (TMR3RLH, 0x93); ///< Timer 3 Reload High Byte SI_SFR (TMR3RLL, 0x92); ///< Timer 3 Reload Low Byte SI_SFR (TMR4CN0, 0x98); ///< Timer 4 Control 0 SI_SFR (TMR4CN1, 0xFF); ///< Timer 4 Control 1 SI_SFR (TMR4H, 0xA5); ///< Timer 4 High Byte SI_SFR (TMR4L, 0xA4); ///< Timer 4 Low Byte SI_SFR (TMR4RLH, 0xA3); ///< Timer 4 Reload High Byte SI_SFR (TMR4RLL, 0xA2); ///< Timer 4 Reload Low Byte SI_SFR (UART1FCN0, 0x9D); ///< UART1 FIFO Control 0 SI_SFR (UART1FCN1, 0xD8); ///< UART1 FIFO Control 1 SI_SFR (UART1FCT, 0xFA); ///< UART1 FIFO Count SI_SFR (UART1LIN, 0x9E); ///< UART1 LIN Configuration SI_SFR (VDM0CN, 0xFF); ///< Supply Monitor Control SI_SFR (WDTCN, 0x97); ///< Watchdog Timer Control SI_SFR (XBR0, 0xE1); ///< Port I/O Crossbar 0 SI_SFR (XBR1, 0xE2); ///< Port I/O Crossbar 1 SI_SFR (XBR2, 0xE3); ///< Port I/O Crossbar 2 //------------------------------------------------------------------------------ // 16-bit Register Definitions (may not work on all compilers) //------------------------------------------------------------------------------ SI_SFR16 (ADC0GT, 0xC3); ///< ADC0 Greater-Than SI_SFR16 (ADC0, 0xBD); ///< ADC0 Data Word SI_SFR16 (ADC0LT, 0xC5); ///< ADC0 Less-Than SI_SFR16 (DP, 0x82); ///< Data Pointer SI_SFR16 (PCA0CP0, 0xFB); ///< PCA Channel 0 Capture Module SI_SFR16 (PCA0CP1, 0xE9); ///< PCA Channel 1 Capture Module SI_SFR16 (PCA0CP2, 0xEB); ///< PCA Channel 2 Capture Module SI_SFR16 (PCA0, 0xF9); ///< PCA Counter/Timer SI_SFR16 (SBRL1, 0x95); ///< UART1 Baud Rate Generator SI_SFR16 (TMR2, 0xCC); ///< Timer 2 SI_SFR16 (TMR2RL, 0xCA); ///< Timer 2 Reload SI_SFR16 (TMR3, 0x94); ///< Timer 3 SI_SFR16 (TMR3RL, 0x92); ///< Timer 3 Reload SI_SFR16 (TMR4, 0xA4); ///< Timer 4 SI_SFR16 (TMR4RL, 0xA2); ///< Timer 4 Reload //------------------------------------------------------------------------------ // Indirect Register Definitions //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Bit Definitions //------------------------------------------------------------------------------ // ACC (Accumulator) #define SFR_ACC 0xE0 SI_SBIT (ACC_ACC0, SFR_ACC, 0); ///< Accumulator Bit 0 SI_SBIT (ACC_ACC1, SFR_ACC, 1); ///< Accumulator Bit 1 SI_SBIT (ACC_ACC2, SFR_ACC, 2); ///< Accumulator Bit 2 SI_SBIT (ACC_ACC3, SFR_ACC, 3); ///< Accumulator Bit 3 SI_SBIT (ACC_ACC4, SFR_ACC, 4); ///< Accumulator Bit 4 SI_SBIT (ACC_ACC5, SFR_ACC, 5); ///< Accumulator Bit 5 SI_SBIT (ACC_ACC6, SFR_ACC, 6); ///< Accumulator Bit 6 SI_SBIT (ACC_ACC7, SFR_ACC, 7); ///< Accumulator Bit 7 // ADC0CN0 (ADC0 Control 0) #define SFR_ADC0CN0 0xE8 SI_SBIT (ADC0CN0_ADCM0, SFR_ADC0CN0, 0); ///< Start of Conversion Mode Select Bit 0 SI_SBIT (ADC0CN0_ADCM1, SFR_ADC0CN0, 1); ///< Start of Conversion Mode Select Bit 1 SI_SBIT (ADC0CN0_ADCM2, SFR_ADC0CN0, 2); ///< Start of Conversion Mode Select Bit 2 SI_SBIT (ADC0CN0_ADWINT, SFR_ADC0CN0, 3); ///< Window Compare Interrupt Flag SI_SBIT (ADC0CN0_ADBUSY, SFR_ADC0CN0, 4); ///< ADC Busy SI_SBIT (ADC0CN0_ADINT, SFR_ADC0CN0, 5); ///< Conversion Complete Interrupt Flag SI_SBIT (ADC0CN0_ADBMEN, SFR_ADC0CN0, 6); ///< Burst Mode Enable SI_SBIT (ADC0CN0_ADEN, SFR_ADC0CN0, 7); ///< ADC Enable // B (B Register) #define SFR_B 0xF0 SI_SBIT (B_B0, SFR_B, 0); ///< B Register Bit 0 SI_SBIT (B_B1, SFR_B, 1); ///< B Register Bit 1 SI_SBIT (B_B2, SFR_B, 2); ///< B Register Bit 2 SI_SBIT (B_B3, SFR_B, 3); ///< B Register Bit 3 SI_SBIT (B_B4, SFR_B, 4); ///< B Register Bit 4 SI_SBIT (B_B5, SFR_B, 5); ///< B Register Bit 5 SI_SBIT (B_B6, SFR_B, 6); ///< B Register Bit 6 SI_SBIT (B_B7, SFR_B, 7); ///< B Register Bit 7 // IE (Interrupt Enable) #define SFR_IE 0xA8 SI_SBIT (IE_EX0, SFR_IE, 0); ///< External Interrupt 0 Enable SI_SBIT (IE_ET0, SFR_IE, 1); ///< Timer 0 Interrupt Enable SI_SBIT (IE_EX1, SFR_IE, 2); ///< External Interrupt 1 Enable SI_SBIT (IE_ET1, SFR_IE, 3); ///< Timer 1 Interrupt Enable SI_SBIT (IE_ES0, SFR_IE, 4); ///< UART0 Interrupt Enable SI_SBIT (IE_ET2, SFR_IE, 5); ///< Timer 2 Interrupt Enable SI_SBIT (IE_ESPI0, SFR_IE, 6); ///< SPI0 Interrupt Enable SI_SBIT (IE_EA, SFR_IE, 7); ///< All Interrupts Enable // IP (Interrupt Priority) #define SFR_IP 0xB8 SI_SBIT (IP_PX0, SFR_IP, 0); ///< External Interrupt 0 Priority Control LSB SI_SBIT (IP_PT0, SFR_IP, 1); ///< Timer 0 Interrupt Priority Control LSB SI_SBIT (IP_PX1, SFR_IP, 2); ///< External Interrupt 1 Priority Control LSB SI_SBIT (IP_PT1, SFR_IP, 3); ///< Timer 1 Interrupt Priority Control LSB SI_SBIT (IP_PS0, SFR_IP, 4); ///< UART0 Interrupt Priority Control LSB SI_SBIT (IP_PT2, SFR_IP, 5); ///< Timer 2 Interrupt Priority Control LSB SI_SBIT (IP_PSPI0, SFR_IP, 6); ///< Serial Peripheral Interface (SPI0) Interrupt Priority Control LSB // P0 (Port 0 Pin Latch) #define SFR_P0 0x80 SI_SBIT (P0_B0, SFR_P0, 0); ///< Port 0 Bit 0 Latch SI_SBIT (P0_B1, SFR_P0, 1); ///< Port 0 Bit 1 Latch SI_SBIT (P0_B2, SFR_P0, 2); ///< Port 0 Bit 2 Latch SI_SBIT (P0_B3, SFR_P0, 3); ///< Port 0 Bit 3 Latch SI_SBIT (P0_B4, SFR_P0, 4); ///< Port 0 Bit 4 Latch SI_SBIT (P0_B5, SFR_P0, 5); ///< Port 0 Bit 5 Latch SI_SBIT (P0_B6, SFR_P0, 6); ///< Port 0 Bit 6 Latch SI_SBIT (P0_B7, SFR_P0, 7); ///< Port 0 Bit 7 Latch // P1 (Port 1 Pin Latch) #define SFR_P1 0x90 SI_SBIT (P1_B0, SFR_P1, 0); ///< Port 1 Bit 0 Latch SI_SBIT (P1_B1, SFR_P1, 1); ///< Port 1 Bit 1 Latch SI_SBIT (P1_B2, SFR_P1, 2); ///< Port 1 Bit 2 Latch SI_SBIT (P1_B3, SFR_P1, 3); ///< Port 1 Bit 3 Latch SI_SBIT (P1_B4, SFR_P1, 4); ///< Port 1 Bit 4 Latch SI_SBIT (P1_B5, SFR_P1, 5); ///< Port 1 Bit 5 Latch SI_SBIT (P1_B6, SFR_P1, 6); ///< Port 1 Bit 6 Latch SI_SBIT (P1_B7, SFR_P1, 7); ///< Port 1 Bit 7 Latch // P2 (Port 2 Pin Latch) #define SFR_P2 0xA0 SI_SBIT (P2_B0, SFR_P2, 0); ///< Port 2 Bit 0 Latch SI_SBIT (P2_B1, SFR_P2, 1); ///< Port 2 Bit 1 Latch SI_SBIT (P2_B2, SFR_P2, 2); ///< Port 2 Bit 2 Latch SI_SBIT (P2_B3, SFR_P2, 3); ///< Port 2 Bit 3 Latch // P3 (Port 3 Pin Latch) #define SFR_P3 0xB0 SI_SBIT (P3_B0, SFR_P3, 0); ///< Port 3 Bit 0 Latch SI_SBIT (P3_B1, SFR_P3, 1); ///< Port 3 Bit 1 Latch // PCA0CN0 (PCA Control) #define SFR_PCA0CN0 0xD8 SI_SBIT (PCA0CN0_CCF0, SFR_PCA0CN0, 0); ///< PCA Module 0 Capture/Compare Flag SI_SBIT (PCA0CN0_CCF1, SFR_PCA0CN0, 1); ///< PCA Module 1 Capture/Compare Flag SI_SBIT (PCA0CN0_CCF2, SFR_PCA0CN0, 2); ///< PCA Module 2 Capture/Compare Flag SI_SBIT (PCA0CN0_CR, SFR_PCA0CN0, 6); ///< PCA Counter/Timer Run Control SI_SBIT (PCA0CN0_CF, SFR_PCA0CN0, 7); ///< PCA Counter/Timer Overflow Flag // PSW (Program Status Word) #define SFR_PSW 0xD0 SI_SBIT (PSW_PARITY, SFR_PSW, 0); ///< Parity Flag SI_SBIT (PSW_F1, SFR_PSW, 1); ///< User Flag 1 SI_SBIT (PSW_OV, SFR_PSW, 2); ///< Overflow Flag SI_SBIT (PSW_RS0, SFR_PSW, 3); ///< Register Bank Select Bit 0 SI_SBIT (PSW_RS1, SFR_PSW, 4); ///< Register Bank Select Bit 1 SI_SBIT (PSW_F0, SFR_PSW, 5); ///< User Flag 0 SI_SBIT (PSW_AC, SFR_PSW, 6); ///< Auxiliary Carry Flag SI_SBIT (PSW_CY, SFR_PSW, 7); ///< Carry Flag // SCON0 (UART0 Serial Port Control) #define SFR_SCON0 0x98 SI_SBIT (SCON0_RI, SFR_SCON0, 0); ///< Receive Interrupt Flag SI_SBIT (SCON0_TI, SFR_SCON0, 1); ///< Transmit Interrupt Flag SI_SBIT (SCON0_RB8, SFR_SCON0, 2); ///< Ninth Receive Bit SI_SBIT (SCON0_TB8, SFR_SCON0, 3); ///< Ninth Transmission Bit SI_SBIT (SCON0_REN, SFR_SCON0, 4); ///< Receive Enable SI_SBIT (SCON0_MCE, SFR_SCON0, 5); ///< Multiprocessor Communication Enable SI_SBIT (SCON0_SMODE, SFR_SCON0, 7); ///< Serial Port 0 Operation Mode // SCON1 (UART1 Serial Port Control) #define SFR_SCON1 0xC8 SI_SBIT (SCON1_RI, SFR_SCON1, 0); ///< Receive Interrupt Flag SI_SBIT (SCON1_TI, SFR_SCON1, 1); ///< Transmit Interrupt Flag SI_SBIT (SCON1_RBX, SFR_SCON1, 2); ///< Extra Receive Bit SI_SBIT (SCON1_TBX, SFR_SCON1, 3); ///< Extra Transmission Bit SI_SBIT (SCON1_REN, SFR_SCON1, 4); ///< Receive Enable SI_SBIT (SCON1_PERR, SFR_SCON1, 6); ///< Parity Error Flag SI_SBIT (SCON1_OVR, SFR_SCON1, 7); ///< Receive FIFO Overrun Flag // SMB0CN0 (SMBus 0 Control) #define SFR_SMB0CN0 0xC0 SI_SBIT (SMB0CN0_SI, SFR_SMB0CN0, 0); ///< SMBus Interrupt Flag SI_SBIT (SMB0CN0_ACK, SFR_SMB0CN0, 1); ///< SMBus Acknowledge SI_SBIT (SMB0CN0_ARBLOST, SFR_SMB0CN0, 2); ///< SMBus Arbitration Lost Indicator SI_SBIT (SMB0CN0_ACKRQ, SFR_SMB0CN0, 3); ///< SMBus Acknowledge Request SI_SBIT (SMB0CN0_STO, SFR_SMB0CN0, 4); ///< SMBus Stop Flag SI_SBIT (SMB0CN0_STA, SFR_SMB0CN0, 5); ///< SMBus Start Flag SI_SBIT (SMB0CN0_TXMODE, SFR_SMB0CN0, 6); ///< SMBus Transmit Mode Indicator SI_SBIT (SMB0CN0_MASTER, SFR_SMB0CN0, 7); ///< SMBus Master/Slave Indicator // SPI0CN0 (SPI0 Control) #define SFR_SPI0CN0 0xF8 SI_SBIT (SPI0CN0_SPIEN, SFR_SPI0CN0, 0); ///< SPI0 Enable SI_SBIT (SPI0CN0_TXNF, SFR_SPI0CN0, 1); ///< TX FIFO Not Full SI_SBIT (SPI0CN0_NSSMD0, SFR_SPI0CN0, 2); ///< Slave Select Mode Bit 0 SI_SBIT (SPI0CN0_NSSMD1, SFR_SPI0CN0, 3); ///< Slave Select Mode Bit 1 SI_SBIT (SPI0CN0_RXOVRN, SFR_SPI0CN0, 4); ///< Receive Overrun Flag SI_SBIT (SPI0CN0_MODF, SFR_SPI0CN0, 5); ///< Mode Fault Flag SI_SBIT (SPI0CN0_WCOL, SFR_SPI0CN0, 6); ///< Write Collision Flag SI_SBIT (SPI0CN0_SPIF, SFR_SPI0CN0, 7); ///< SPI0 Interrupt Flag // TCON (Timer 0/1 Control) #define SFR_TCON 0x88 SI_SBIT (TCON_IT0, SFR_TCON, 0); ///< Interrupt 0 Type Select SI_SBIT (TCON_IE0, SFR_TCON, 1); ///< External Interrupt 0 SI_SBIT (TCON_IT1, SFR_TCON, 2); ///< Interrupt 1 Type Select SI_SBIT (TCON_IE1, SFR_TCON, 3); ///< External Interrupt 1 SI_SBIT (TCON_TR0, SFR_TCON, 4); ///< Timer 0 Run Control SI_SBIT (TCON_TF0, SFR_TCON, 5); ///< Timer 0 Overflow Flag SI_SBIT (TCON_TR1, SFR_TCON, 6); ///< Timer 1 Run Control SI_SBIT (TCON_TF1, SFR_TCON, 7); ///< Timer 1 Overflow Flag // TMR2CN0 (Timer 2 Control 0) #define SFR_TMR2CN0 0xC8 SI_SBIT (TMR2CN0_T2XCLK0, SFR_TMR2CN0, 0); ///< Timer 2 External Clock Select Bit 0 SI_SBIT (TMR2CN0_T2XCLK1, SFR_TMR2CN0, 1); ///< Timer 2 External Clock Select Bit 1 SI_SBIT (TMR2CN0_TR2, SFR_TMR2CN0, 2); ///< Timer 2 Run Control SI_SBIT (TMR2CN0_T2SPLIT, SFR_TMR2CN0, 3); ///< Timer 2 Split Mode Enable SI_SBIT (TMR2CN0_TF2CEN, SFR_TMR2CN0, 4); ///< Timer 2 Capture Enable SI_SBIT (TMR2CN0_TF2LEN, SFR_TMR2CN0, 5); ///< Timer 2 Low Byte Interrupt Enable SI_SBIT (TMR2CN0_TF2L, SFR_TMR2CN0, 6); ///< Timer 2 Low Byte Overflow Flag SI_SBIT (TMR2CN0_TF2H, SFR_TMR2CN0, 7); ///< Timer 2 High Byte Overflow Flag // TMR4CN0 (Timer 4 Control 0) #define SFR_TMR4CN0 0x98 SI_SBIT (TMR4CN0_T4XCLK0, SFR_TMR4CN0, 0); ///< Timer 4 External Clock Select Bit 0 SI_SBIT (TMR4CN0_T4XCLK1, SFR_TMR4CN0, 1); ///< Timer 4 External Clock Select Bit 1 SI_SBIT (TMR4CN0_TR4, SFR_TMR4CN0, 2); ///< Timer 4 Run Control SI_SBIT (TMR4CN0_T4SPLIT, SFR_TMR4CN0, 3); ///< Timer 4 Split Mode Enable SI_SBIT (TMR4CN0_TF4CEN, SFR_TMR4CN0, 4); ///< Timer 4 Capture Enable SI_SBIT (TMR4CN0_TF4LEN, SFR_TMR4CN0, 5); ///< Timer 4 Low Byte Interrupt Enable SI_SBIT (TMR4CN0_TF4L, SFR_TMR4CN0, 6); ///< Timer 4 Low Byte Overflow Flag SI_SBIT (TMR4CN0_TF4H, SFR_TMR4CN0, 7); ///< Timer 4 High Byte Overflow Flag // UART1FCN1 (UART1 FIFO Control 1) #define SFR_UART1FCN1 0xD8 SI_SBIT (UART1FCN1_RIE, SFR_UART1FCN1, 0); ///< Receive Interrupt Enable SI_SBIT (UART1FCN1_RXTO0, SFR_UART1FCN1, 1); ///< Receive Timeout Bit 0 SI_SBIT (UART1FCN1_RXTO1, SFR_UART1FCN1, 2); ///< Receive Timeout Bit 1 SI_SBIT (UART1FCN1_RFRQ, SFR_UART1FCN1, 3); ///< Receive FIFO Request SI_SBIT (UART1FCN1_TIE, SFR_UART1FCN1, 4); ///< Transmit Interrupt Enable SI_SBIT (UART1FCN1_TXHOLD, SFR_UART1FCN1, 5); ///< Transmit Hold SI_SBIT (UART1FCN1_TXNF, SFR_UART1FCN1, 6); ///< TX FIFO Not Full SI_SBIT (UART1FCN1_TFRQ, SFR_UART1FCN1, 7); ///< Transmit FIFO Request //------------------------------------------------------------------------------ // Interrupt Definitions //------------------------------------------------------------------------------ #define INT0_IRQn 0 ///< External Interrupt 0 #define TIMER0_IRQn 1 ///< Timer 0 Overflow #define INT1_IRQn 2 ///< External Interrupt 1 #define TIMER1_IRQn 3 ///< Timer 1 Overflow #define UART0_IRQn 4 ///< UART0 #define TIMER2_IRQn 5 ///< Timer 2 Overflow / Capture #define SPI0_IRQn 6 ///< SPI0 #define SMBUS0_IRQn 7 ///< SMBus 0 #define PMATCH_IRQn 8 ///< Port Match #define ADC0WC_IRQn 9 ///< ADC0 Window Compare #define ADC0EOC_IRQn 10 ///< ADC0 End of Conversion #define PCA0_IRQn 11 ///< PCA0 #define CMP0_IRQn 12 ///< Comparator 0 #define CMP1_IRQn 13 ///< Comparator 1 #define TIMER3_IRQn 14 ///< Timer 3 Overflow / Capture #define UART1_IRQn 17 ///< UART1 #define I2C0_IRQn 18 ///< I2C0 Slave #define TIMER4_IRQn 19 ///< Timer 4 Overflow / Capture //------------------------------------------------------------------------------ // SFR Page Definitions //------------------------------------------------------------------------------ #define CRC0_PAGE 0x00 ///< CRC0 Page #define LEGACY_PAGE 0x00 ///< Legacy SFR Page #define PCA0_PAGE 0x00 ///< PCA0 Page #define PG2_PAGE 0x10 ///< Page2 #define TIMER2_PAGE 0x10 ///< Timer 2 Page #define TIMER3_PAGE 0x10 ///< Timer 3 Page #define TIMER4_PAGE 0x10 ///< Timer 4 Page #define I2CSLAVE0_PAGE 0x20 ///< I2C Slave 0 Page #define PG3_PAGE 0x20 ///< Page3 #define SMB0_PAGE 0x20 ///< SMBus 0 Page #define SPI0_PAGE 0x20 ///< SPI0 Page #define UART0_PAGE 0x20 ///< UART0 Page #define UART1_PAGE 0x20 ///< UART1 Page //----------------------------------------------------------------------------- // SDCC PDATA External Memory Paging Support //----------------------------------------------------------------------------- #if defined SDCC SI_SFR(_XPAGE, 0xAA); // Point to the EMI0CN register #endif #endif // SI_EFM8BB2_DEFS_H //-eof-------------------------------------------------------------------------- <file_sep>#include <SI_EFM8BB2_Register_Enums.h> #include "rtc6705.h" #include "stdint.h" extern void delayMSn(uint8_t); SI_SBIT(MOSI, SFR_P1, 2); SI_SBIT(NSS, SFR_P1, 3); SI_SBIT(CLK, SFR_P1, 4); const uint8_t val_a_list[40] = { 48, 60, 8, 20, 32, 44, 56, 4, 12, 39, 2, 29, 56, 19, 46, 9, 16, 28, 40, 52, 36, 24, 12, 0, 59, 47, 35, 23, 11, 63, 51, 39, 57, 22, 51, 16, 45, 10, 39, 4, }; const uint16_t val_n_list[40] = { 2293, 2285, 2278, 2270, 2262, 2254, 2246, 2239, 2242, 2249, 2257, 2264, 2271, 2279, 2286, 2294, 2231, 2223, 2215, 2207, 2301, 2309, 2317, 2325, 2244, 2252, 2260, 2268, 2276, 2283, 2291, 2299, 2212, 2227, 2241, 2256, 2270, 2285, 2299, 2314, }; //these are not real values but fine-tuned tweaked ones uint8_t CRC8(uint8_t *nice_data, uint8_t len) { unsigned char crc = 0; /* start with 0 so first byte can be 'xored' in */ unsigned char currByte; uint8_t i = 0; uint8_t j = 0; for (i = 0; i < len; i++) { currByte = nice_data[i]; crc ^= currByte; /* XOR-in the next input byte */ for (j = 0; j < 8; j++) { if ((crc & 0x80) != 0) { crc = (uint8_t)((crc << 1) ^ POLYGEN); } else { crc <<= 1; } } } return crc; } void SPIsend(uint32_t command) { uint8_t i = 0; NSS = 0; delayMSn(1); for(i = 0; i < 25; ++i) { MOSI = (command >> i) & 1; CLK = 1; delayMSn(1); CLK = 0; delayMSn(1); } MOSI = 0; delayMSn(1); NSS = 1; } void set_chan(uint8_t chan) { uint8_t val_a; uint32_t val_n; uint32_t val_hex; val_a = val_a_list[chan]; val_n = val_n_list[chan]; val_hex = RTC6705_REG0_HEAD; val_hex |= (RTC6705_REG0_BODY << 5); SPIsend(val_hex); delayMSn(1); val_hex = RTC6705_REG1_HEAD; val_hex |= (val_a << 5); val_hex |= (val_n << 12); SPIsend(val_hex); } <file_sep>This is an alternative vtx MCU firmware for Betafpv Lite Brushed V2 flight controller board. Some branches of the FC have a hardware issue that cause the VTX frequency to be 50 MHz ahead of a set frequency. **Only in this case you need a firmware from this repo!** This repo contains only source code, binaries are here https://github.com/vodka-bears/BetterLiteV2. <file_sep>//------------------------------------------------------------------------------ // Copyright 2014 Silicon Laboratories, Inc. // All rights reserved. This program and the accompanying materials // are made available under the terms of the Silicon Laboratories End User // License Agreement which accompanies this distribution, and is available at // http://developer.silabs.com/legal/version/v11/Silicon_Labs_Software_License_Agreement.txt // Original content and implementation provided by Silicon Laboratories. //------------------------------------------------------------------------------ //Supported Devices: // EFM8BB21F16A_QFN20 // EFM8BB21F16G_QFN20 // EFM8BB21F16G_QSOP24 // EFM8BB21F16I_QFN20 // EFM8BB21F16I_QSOP24 // EFM8BB22F16A_QFN28 // EFM8BB22F16G_QFN28 // EFM8BB22F16I_QFN28 #ifndef SI_EFM8BB2_DEVICES_H #define SI_EFM8BB2_DEVICES_H #define EFM8BB21F16A_QFN20 0x23 #define EFM8BB21F16G_QFN20 0x03 #define EFM8BB21F16G_QSOP24 0x02 #define EFM8BB21F16I_QFN20 0x13 #define EFM8BB21F16I_QSOP24 0x12 #define EFM8BB22F16A_QFN28 0x21 #define EFM8BB22F16G_QFN28 0x01 #define EFM8BB22F16I_QFN28 0x11 #if (EFM8BB2_DEVICE == EFM8BB21F16A_QFN20) #define DEVICE_DERIVID EFM8BB21F16A_QFN20 #define DEVICE_FLASH_SIZE 0x4000 #define DEVICE_XRAM_SIZE 0x0800 #define DEVICE_PKG_QFN20 1 #elif (EFM8BB2_DEVICE == EFM8BB21F16G_QFN20) #define DEVICE_DERIVID EFM8BB21F16G_QFN20 #define DEVICE_FLASH_SIZE 0x4000 #define DEVICE_XRAM_SIZE 0x0800 #define DEVICE_PKG_QFN20 1 #elif (EFM8BB2_DEVICE == EFM8BB21F16G_QSOP24) #define DEVICE_DERIVID EFM8BB21F16G_QSOP24 #define DEVICE_FLASH_SIZE 0x4000 #define DEVICE_XRAM_SIZE 0x0800 #define DEVICE_PKG_QSOP24 1 #elif (EFM8BB2_DEVICE == EFM8BB21F16I_QFN20) #define DEVICE_DERIVID EFM8BB21F16I_QFN20 #define DEVICE_FLASH_SIZE 0x4000 #define DEVICE_XRAM_SIZE 0x0800 #define DEVICE_PKG_QFN20 1 #elif (EFM8BB2_DEVICE == EFM8BB21F16I_QSOP24) #define DEVICE_DERIVID EFM8BB21F16I_QSOP24 #define DEVICE_FLASH_SIZE 0x4000 #define DEVICE_XRAM_SIZE 0x0800 #define DEVICE_PKG_QSOP24 1 #elif (EFM8BB2_DEVICE == EFM8BB22F16A_QFN28) #define DEVICE_DERIVID EFM8BB22F16A_QFN28 #define DEVICE_FLASH_SIZE 0x4000 #define DEVICE_XRAM_SIZE 0x0800 #define DEVICE_PKG_QFN28 1 #elif (EFM8BB2_DEVICE == EFM8BB22F16G_QFN28) #define DEVICE_DERIVID EFM8BB22F16G_QFN28 #define DEVICE_FLASH_SIZE 0x4000 #define DEVICE_XRAM_SIZE 0x0800 #define DEVICE_PKG_QFN28 1 #elif (EFM8BB2_DEVICE == EFM8BB22F16I_QFN28) #define DEVICE_DERIVID EFM8BB22F16I_QFN28 #define DEVICE_FLASH_SIZE 0x4000 #define DEVICE_XRAM_SIZE 0x0800 #define DEVICE_PKG_QFN28 1 #endif #endif // SI_EFM8BB2_DEVICES_H //-eof-------------------------------------------------------------------------- <file_sep>#include "stdint.h" extern uint8_t channel_vtx_changed; void delayMS(uint8_t n) { uint8_t i; uint32_t j; for(i=0;i<n;i++) { if (channel_vtx_changed) return; for(j=185;j>0;j--); } } void delayS(uint8_t n) { if (channel_vtx_changed) return; delayMS(1000*n); } void delayMSn(uint8_t n) { uint8_t i; uint32_t j; for(i=0;i<n;i++) for(j=185;j>0;j--); } <file_sep>/**************************************************************************//** * Copyright (c) 2015 by Silicon Laboratories Inc. All rights reserved. * * http://developer.silabs.com/legal/version/v11/Silicon_Labs_Software_License_Agreement.txt *****************************************************************************/ #ifndef STDBOOL_H #define STDBOOL_H #if defined __C51__ typedef bit bool; enum{ false = 0, true = 1, }; #elif defined __ICC8051__ #ifndef _SYSTEM_BUILD #pragma system_include #endif #ifndef __cplusplus #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif /* !__cplusplus */ #else // __SLS_IDE__ : Macros defined to remove syntax errors within Simplicity Studio typedef bit bool; enum{ false = 0, true = 1, }; #endif #endif //STDBOOL_H <file_sep>#include <SI_EFM8BB2_Register_Enums.h> SI_SBIT(MOSI, SFR_P1, 2); SI_SBIT(NSS, SFR_P1, 3); SI_SBIT(CLK, SFR_P1, 4); extern void enter_DefaultMode_from_RESET(void) { //backup SFRPAGE uint8_t SFRPAGE_save = SFRPAGE; SFRPAGE = 0x00; //disable watchdog WDTCN = 0xDE; //First key WDTCN = 0xAD; //Second key P0MDOUT = P0MDOUT_B0__OPEN_DRAIN | P0MDOUT_B1__PUSH_PULL | P0MDOUT_B2__OPEN_DRAIN | P0MDOUT_B3__PUSH_PULL | P0MDOUT_B4__OPEN_DRAIN | P0MDOUT_B5__OPEN_DRAIN | P0MDOUT_B6__OPEN_DRAIN | P0MDOUT_B7__OPEN_DRAIN; P1MDOUT = P1MDOUT_B2__PUSH_PULL | P1MDOUT_B3__PUSH_PULL | P1MDOUT_B4__PUSH_PULL; P1SKIP = P1SKIP_B2__SKIPPED | P1SKIP_B3__SKIPPED | P1SKIP_B2__SKIPPED; XBR2 = XBR2_XBARE__ENABLED; XBR0 = XBR0_URT0E__ENABLED; CKCON0 = CKCON0_SCA__SYSCLK_DIV_4 | CKCON0_T0M__SYSCLK | CKCON0_T2MH__SYSCLK | CKCON0_T2ML__SYSCLK | CKCON0_T3MH__SYSCLK | CKCON0_T3ML__SYSCLK | CKCON0_T1M__PRESCALE; // (24'500'000/8/4)/(256-176) ~= 9570 TH1 = 0xB0; //176 TMOD = TMOD_T1M__MODE2; TCON = TCON_TR1__BMASK; //timer 1 enable IE = IE_ES0__ENABLED; MOSI = 0; CLK = 0; NSS = 1; //restore SFRPAGE SFRPAGE = SFRPAGE_save; }
70b71c3eee12c81a2d31ba13c201b6f82ce6dbd3
[ "Markdown", "C" ]
13
C
vodka-bears/LiteVTX
6c8877606fc343a24d33c0fda71c236666a9e0cc
dabe173ae9de7b39905930f0507e72784a2bc4b7
refs/heads/master
<file_sep> mongo-java-distributed-lock ============= About ------------ A Java distributed lock library that uses [MongoDB](http://www.mongodb.org/) as the central sync point. [See the Wiki](https://github.com/deftlabs/mongo-java-distributed-lock/wiki) for more information. This library is currently in alpha. Usage ------------ * [Javadocs](http://api.deftlabs.com/mongo-java-distributed-lock) * [Getting Started](https://github.com/deftlabs/mongo-java-distributed-lock/wiki/Getting-Started) Build ------------ [![Build Status](https://secure.travis-ci.org/deftlabs/mongo-java-distributed-lock.png)](http://travis-ci.org/deftlabs/mongo-java-distributed-lock) License ------------ Copyright 2011, Deft Labs. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. <file_sep>/** * Copyright 2011, <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deftlabs.lock.mongo.impl; // Lib import com.deftlabs.lock.mongo.DistributedLock; import com.deftlabs.lock.mongo.DistributedLockSvcOptions; // Mongo import com.mongodb.Mongo; import com.mongodb.MongoClient; import org.bson.types.ObjectId; // Java import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * The lock monitors. */ final class Monitor { /** * The lock heartbeat thread is responsible for sending updates to the lock * doc every X seconds (when the lock is owned by the current process). This * library uses missing/stale/old heartbeats to timeout locks that have not been * closed properly (based on the lock/unlock) contract. This can happen when processes * die unexpectedly (e.g., out of memory) or when they are not stopped properly (e.g., kill -9). */ static class LockHeartbeat extends MonitorThread { LockHeartbeat(final MongoClient pMongo, final DistributedLockSvcOptions pSvcOptions, final Map<String, DistributedLock> pLocks) { super("Mongo-Distributed-Lock-LockHeartbeat-" + System.currentTimeMillis(), pMongo, pSvcOptions, pLocks); } @Override boolean monitor() throws InterruptedException { for (final String lockName : _locks.keySet()) { final DistributedLock lock = _locks.get(lockName); final ObjectId lockId = lock.getLockId(); if (!lock.isLocked() || lockId == null) continue; LockDao.heartbeat(_mongo, lockName, lockId, lock.getOptions(), _svcOptions); } return _shutdown.await(_svcOptions.getHeartbeatFrequency(), TimeUnit.MILLISECONDS); } } /** * The lock timeout thread impl (see LockHeartbeat docs for more info). One lock * timeout thread runs in each process this lock lib is running. This thread is * responsible for cleaning up expired locks (based on time since last heartbeat). */ static class LockTimeout extends MonitorThread { LockTimeout(final MongoClient pMongo, final DistributedLockSvcOptions pSvcOptions) { super("Mongo-Distributed-Lock-LockTimeout-" + System.currentTimeMillis(), pMongo, pSvcOptions); } @Override boolean monitor() throws InterruptedException { LockDao.expireInactiveLocks(_mongo, _svcOptions); return _shutdown.await(_svcOptions.getTimeoutFrequency(), TimeUnit.MILLISECONDS); } } /** * The lock unlocked thread is responsible for waking up local * threads when a lock state changes. */ static class LockUnlocked extends MonitorThread { LockUnlocked(final MongoClient pMongo, final DistributedLockSvcOptions pSvcOptions, final Map<String, DistributedLock> pLocks) { super("Mongo-Distributed-Lock-LockUnlocked-" + System.currentTimeMillis(), pMongo, pSvcOptions, pLocks); } @Override boolean monitor() throws InterruptedException { for (final String lockName : _locks.keySet()) { final DistributedLock lock = _locks.get(lockName); if (lock.isLocked()) continue; // Check to see if this is locked. if (LockDao.isLocked(_mongo, lockName, _svcOptions)) continue; // The lock is not locked, wakeup any blocking threads. lock.wakeupBlocked(); } return _shutdown.await(_svcOptions.getLockUnlockedFrequency(), TimeUnit.MILLISECONDS); } } private static abstract class MonitorThread extends Thread { MonitorThread(final String pName, final MongoClient pMongo, final DistributedLockSvcOptions pSvcOptions) { this(pName, pMongo, pSvcOptions, null); } MonitorThread(final String pName, final MongoClient pMongo, final DistributedLockSvcOptions pSvcOptions, final Map<String, DistributedLock> pLocks) { super(pName); _mongo = pMongo; _svcOptions = pSvcOptions; _locks = pLocks; _shutdown = new CountDownLatch(1); _exited = new CountDownLatch(1); setDaemon(true); } @Override public void run() { boolean shutdown = false; try { while (!shutdown) { try { shutdown = monitor(); } catch (final InterruptedException ie) { break; } catch (final Throwable t) { LOG.log(Level.SEVERE, t.getMessage(), t); } } } finally { _exited.countDown(); } } /** * Performs check and awaits shutdown signal for configured amount of milliseconds * @return true if shutdown() was called, false otherwise. */ abstract boolean monitor() throws InterruptedException; void shutdown() throws InterruptedException { _shutdown.countDown(); if (!_exited.await(10000, TimeUnit.MILLISECONDS)) { this.interrupt(); } } final MongoClient _mongo; final DistributedLockSvcOptions _svcOptions; final Map<String, DistributedLock> _locks; final CountDownLatch _shutdown; final CountDownLatch _exited; } private static final Logger LOG = Logger.getLogger("com.deftlabs.lock.mongo.Monitor"); } <file_sep>/** * Copyright 2011, Deft Labs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deftlabs.lock.mongo.impl; /** * The distributed lock history fields. See LockDef for more info. * * The fields in LockDef need to be represented here. */ enum LockHistoryDef { ID("_id"), // This is an object id in history LIBRARY_VERSION("libraryVersion"), STATE("lockState"), LOCK_ID("lockId"), OWNER_APP_NAME("appName"), OWNER_ADDRESS("ownerAddress"), OWNER_HOSTNAME("ownerHostname"), OWNER_THREAD_ID("ownerThreadId"), OWNER_THREAD_NAME("ownerThreadName"), OWNER_THREAD_GROUP_NAME("ownerThreadGroupName"), INACTIVE_LOCK_TIMEOUT("inactiveLockTimeout"), // Fields on top of LockDef CREATED("historyCreated"), LOCK_NAME("lockName"), TIMED_OUT("timedOut"); private LockHistoryDef(final String pField) { field = pField; } final String field; } <file_sep><?xml version="1.0"?> <!-- Copyright 2011, <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project name="mongo-java-distributed-lock" default="usage" basedir="./" xmlns:aspectj="antlib:org.aspectj" xmlns:artifact="antlib:org.apache.maven.artifact.ant"> <!-- ******************************************************************* --> <!-- Set the base attributes. --> <!-- ******************************************************************* --> <property name="dir.build" value="build"/> <property name="dir.build.java" value="${dir.build}/java/classes"/> <property name="dir.build.release" value="${dir.build}/mongo-java-distributed-lock"/> <property name="dir.src" value="src"/> <property name="dir.src.java" value="src/main"/> <property name="dir.src.java.unit" value="src/unit"/> <property name="dir.src.java.test" value="src/test"/> <property name="dir.lib" value="lib"/> <property name="dir.conf" value="conf"/> <property file="build.properties" prefix="build.conf"/> <property environment="env"/> <path id="classpath.all"> <fileset dir="${dir.lib}"><include name="*.jar"/></fileset> </path> <path id="classpath.cp"><pathelement location="${dir.build.java}"/></path> <!-- ******************************************************************* --> <!-- Set the Maven attributes. --> <!-- ******************************************************************* --> <property name="groupId" value="com.deftlabs"/> <property name="artifactId" value="mongo-java-distributed-lock"/> <property name="maven-snapshots-repository-id" value="sonatype-nexus-snapshots-deftlabs"/> <property name="maven-snapshots-repository-url" value="https://oss.sonatype.org/content/repositories/snapshots"/> <property name="maven-staging-repository-id" value="sonatype-nexus-staging-deftlabs"/> <property name="maven-staging-repository-url" value="https://oss.sonatype.org/service/local/staging/deploy/maven2/"/> <!-- ******************************************************************* --> <!-- Remove the build directory. --> <!-- ******************************************************************* --> <target name="clean"> <delete dir="${dir.build}"/> <delete file="conf/maven-mongo-java-distributed-lock.xml.asc"/> </target> <!-- ******************************************************************* --> <!-- Compile the java classes. --> <!-- ******************************************************************* --> <target name="compile"> <mkdir dir="${dir.build.java}"/> <javac destdir="${dir.build.java}" target="${build.conf.javac.source}" debug="true" encoding="UTF-8" classpathref="classpath.cp" source="${build.conf.javac.source}" includeantruntime="false" debuglevel="lines,vars,source"> <src path="${dir.src.java}"/> <src path="${dir.src.java.unit}"/> <src path="${dir.src.java.test}"/> <compilerarg value="-Xlint:all,-fallthrough"/> <classpath refid="classpath.all"/> </javac> </target> <!-- ******************************************************************* --> <!-- Create the jar file. --> <!-- ******************************************************************* --> <target name="jar" depends="clean, unit, compile"> <mkdir dir="${dir.build}/dist"/> <!-- Set the lib version in the class --> <mkdir dir="${dir.build}/tmp"/> <copy file="src/main/com/deftlabs/lock/mongo/DistributedLockSvcOptions.java" tofile="${dir.build}/tmp/DistributedLockSvcOptions.java" filtering="true"> <filterset><filter token="LIB_VERSION" value="${build.conf.lib.version}"/></filterset> </copy> <javac destdir="${dir.build.java}" target="${build.conf.javac.source}" debug="true" encoding="UTF-8" classpathref="classpath.cp" source="${build.conf.javac.source}" includeantruntime="false" debuglevel="lines,vars,source"> <src path="${dir.build}/tmp"/> <compilerarg value="-Xlint:all,-fallthrough"/> <classpath refid="classpath.all"/> </javac> <copy file="src/main/META-INF/MANIFEST.MF" tofile="${dir.build}/MANIFEST.MF" filtering="true"> <filterset><filter token="VERSION" value="${build.conf.lib.version}"/></filterset> </copy> <jar destfile="${dir.build}/dist/mongo-java-distributed-lock.jar" basedir="${dir.build.java}" manifest="${dir.build}/MANIFEST.MF"></jar> <copy file="conf/maven-mongo-java-distributed-lock.xml" tofile="${dir.build}/maven-mongo-java-distributed-lock.xml" filtering="true"> <filterset><filter token="VERSION" value="${build.conf.lib.version}"/></filterset> </copy> </target> <!-- ******************************************************************* --> <!-- Create the additional jars. --> <!-- ******************************************************************* --> <target name="jar.all" depends="jar, javadocs"> <jar jarfile="${dir.build}/dist/mongo-java-distributed-lock-sources-${build.conf.lib.version}.jar"><fileset dir="src/main"/></jar> <jar jarfile="${dir.build}/dist/mongo-java-distributed-lock-javadoc-${build.conf.lib.version}.jar"><fileset dir="${dir.build}/javadocs"/></jar> <copy file="${dir.build}/dist/mongo-java-distributed-lock.jar" tofile="${dir.build}/dist/mongo-java-distributed-lock-${build.conf.lib.version}.jar"/> </target> <!-- ******************************************************************* --> <!-- Run the isolated unit tests. --> <!-- ******************************************************************* --> <target name="unit" depends="compile"> <junit fork="yes" haltonfailure="true"> <jvmarg value="-Duser.timezone=GMT"/> <jvmarg value="-Dfile.encoding=UTF-8"/> <classpath refid="classpath.all"/> <classpath> <pathelement path="${dir.build.java}"/> <pathelement path="${dir.conf}"/> </classpath> <formatter type="brief" usefile="false"/> <batchtest todir="."> <fileset dir="${dir.build.java}"> <include name="**/*UnitTests.class"/> </fileset> </batchtest> </junit> </target> <!-- ******************************************************************* --> <!-- Run the integration tests. Server must be running to work. --> <!-- ******************************************************************* --> <target name="test" depends="unit"> <junit fork="yes" haltonfailure="true"> <jvmarg value="-Duser.timezone=GMT"/> <jvmarg value="-Dfile.encoding=UTF-8"/> <jvmarg value="-DsocksProxyHost"/> <jvmarg value="-DsocksProxtPort"/> <jvmarg value="-Dhttps.proxyHost"/> <jvmarg value="-Dhttp.proxyHost"/> <classpath refid="classpath.all"/> <classpath> <pathelement path="${dir.build.java}"/> <pathelement path="${dir.conf}"/> </classpath> <formatter type="brief" usefile="false"/> <batchtest todir="."> <fileset dir="${dir.build.java}"> <include name="**/*IntTests.class"/> </fileset> </batchtest> </junit> </target> <!-- ******************************************************************* --> <!-- Run the standalone threaded tests. Server must be running to work. --> <!-- ******************************************************************* --> <target name="test-thread" depends="compile"> <java classname="com.deftlabs.lock.mongo.StandaloneThreadLockTests"> <arg value="-Duser.timezone=GMT"/> <arg value="-Dfile.encoding=UTF-8"/> <classpath refid="classpath.all"/> <classpath> <pathelement path="${dir.build.java}"/> <pathelement path="${dir.conf}"/> </classpath> </java> </target> <!-- ******************************************************************* --> <!-- Generate the Javadocs. --> <!-- ******************************************************************* --> <target name="javadocs" depends="compile" description="Generate Javadocs"> <delete dir="${dir.build}/javadocs/"/> <javadoc packagenames="com.deftlabs.lock.mongo" excludepackagenames="com.deftlabs.lock.mongo.impl" sourcepath="src/main/" defaultexcludes="yes" destdir="${dir.build}/javadocs" author="true" version="true" source="1.5" use="true" access="protected"> <link href="http://download.oracle.com/javase/1.5.0/docs/api/" /> <classpath refid="classpath.all"/> </javadoc> </target> <!-- ******************************************************************* --> <!-- Deploy to Maven repository. --> <!-- ******************************************************************* --> <target name="maven.snapshot" depends="jar.all" description="Deploy a snapshot version to Maven snapshot repository"> <artifact:mvn> <arg value="org.apache.maven.plugins:maven-deploy-plugin:2.6:deploy-file"/> <arg value="-Durl=${maven-snapshots-repository-url}"/> <arg value="-DrepositoryId=${maven-snapshots-repository-id}"/> <arg value="-DpomFile=${dir.build}/maven-mongo-java-distributed-lock.xml"/> <arg value="-Dfile=${dir.build}/dist/mongo-java-distributed-lock-${build.conf.lib.version}.jar"/> </artifact:mvn> </target> <!-- ******************************************************************* --> <!-- Stage in the Maven repository. --> <!-- ******************************************************************* --> <target name="maven.stage" depends="jar.all" description="Deploy release version to Maven staging repository"> <artifact:mvn> <arg value="org.apache.maven.plugins:maven-gpg-plugin:1.3:sign-and-deploy-file"/> <arg value="-Durl=${maven-staging-repository-url}"/> <arg value="-DrepositoryId=${maven-staging-repository-id}"/> <arg value="-DpomFile=${dir.build}/maven-mongo-java-distributed-lock.xml"/> <arg value="-Dfile=${dir.build}/dist/mongo-java-distributed-lock-${build.conf.lib.version}.jar"/> <arg value="-Dkeyname=665C1184"/> <arg value="-Pgpg-deftlabs"/> </artifact:mvn> <artifact:mvn> <arg value="org.apache.maven.plugins:maven-gpg-plugin:1.3:sign-and-deploy-file"/> <arg value="-Durl=${maven-staging-repository-url}"/> <arg value="-DrepositoryId=${maven-staging-repository-id}"/> <arg value="-DpomFile=${dir.build}/maven-mongo-java-distributed-lock.xml"/> <arg value="-Dfile=${dir.build}/dist/mongo-java-distributed-lock-sources-${build.conf.lib.version}.jar"/> <arg value="-Dclassifier=sources"/> <arg value="-Dkeyname=665C1184"/> <arg value="-Pgpg-deftlabs"/> </artifact:mvn> <artifact:mvn> <arg value="org.apache.maven.plugins:maven-gpg-plugin:1.3:sign-and-deploy-file"/> <arg value="-Durl=${maven-staging-repository-url}"/> <arg value="-DrepositoryId=${maven-staging-repository-id}"/> <arg value="-DpomFile=${dir.build}/maven-mongo-java-distributed-lock.xml"/> <arg value="-Dfile=${dir.build}/dist/mongo-java-distributed-lock-javadoc-${build.conf.lib.version}.jar"/> <arg value="-Dclassifier=javadoc"/> <arg value="-Dkeyname=665C1184"/> <arg value="-Pgpg-deftlabs"/> </artifact:mvn> </target> <!-- ******************************************************************* --> <!-- Describe the build file usage. --> <!-- ******************************************************************* --> <target name="usage"> <echo> ---------------------------------------- - Compile the Java files ......................... compile - Create the jar file ............................ jar - Create ALL of the build jar files .............. jar.all - Clean the source tree .......................... clean - Run the unit tests ............................. unit - Run the integration tests ...................... test - Generate the Javadocs .......................... javadocs ---------------------------------------- </echo> </target> <!-- ******************************************************************* --> </project> <file_sep>/** * Copyright 2011, <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deftlabs.lock.mongo; // Lib import com.deftlabs.lock.mongo.impl.SvcImpl; /** * The distrbuted lock service factory. */ public final class DistributedLockSvcFactory { public DistributedLockSvcFactory(final DistributedLockSvcOptions pOptions) { _options = pOptions; } /** * Returns the global lock service. This method also calls the startup method on the * lock service returned (when it is created). */ public DistributedLockSvc getLockSvc() { if (_lockSvc != null && _lockSvc.isRunning()) return _lockSvc; synchronized(_mutex) { if (_lockSvc != null && _lockSvc.isRunning()) return _lockSvc; final SvcImpl svc = new SvcImpl(_options); svc.startup(); _lockSvc = svc; return _lockSvc; } } private static volatile DistributedLockSvc _lockSvc = null; private final DistributedLockSvcOptions _options; private final static Object _mutex = new Object(); } <file_sep>/** * Copyright 2011, <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deftlabs.lock.mongo.impl; // Lib import com.deftlabs.lock.mongo.DistributedLock; import com.deftlabs.lock.mongo.DistributedLockOptions; import com.deftlabs.lock.mongo.DistributedLockSvcOptions; // Mongo import com.mongodb.Mongo; import com.mongodb.MongoClient; import org.bson.types.ObjectId; // Java import java.util.Queue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Condition; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.locks.LockSupport; /** * The distributed lock object. */ public class LockImpl implements DistributedLock { /** * Construct the object with params. */ LockImpl( final MongoClient pMongo, final String pName, final DistributedLockOptions pLockOptions, final DistributedLockSvcOptions pSvcOptions) { _mongo = pMongo; _name = pName; _lockOptions = pLockOptions; _svcOptions = pSvcOptions; } @Override public void lock() { if (tryDistributedLock()) return; park(); } /** * Park the current thread. This method will check to see (when allowed) to see * if it can get the distributed lock. */ private void park() { boolean wasInterrupted = false; final Thread current = Thread.currentThread(); _waitingThreads.add(current); // Block while not first in queue or cannot acquire lock while (_running.get()) { LockSupport.park(this); if (Thread.interrupted()) { wasInterrupted = true; break; } if (_waitingThreads.peek() == current && !isLocked()) { // Check to see if this thread can get the distributed lock if (tryDistributedLock()) break; } } if (wasInterrupted) current.interrupt(); else _waitingThreads.remove(); } /** * Park the current thread for a max amount of time. This method will check to see * (when allowed) to see if it can get the distributed lock. */ private boolean park(final long pNanos) { boolean wasInterrupted = false; final Thread current = Thread.currentThread(); _waitingThreads.add(current); boolean locked = false; long parkTime = pNanos; long startTime = System.nanoTime(); // Block while not first in queue or cannot acquire lock while (_running.get()) { parkTime = (pNanos - (System.nanoTime() - startTime)); if (parkTime <= 0) break; LockSupport.parkNanos(this, parkTime); if (Thread.interrupted()) { wasInterrupted = true; break; } if (_waitingThreads.peek() == current && !isLocked()) { // Check to see if this thread can get the distributed lock if (tryDistributedLock()) { locked = true; break; } } if ((System.nanoTime() - startTime) >= pNanos) break; } // TODO: There is a problem here... we need to be able to remove // the actual thread, not just the head. This is causing an issue // where we are removing other threads. if (wasInterrupted) { current.interrupt(); return locked; } else _waitingThreads.remove(); return locked; } /** * Try and lock the distributed lock. */ private boolean tryDistributedLock() { if (isLocked()) return false; final ObjectId lockId = LockDao.lock(_mongo, _name, _svcOptions, _lockOptions); if (lockId == null) return false; _locked.set(true); _lockId = lockId; return true; } /** * This is not supported. */ @Override public void lockInterruptibly() { throw new UnsupportedOperationException("not implemented"); } /** * For now, this is not supported. */ @Override public Condition newCondition() { throw new UnsupportedOperationException("not implemented"); } /** * Does not block. Returns right away if not able to lock. */ @Override public boolean tryLock() { return tryDistributedLock(); } @Override public boolean tryLock(final long pTime, final TimeUnit pTimeUnit) { if (tryDistributedLock()) return true; return park(pTimeUnit.toNanos(pTime)); } @Override public void unlock() { LockDao.unlock(_mongo, _name, _svcOptions, _lockOptions, _lockId); _locked.set(false); _lockId = null; LockSupport.unpark(_waitingThreads.peek()); } /** * Called to initialize the lock. */ synchronized void init() { if (_running.get()) throw new IllegalStateException("init already called"); _running.set(true); } /** * Called to destroy the lock. */ synchronized void destroy() { if (!_running.get()) throw new IllegalStateException("destroy already called"); _running.set(false); for (final Thread t : _waitingThreads) t.interrupt(); _waitingThreads.clear(); } /** * Returns true if the lock is currently locked. */ @Override public boolean isLocked() { return _locked.get(); } /** * Returns the lock name. */ @Override public String getName() { return _name; } @Override public ObjectId getLockId() { return _lockId; } /** * Returns the options used to configure this lock. */ @Override public DistributedLockOptions getOptions() { return _lockOptions; } /** * Wakeup any blocked threads. This should <b>ONLY</b> be used by the lock service, * not the user. */ @Override public void wakeupBlocked() { LockSupport.unpark(_waitingThreads.peek()); } private final String _name; private final MongoClient _mongo; private final DistributedLockOptions _lockOptions; private final DistributedLockSvcOptions _svcOptions; private volatile ObjectId _lockId; private final AtomicBoolean _locked = new AtomicBoolean(false); private final AtomicBoolean _running = new AtomicBoolean(false); private final Queue<Thread> _waitingThreads = new ConcurrentLinkedQueue<Thread>(); } <file_sep><project> <modelVersion>4.0.0</modelVersion> <groupId>com.deftlabs</groupId> <artifactId>mongo-java-distributed-lock</artifactId> <packaging>jar</packaging> <name>Mongo Java Distributed Lock</name> <version>0.1.7</version> <description>A distributed lock backed by MongoDB</description> <url>https://deftlabs.com</url> <licenses> <license> <name>The Apache Software License, Version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> <distribution>repo</distribution> </license> </licenses> <scm> <url>https://github.com/deftlabs</url> </scm> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>[3.2.0,)</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.4.0</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>com.google.code.maven-replacer-plugin</groupId> <artifactId>replacer</artifactId> <version>1.5.3</version> <executions> <execution> <phase>process-sources</phase> <goals> <goal>replace</goal> </goals> </execution> </executions> <configuration> <ignoreMissingFile>true</ignoreMissingFile> <file>src/main/java/com/deftlabs/lock/mongo/DistributedLockSvcOptions.java</file> <outputFile>src/main/java/com/deftlabs/lock/mongo/DistributedLockSvcOptions.java</outputFile> <regex>false</regex> <token>@LIB_VERSION@</token> <value>${project.version}</value> </configuration> </plugin> </plugins> </build> <developers> <developer> <name><NAME></name> <organization>Deft Labs</organization> </developer> </developers> </project> <file_sep>/** * Copyright 2012, Deft Labs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deftlabs.lock.mongo; // Mongo import com.mongodb.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; // JUnit // Java /** * Test assumptions about the java driver for mongo. */ public final class DriverIntTest { @Test public void testWriteConcerns() throws Exception { final BasicDBObject doc = new BasicDBObject("_id", "test"); getCollection().insert(doc, WriteConcern.UNACKNOWLEDGED); assertThatExceptionOfType(DuplicateKeyException.class) .isThrownBy(() -> getCollection().insert(doc, WriteConcern.ACKNOWLEDGED)); } @Test public void testFindAndModify() throws Exception { final BasicDBObject query = new BasicDBObject("_id", "test"); final BasicDBObject toSet = new BasicDBObject("locked", true); final BasicDBObject lockDoc = (BasicDBObject)getCollection().findAndModify(query, new BasicDBObject("_id", 1), null, false, new BasicDBObject("$set", toSet), false, false); assertThat(lockDoc).isNull(); } @Test public void testFindAndModifyWithDoc() throws Exception { final BasicDBObject insert = new BasicDBObject("_id", "test"); insert.put("locked", false); insert.put("lockId", "10"); getCollection().insert(insert, WriteConcern.ACKNOWLEDGED); final BasicDBObject query = new BasicDBObject("_id", "test"); query.put("locked", false); query.put("lockId", "10"); final BasicDBObject toSet = new BasicDBObject("locked", true); toSet.put("lockId", "20"); final BasicDBObject lockDoc = (BasicDBObject)getCollection().findAndModify(query, new BasicDBObject("lockId", 1), null, false, new BasicDBObject("$set", toSet), true, false); assertThat(lockDoc).isNotNull(); assertThat(lockDoc.getString("lockId")).isEqualTo("20"); } @Test public void testFindAndModifyWithDocMiss() throws Exception { final BasicDBObject insert = new BasicDBObject("_id", "test"); insert.put("locked", false); insert.put("lockId", "10"); getCollection().insert(insert, WriteConcern.ACKNOWLEDGED); final BasicDBObject query = new BasicDBObject("_id", "test"); query.put("locked", false); query.put("lockId", "20"); final BasicDBObject toSet = new BasicDBObject("locked", true); toSet.put("lockId", "20"); final BasicDBObject lockDoc = (BasicDBObject)getCollection().findAndModify(query, new BasicDBObject("lockId", 1), null, false, new BasicDBObject("$set", toSet), true, false); assertThat(lockDoc).isNull(); } @Before public void init() throws Exception { getDb().dropDatabase(); } @After public void cleanup() { getDb().dropDatabase(); } private DBCollection getCollection() { return getDb().getCollection("test"); } private DB getDb() { return _mongo.getDB("mongo-distributed-lock-test"); } public DriverIntTest() throws Exception { _mongo = new MongoClient(new MongoClientURI("mongodb://127.0.0.1:27017")); } private final MongoClient _mongo; } <file_sep>/** * Copyright 2011, <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deftlabs.lock.mongo; /** * The distributed lock service interface. */ public interface DistributedLockSvc { /** * Create a new distributed lock. If a lock already exists with this name, * the lock will be returned (else a new one is created). */ public DistributedLock create(final String pLockName); /** * Create a new distributed lock. If a lock already exists with this name, * the lock will be returned (else a new one is created). */ public DistributedLock create(final String pLockName, final DistributedLockOptions pOptions); /** * Destroy a distributed lock. */ public void destroy(final DistributedLock pLock); /** * Part of the usage contract. The startup method is called by the factory. */ public void startup(); /** * Part of the usage contract. Must be called when the app stops. */ public void shutdown(); /** * Returns true if the lock service is running. */ public boolean isRunning(); } <file_sep>/** * Copyright 2011, Deft Labs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deftlabs.lock.mongo; // Mongo import com.mongodb.*; import com.mongodb.client.MongoCollection; import org.bson.Document; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; // JUnit // Java /** * The standalone threaded lock tests. */ public final class StandaloneThreadLockTests { private void test() throws Exception { final CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT); final AtomicBoolean locked = new AtomicBoolean(false); final DistributedLockSvc lockSvc = createSimpleLockSvc(); try { for (int idx=0; idx < THREAD_COUNT; idx++) { new Thread(new LockTest(countDownLatch, lockSvc, locked)).start(); } countDownLatch.await(); } finally { lockSvc.shutdown(); } } private DistributedLockSvc createSimpleLockSvc() { final DistributedLockSvcOptions options = new DistributedLockSvcOptions("mongodb://127.0.0.1:27017"); options.setEnableHistory(false); final DistributedLockSvcFactory factory = new DistributedLockSvcFactory(options); return factory.getLockSvc(); } private static class LockTest implements Runnable { private LockTest( final CountDownLatch pCountDownLatch, final DistributedLockSvc pLockSvc, final AtomicBoolean pLocked) { _countDownLatch = pCountDownLatch; _lockSvc = pLockSvc; _locked = pLocked; } @Override public void run() { final DistributedLock lock = _lockSvc.create("com.deftlabs.lock.mongo.testLock"); final long startTime = System.currentTimeMillis(); for (int idx = 0; idx < LOCK_TEST_COUNT; idx++) { try { lock.lock(); if (!_locked.compareAndSet(false, true)) throw new IllegalStateException("Already locked"); } finally { if (!_locked.compareAndSet(true, false)) throw new IllegalStateException("Already unlocked"); lock.unlock(); } } final long execTime = System.currentTimeMillis() - startTime; _countDownLatch.countDown(); } private final DistributedLockSvc _lockSvc; private final CountDownLatch _countDownLatch; private final AtomicBoolean _locked; } private DBCollection getCollection() { return _mongo.getDB("mongo-distributed-lock").getCollection("locks"); } private DBCollection getHistoryCollection() { return _mongo.getDB("mongo-distributed-lock").getCollection("lockHistory"); } private StandaloneThreadLockTests() throws Exception { _mongo = new MongoClient(new MongoClientURI("mongodb://127.0.0.1:27017")); } private static final int THREAD_COUNT = 200; private static final int LOCK_TEST_COUNT = 50; public static void main(final String [] pArgs) throws Exception { final StandaloneThreadLockTests tests = new StandaloneThreadLockTests(); tests.test(); } private final MongoClient _mongo; } <file_sep>/** * Copyright 2011, <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deftlabs.lock.mongo.impl; /** * The distributed lock db data fields. */ enum LockDef { ID("_id"), // This is the lock name LIBRARY_VERSION("libraryVersion"), // A string with the java library version number UPDATED("lastUpdated"), LAST_HEARTBEAT("lastHeartbeat"), LOCK_ACQUIRED_TIME("lockAcquired"), // The time the lock was granted STATE("lockState"), // The current state of this lock LOCK_ID("lockId"), // The generated id is used to ensure multiple thread/processes don't step on each other OWNER_APP_NAME("appName"), // The name of the application who has the lock (optional) OWNER_ADDRESS("ownerAddress"), OWNER_HOSTNAME("ownerHostname"), OWNER_THREAD_ID("ownerThreadId"), OWNER_THREAD_NAME("ownerThreadName"), OWNER_THREAD_GROUP_NAME("ownerThreadGroupName"), INACTIVE_LOCK_TIMEOUT("inactiveLockTimeout"), // The number of ms before timeout (since last heartbeat) LOCK_TIMEOUT_TIME("lockTimeoutTime"), LOCK_ATTEMPT_COUNT("lockAttemptCount"); // The number of times another thread/process has requested this lock (since locked) LockDef(final String pField) { field = pField; } final String field; }
41141e5a1191d8c43b59ddf14e2f34b53f57f170
[ "Markdown", "Java", "Maven POM", "Ant Build System" ]
11
Markdown
chandon/mongo-java-distributed-lock
6e3827c8cba86846b87ed8583d17c22c8fcc9430
0045571398b423a1ede67301d2013a76dc79c39d
refs/heads/master
<file_sep>const { src, dest, parallel, watch } = require('gulp'); const concat = require('gulp-concat'); const minify = require('gulp-minify'); const rename = require('gulp-rename'); const sass = require('gulp-sass'); const replace = require('gulp-replace'); const regex = /^(import|export).*;{1}$/gm; function jsBuild(){ return src(['./node_modules/pasoon-calendar-view/src/*.js', './src/*.js'], {base:'./'}) .pipe(concat('date-picker.js')) .pipe(replace(regex, '')) .pipe(dest('dist')) }; function jsMinify(){ return src(['./node_modules/pasoon-calendar-view/src/*.js', './src/*.js'], {base:'./'}) .pipe(concat('date-picker.js')) .pipe(replace(regex, '')) .pipe(minify()) .pipe(dest('dist')) .pipe(rename('calendar-view.min.js')) }; function sassBuild() { return src('./src/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(dest('./dist')); }; function sassMinify() { return src('./src/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(dest('./dist')); }; exports.default = parallel(sassMinify, jsMinify); exports.minify = parallel(sassMinify, jsMinify); exports.build = parallel(sassBuild, jsBuild); exports.watch = function () { watch('./src/**/*.*', parallel(sassBuild, jsBuild)); };<file_sep> const CalendarView = (($) => { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ const NAME = 'calendarView' const VERSION = '1.1.2' const DATA_KEY = 'bs.calendar-view' const EVENT_KEY = `.${DATA_KEY}` const DATA_API_KEY = '.data-api' const JQUERY_NO_CONFLICT = $.fn[NAME] const Event = { CHANGE: `change${EVENT_KEY}`, CLICK_DATA_API: `click${EVENT_KEY}${DATA_API_KEY}`, OVER_DATA_API: `mouseenter${EVENT_KEY}${DATA_API_KEY}`, SELECT: `select${EVENT_KEY}`, OVER: `over${EVENT_KEY}` } const ClassName = { CALENDAR_VIEW: 'calendar-view', MONTH_VIEW: 'calendar-month-view', WEEK_VIEW: 'calendar-week-view', DAY_VIEW: 'calendar-day-view', DAY_VIEW_TODAY: 'calendar-day-view-today', DAY_VIEW_INFOCUS: 'calendar-day-view-infocus', DAY_VIEW_OUTFOCUS: 'calendar-day-view-outfocus', DAY_VIEW_SELECTED: 'calendar-day-view-selected', DAY_VIEW_START: 'calendar-day-view-start', DAY_VIEW_END: 'calendar-day-view-end', DAY_VIEW_BETWEEN: 'calendar-day-view-between', DAY_VIEW_DISABLED: 'calendar-day-view-disabled', } const Selector = { CALENDAR_VIEW: `.${ClassName.CALENDAR_VIEW}`, MONTH_VIEW: `.${ClassName.MONTH_VIEW}`, DAY_VIEW: `.${ClassName.DAY_VIEW}` } /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ class CalendarView { constructor(element) { this._element = element; this._calendar = 'jalali'; this._current = Pasoonate.make()[this._calendar](); this._weekViewElement = '<tr>'; this._dayViewElement = '<td>'; this.beforeRenderDayAction = (date) => { return date.getDay(); }; this.render(); $(this._element).trigger($.Event(Event.CHANGE, { current: Pasoonate.make(this._current.getTimestamp())[this._calendar]() })); } // Public render() { this._goto(); } beforeRenderDay([action]) { if(typeof action === 'function') { this.beforeRenderDayAction = action; this._renderMonthView(); } } weekViewElement([element]) { if(typeof element === 'function') { this._weekViewElement = element(); } else { this._weekViewElement = element; } } dayViewElement([element]) { if(typeof element === 'function') { this._dayViewElement = element(); } else { this._dayViewElement = element; } } goto([year, month, day]) { this._goto(year, month, day); } nextMonth() { let date = Pasoonate.make(this._current.getTimestamp())[this._calendar](); date.addMonth(1); this._goto(date.getYear(), date.getMonth()); } prevMonth() { let date = Pasoonate.make(this._current.getTimestamp())[this._calendar](); date.subMonth(1); this._goto(date.getYear(), date.getMonth()); } selectDay([date]) { $(this._element) .find(`${Selector.DAY_VIEW}[data-gregorian-date=${date}]`) .addClass(ClassName.DAY_VIEW_SELECTED); } clearSelection([date]) { if(date) { $(this._element).find(`${Selector.DAY_VIEW}[data-gregorian-date=${date}]`).removeClass(ClassName.DAY_VIEW_SELECTED); } else { $(this._element).find(Selector.DAY_VIEW).removeClass(ClassName.DAY_VIEW_SELECTED); } } selectRange([start, end]) { const [startYear, startMonth, startDay] = String(start).split('-'); const day = Pasoonate.make().gregorian().setDate(Number(startYear), Number(startMonth), Number(startDay)); $(this._element) .find(`${Selector.DAY_VIEW}[data-gregorian-date=${start}]`) .addClass(ClassName.DAY_VIEW_START); $(this._element) .find(`${Selector.DAY_VIEW}[data-gregorian-date=${end}]`) .addClass(ClassName.DAY_VIEW_END); day.addDay(1); while(day.format('yyyy-MM-dd') !== end) { $(this._element) .find(`${Selector.DAY_VIEW}[data-gregorian-date=${day.format('yyyy-MM-dd')}]`) .addClass(ClassName.DAY_VIEW_BETWEEN); day.addDay(1); } } clearRange() { $(this._element) .find(Selector.DAY_VIEW) .removeClass([ClassName.DAY_VIEW_START, ClassName.DAY_VIEW_END, ClassName.DAY_VIEW_BETWEEN]); } startDay([date]) { $(this._element) .find(`${Selector.DAY_VIEW}[data-gregorian-date=${date}]`) .addClass(ClassName.DAY_VIEW_START); } endDay([date]) { $(this._element) .find(`${Selector.DAY_VIEW}[data-gregorian-date=${date}]`) .addClass(ClassName.DAY_VIEW_END); } disableDay([date]) { $(this._element) .find(`${Selector.DAY_VIEW}[data-gregorian-date=${date}]`) .addClass(ClassName.DAY_VIEW_DISABLED); } enableDay([date]) { $(this._element) .find(`${Selector.DAY_VIEW}[data-gregorian-date=${date}]`) .removeClass(ClassName.DAY_VIEW_DISABLED); } addClass([date, className]) { $(this._element) .find(`${Selector.DAY_VIEW}[data-gregorian-date=${date}]`) .addClass(className); } removeClass([date, className]) { $(this._element) .find(`${Selector.DAY_VIEW}[data-gregorian-date=${date}]`) .removeClass(className); } hasClass([date, className, has]) { has.value = $(this._element) .find(`${Selector.DAY_VIEW}[data-gregorian-date=${date}]`) .hasClass(className); } getFirstAndLastDay([range]) { const $days = $(this._element).find(`${Selector.DAY_VIEW}`); if($days.length) { range.first = Number($days[0].dataset['pick']); range.last = Number($days[$days.length - 1].dataset['pick']); } } // Private _renderMonthView() { let $monthView = $(this._element).find(Selector.MONTH_VIEW); let firstOfMonth = Pasoonate.make()[this._calendar](); let firstOfWeek; $monthView.empty(); firstOfMonth.setTimestamp(this._current.getTimestamp()).setDay(1); firstOfWeek = firstOfMonth.subDay(firstOfMonth.dayOfWeek()); for(let i = 1; i <= 6; i++) { $monthView.append(this._renderWeekView(firstOfWeek, i)); firstOfWeek.addDay(7); } } _renderWeekView(from, week) { let $week = $(this._weekViewElement); let day = Pasoonate.make(from.getTimestamp())[this._calendar](); $week.addClass(ClassName.WEEK_VIEW).addClass('week-' + week); for(let i = 0; i < 7; i++) { $week.append(this._renderDayView(day)); day.addDay(1); } return $week; } _renderDayView(day) { let content = this.beforeRenderDayAction(day); let $day = $(this._dayViewElement); let today = Pasoonate.make()[this._calendar](); $day.addClass(ClassName.DAY_VIEW); $day.attr('data-pick', day.getTimestamp()); $day.attr('data-gregorian-date', Pasoonate.make(day.getTimestamp()).gregorian().format('yyyy-MM-dd')); if(day.getMonth() === this._current.getMonth()) { $day.attr('data-day', day.getDay()); $day.addClass(ClassName.DAY_VIEW_INFOCUS); } else { $day.addClass(ClassName.DAY_VIEW_OUTFOCUS); } if(day.format('yyyy-MM-dd') === today.format('yyyy-MM-dd')) { $day.addClass(ClassName.DAY_VIEW_TODAY); } $day.html(content); return $day; } _goto(year, month, day) { let old = Pasoonate.make(this._current.getTimestamp())[this._calendar](); let isChange = false; isChange = (year && year != this._current.getYear()) | (month && month != this._current.getMonth()) | (day && day != this._current.getDay()); if(isChange) { let newYear = parseInt(year) || this._current.getYear(); let newMonth = parseInt(month) || this._current.getMonth(); let newDay = parseInt(day) || this._current.getDay(); if(this._current._currentCalendar.daysInMonth(newYear, newMonth) < newDay) { newDay = this._current._currentCalendar.daysInMonth(newYear, newMonth); } this._current[this._calendar](`${newYear}/${newMonth}/${newDay}`); const changeEvent = $.Event(Event.CHANGE, { old: old, current: Pasoonate.make(this._current.getTimestamp())[this._calendar]() }) $(this._element).trigger(changeEvent); if (changeEvent.isDefaultPrevented()) { this._current.setTimestamp(old.getTimestamp()); return; } } this._renderMonthView(); } // Static static _jQueryInterface(method, ...args) { return this.each(function () { const $this = $(this); let data = $this.data(DATA_KEY); if (!data) { data = new CalendarView(this); $this.data(DATA_KEY, data); } if (typeof method === 'string') { if (typeof data[method] === 'undefined') { throw new TypeError(`No method named "${method}"`); } data[method](args); } }) } } /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(document) .on(Event.CLICK_DATA_API, `${Selector.DAY_VIEW}:not(${Selector.DAY_VIEW_DISABLED})`, function () { $(this) .closest(Selector.CALENDAR_VIEW) .trigger( $.Event(Event.SELECT, { relatedTarget: this }) ); }) .on(Event.OVER_DATA_API, `${Selector.DAY_VIEW}:not(${Selector.DAY_VIEW_DISABLED})`, function () { $(this) .closest(Selector.CALENDAR_VIEW) .trigger( $.Event(Event.OVER, { relatedTarget: this }) ); }) /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = CalendarView._jQueryInterface; $.fn[NAME].Constructor = CalendarView; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return CalendarView._jQueryInterface; } return CalendarView; })($); const DatePicker = (($) => { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ const NAME = 'datePicker'; const VERSION = '1.5.1'; const DATA_KEY = 'bs.date-picker'; const EVENT_KEY = `.${DATA_KEY}`; const DATA_API_KEY = '.data-api'; const JQUERY_NO_CONFLICT = $.fn[NAME]; const Event = { HIDE: `hide${EVENT_KEY}`, HIDDEN: `hidden${EVENT_KEY}`, SHOW: `show${EVENT_KEY}`, SHOWN: `shown${EVENT_KEY}`, FOCUS_CHANGE: `focus-change${EVENT_KEY}`, MONTH_CHANGE: `month-change${EVENT_KEY}`, CHANGE: `change${EVENT_KEY}`, CLICK_DATA_API: `click${EVENT_KEY}${DATA_API_KEY}`, OVER_DATA_API: `mouseover${EVENT_KEY}${DATA_API_KEY}`, }; const ClassName = { DATE_PICKER: 'date-picker', DISABLED: 'disabled', FADE: 'fade', SHOW: 'show', DAY_NUMBER: 'date-picker-day-number', DAY_DISABLED: 'date-picker-day-disabled', DAY_START: 'date-picker-day-start', DAY_END: 'date-picker-day-end', DAY_BETWEEN: 'date-picker-day-between', BTN_NEXT_MONTH: 'date-picker-btn-next-month', BTN_PREV_MONTH: 'date-picker-btn-prev-month', YEAR_MONTH: 'date-picker-year-month', LOCK_DAY: 'calendar-day-view-lock', SELECTABLE_DAY: 'calendar-day-view-selectable', }; const Selector = { DATE_PICKER: '.date-picker', INPUT: 'input[type=date]', DISABLED: '.disabled', DATA_TOGGLE: '[data-toggle="date-picker"]', DAY_NUMBER: '.date-picker-day-number', BTN_NEXT_MONTH: '.date-picker-btn-next-month', BTN_PREV_MONTH: '.date-picker-btn-prev-month', YEAR_MONTH: '.date-picker-year-month', CALENDAR_VIEW: '.calendar-view', NOTICE: '.date-picker-notice', INPUT_CHECKIN: '.date-picker-header #datePickerInputCheckin', INPUT_CHECKOUT: '.date-picker-header #datePickerInputCheckout', BTN_CLOSE: '.date-picker-header .date-picker-close' }; class DatePicker { constructor(element) { this._element = element; this._parent = element.parentNode; this._options = {}; this._startDay = null; this._endDay = null; this._focusOn = 'start'; this._render(); } // Public show() { if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && $(this._element).hasClass(ClassName.DISABLED)) { return; } const datePicker = $(this._element.parentNode).find(Selector.DATE_PICKER)[0]; const showEvent = $.Event(Event.SHOW, { relatedTarget: this._element }); $(this._element).trigger(showEvent); if (showEvent.isDefaultPrevented()) { return; } const complete = () => { const shownEvent = $.Event(Event.SHOWN, { relatedTarget: this._element }) $(this._element).trigger(shownEvent) }; $(datePicker).addClass(ClassName.SHOW); complete(); } hide() { if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && $(this._element).hasClass(ClassName.DISABLED)) { return; } const datePicker = $(this._element.parentNode).find(Selector.DATE_PICKER)[0]; const hideEvent = $.Event(Event.HIDE, { relatedTarget: this._element }); $(this._element).trigger(hideEvent); if (hideEvent.isDefaultPrevented()) { return; } const complete = () => { const hiddenEvent = $.Event(Event.HIDDEN, { relatedTarget: this._element }) $(this._element).trigger(hiddenEvent) }; $(datePicker).removeClass(ClassName.SHOW); complete(); } toggle() { if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && $(this._element).hasClass(ClassName.DISABLED)) { return; } const datePicker = $(this._element.parentNode).find(Selector.DATE_PICKER)[0]; if($(datePicker).hasClass(ClassName.SHOW)) { this.hide(); } else { this.show(); } } dispose() { $.removeData(this._element, DATA_KEY) this._element = null } clear() { this._startDay = null; this._endDay = null; this._focusOn = 'start'; $(this._element).parent().find(Selector.CALENDAR_VIEW).calendarView('clearRange'); this._unlockCurrentDays(); this._lockDays(this._options.lockBefore, this._options.lockAfter); $(this._parent).find(Selector.INPUT_CHECKIN).removeClass('focus').html('ورود'); $(this._parent).find(Selector.INPUT_CHECKOUT).removeClass('focus').html('خروج'); const changeEvent = $.Event(Event.CHANGE, { startDay: this._startDay, endDay: this._endDay }); $(this._element).trigger(changeEvent); } options([options]) { options.data = this._updateDataOption(options.data); Object.assign(this._options, options); this.refresh(); } focusOn([type]) { $(this._parent).find(Selector.INPUT_CHECKIN).removeClass('focus'); $(this._parent).find(Selector.INPUT_CHECKOUT).removeClass('focus'); if(type === 'start') { this._focusOn = type; $(this._parent).find(Selector.INPUT_CHECKIN).addClass('focus'); } else if(type === 'end') { if(this._startDay === null) { this._focusOn = 'start'; $(this._parent).find(Selector.INPUT_CHECKIN).addClass('focus'); const focusChangeEvent = $.Event(Event.FOCUS_CHANGE, { relatedTarget: this._element, focusOn: this._focusOn }); $(this._element).trigger(focusChangeEvent); } else { this._focusOn = type; $(this._parent).find(Selector.INPUT_CHECKOUT).addClass('focus'); } } } refresh() { const $calendarView = $(this._element.parentNode).find(Selector.CALENDAR_VIEW); const data = this._dataKeyByDay(); $calendarView.calendarView('render'); for(const date in data) { if(data[date].disabled) { $calendarView.calendarView('disableDay', date); } } this._assignSelectableDays(); this._unlockCurrentDays(); this._autoLockDays(); this._lockDays(this._options.lockBefore, this._options.lockAfter); $(this._parent).find(Selector.INPUT_CHECKIN).html('ورود'); $(this._parent).find(Selector.INPUT_CHECKOUT).html('خروج'); if(this._options.startDay) { this._startDay = this._options.startDay; this._options.startDay = undefined; } if(this._options.endDay) { this._endDay = this._options.endDay; this._options.endDay = undefined; } if(this._startDay) { $calendarView.calendarView('startDay', this._startDay); $(this._parent).find(Selector.INPUT_CHECKIN).html(Pasoonate.make().gregorian(this._startDay).jalali().format('yyyy/MM/dd')); } if(this._endDay) { $calendarView.calendarView('endDay', this._endDay); $(this._parent).find(Selector.INPUT_CHECKOUT).html(Pasoonate.make().gregorian(this._endDay).jalali().format('yyyy/MM/dd')); } if(this._startDay && this._endDay) { $calendarView.calendarView('clearRange'); $calendarView.calendarView('selectRange', this._startDay, this._endDay); } $calendarView.find(Selector.NOTICE).empty(); if(this._options.notice) { $calendarView.find(Selector.NOTICE).html(this._options.notice); } } nextMonth() { const $calendarView = $(this._element.parentNode).find(Selector.CALENDAR_VIEW); const data = this._dataKeyByDay(); $calendarView.calendarView('nextMonth'); for(const date in data) { if(data[date].disabled) { $calendarView.calendarView('disableDay', date); } } if(this._startDay) { $calendarView.calendarView('startDay', this._startDay); } if(this._endDay) { $calendarView.calendarView('endDay', this._endDay); } if(this._startDay && this._endDay) { $calendarView.calendarView('clearRange'); $calendarView.calendarView('selectRange', this._startDay, this._endDay); } this._assignSelectableDays(); this._unlockCurrentDays(); this._autoLockDays(); this._lockDays(this._options.lockBefore, this._options.lockAfter); //#region Month Change Event let monthRange = {}; $calendarView.calendarView('getFirstAndLastDay', monthRange); const firstDay = Pasoonate.make(monthRange.first); const lastDay = Pasoonate.make(monthRange.last); const newMonth = Pasoonate.make(monthRange.first).jalali().addDay(15).getMonth(); const oldMonth = Pasoonate.make(monthRange.first).jalali().addDay(15).subMonth(1).getMonth(); const monthChangeEvent = $.Event(Event.MONTH_CHANGE, { relatedTarget: this._element, newMonth: newMonth, oldMonth: oldMonth, firstDay: firstDay.gregorian().format('yyyy-MM-dd'), lastDay: lastDay.gregorian().format('yyyy-MM-dd') }); $(this._element).trigger(monthChangeEvent); //#endregion } prevMonth() { const $calendarView = $(this._element.parentNode).find(Selector.CALENDAR_VIEW); const data = this._dataKeyByDay(); $calendarView.calendarView('prevMonth'); for(const date in data) { if(data[date].disabled) { $calendarView.calendarView('disableDay', date); } } if(this._startDay) { $calendarView.calendarView('startDay', this._startDay); } if(this._endDay) { $calendarView.calendarView('endDay', this._endDay); } if(this._startDay && this._endDay) { $calendarView.calendarView('clearRange'); $calendarView.calendarView('selectRange', this._startDay, this._endDay); } this._assignSelectableDays(); this._unlockCurrentDays(); this._autoLockDays(); this._lockDays(this._options.lockBefore, this._options.lockAfter); //#region Month Change Event let monthRange = {}; $calendarView.calendarView('getFirstAndLastDay', monthRange); const firstDay = Pasoonate.make(monthRange.first); const lastDay = Pasoonate.make(monthRange.last); const newMonth = Pasoonate.make(monthRange.first).jalali().addDay(15).getMonth(); const oldMonth = Pasoonate.make(monthRange.first).jalali().addDay(15).addMonth(1).getMonth(); const monthChangeEvent = $.Event(Event.MONTH_CHANGE, { relatedTarget: this._element, newMonth: newMonth, oldMonth: oldMonth, firstDay: firstDay.gregorian().format('yyyy-MM-dd'), lastDay: lastDay.gregorian().format('yyyy-MM-dd') }); $(this._element).trigger(monthChangeEvent); //#endregion } // Private _render() { if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && ($(this._element).hasClass(ClassName.DISABLED) || this._element.hasAttribute('disabled'))) { return; } let target = this._element; let parent = target.parentNode; let $picker = $(`<div class="${ClassName.DATE_PICKER}">`); let $calendarView = $('<div class="calendar-view">'); let $calendarHeader = $('<header>'); let $calendarBody = $('<div class="calendar-month-view">'); let $calendarFooter = $('<footer>'); let $pickerHeader = $('<div class="date-picker-header">'); $pickerHeader.append( $('<div class="date-picker-title-bar">').html( '<span>تاریخ ورود و خروج</span>' + '<button type="button" class="btn date-picker-close"></button>' ) ); $pickerHeader.append( $('<div class="date-picker-inputs">').html( '<div class="form-control" id="datePickerInputCheckin" >ورود</div>' + '<span>-</span>' + '<div class="form-control" id="datePickerInputCheckout">خروج</div>' ) ); $calendarHeader.append( $('<div class="calendar-nav">').html( `<div class="col-auto px-1"><button type="button" class="btn btn-link btn-sm ${ClassName.BTN_PREV_MONTH}"><i class="arrow-right"></i></button></div>`+ `<div class="col"><span class="${ClassName.YEAR_MONTH}"></span></div>`+ `<div class="col-auto px-1"><button type="button" class="btn btn-link btn-sm ${ClassName.BTN_NEXT_MONTH}"><i class="arrow-left"></i></button></div>` ) ); $calendarHeader.append( $('<div class="calendar-weekdays">').html( '<div class="calendar-weekday">ش</div>' + '<div class="calendar-weekday">ی</div>' + '<div class="calendar-weekday">د</div>' + '<div class="calendar-weekday">س</div>' + '<div class="calendar-weekday">چ</div>' + '<div class="calendar-weekday">پ</div>' + '<div class="calendar-weekday">ج</div>' ) ); $calendarFooter.html($('<div class="date-picker-notice">').html(this._options.notice || '')); $calendarFooter.append($('<button type="button" class="btn btn-sm btn-outline-secondary">').text('پاک کردن').click(() => { this.clear(); // this.hide(); })); $calendarView.append($calendarHeader).append($calendarBody).append($calendarFooter); $picker.append($pickerHeader).append($calendarView); $picker.data('target', target); $(parent).append($picker).css('position', 'relative'); $calendarView.calendarView('weekViewElement', '<div>'); $calendarView.calendarView('dayViewElement', '<div>'); $calendarView.calendarView('beforeRenderDay', (date) => { let classNames = ''; let text = '&nbsp;'; let day; let data = this._dataKeyByDay(); if(day = data[date.gregorian().format('yyyy-MM-dd')]) { classNames = day.class; text = day.text; } let $day = $(`<div class="${ClassName.DAY_NUMBER} ${classNames}">`); $day.html(`<div>${date.jalali().getDay()}</div><div class="extra-content">${text}</div>`); return $day; }); $calendarView.on('select.bs.calendar-view', (event) => { const selectedDay = event.relatedTarget.dataset.gregorianDate; const days = this._dataKeyByDay(); const pasoonate = Pasoonate.make().gregorian(selectedDay); const inputCheckin = $(parent).find(Selector.INPUT_CHECKIN); const inputCheckout = $(parent).find(Selector.INPUT_CHECKOUT); let isSelectableDay = {}; $calendarView.calendarView('hasClass', selectedDay, ClassName.SELECTABLE_DAY, isSelectableDay); isSelectableDay = isSelectableDay.value; const isLockDay = {}; $calendarView.calendarView('hasClass', selectedDay, ClassName.LOCK_DAY, isLockDay); if(isLockDay.value && !isSelectableDay) { return; } if(this._focusOn === 'start') { if(this._startDay === selectedDay) { return true; } if(this._startDay) { this._startDay = selectedDay; if(this._endDay === null) { //Check Disables if(days[selectedDay] && days[selectedDay].disabled) { return true; } $($calendarView) .calendarView('clearRange') .calendarView('startDay', this._startDay); } else if(this._endDay > selectedDay){ //Check Disables if(days[selectedDay] && days[selectedDay].disabled) { return true; } while(pasoonate.gregorian().format('yyyy-MM-dd') !== this._endDay) { pasoonate.addDay(1); const d = pasoonate.gregorian().format('yyyy-MM-dd'); if(days[d] && days[d].disabled && d !== this._endDay) { return true; } } $($calendarView) .calendarView('clearRange') .calendarView('selectRange', this._startDay, this._endDay); } else if(this._endDay < selectedDay){ //Check Disables if(days[selectedDay] && days[selectedDay].disabled) { return true; } $($calendarView) .calendarView('clearRange') .calendarView('startDay', this._startDay); this._endDay = null; } } else { //Check Disabled day if(days[selectedDay] && days[selectedDay].disabled) { return true; } this._startDay = selectedDay; $($calendarView) .calendarView('clearRange') .calendarView('startDay', this._startDay); this._focusOn = 'end'; const focusChangeEvent = $.Event(Event.FOCUS_CHANGE, { relatedTarget: this._element, focusOn: this._focusOn }); $(this._element).trigger(focusChangeEvent); } } else if(this._focusOn === 'end') { if(this._endDay === selectedDay) { return true; } if(this._endDay) { this._endDay = selectedDay; if(this._startDay === null) { this._focusOn = 'start'; const focusChangeEvent = $.Event(Event.FOCUS_CHANGE, { relatedTarget: this._element, focusOn: this._focusOn }); $(this._element).trigger(focusChangeEvent); return true; } else if(this._startDay < selectedDay){ //Check Disables if(days[selectedDay] && days[selectedDay].disabled && !isSelectableDay) { return true; } while(pasoonate.gregorian().format('yyyy-MM-dd') !== this._startDay) { pasoonate.subDay(1); const d = pasoonate.gregorian().format('yyyy-MM-dd'); if(days[d] && days[d].disabled) { return true; } } $($calendarView) .calendarView('clearRange') .calendarView('selectRange', this._startDay, this._endDay); } else if(this._startDay > selectedDay){ //Check Disables if(days[selectedDay] && days[selectedDay].disabled) { return true; } $($calendarView) .calendarView('clearRange') .calendarView('startDay', this._endDay); this._startDay = this._endDay; this._endDay = null; } } else { //Check Disables if(days[selectedDay] && days[selectedDay].disabled && !isSelectableDay) { return true; } if(pasoonate.gregorian().format('yyyy-MM-dd') <= this._startDay) { return true; } while(pasoonate.gregorian().format('yyyy-MM-dd') > this._startDay) { pasoonate.subDay(1); const d = pasoonate.gregorian().format('yyyy-MM-dd'); if(days[d] && days[d].disabled) { return true; } } this._endDay = selectedDay; $($calendarView) .calendarView('clearRange') .calendarView('selectRange', this._startDay, this._endDay); } } switch(this._focusOn) { case 'start': $(inputCheckin).addClass('focus'); $(inputCheckout).removeClass('focus'); break; case 'end': $(inputCheckout).addClass('focus'); $(inputCheckin).removeClass('focus'); break; } $(inputCheckin).html('انتخاب کنید'); $(inputCheckout).html('انتخاب کنید'); if(this._startDay) { $(inputCheckin).html(Pasoonate.make().gregorian(this._startDay).jalali().format('dd MMMM')); } if(this._endDay) { $(inputCheckout).html(Pasoonate.make().gregorian(this._endDay).jalali().format('dd MMMM')); } const changeEvent = $.Event(Event.CHANGE, { startDay: this._startDay, endDay: this._endDay }); $(this._element).trigger(changeEvent); this._unlockCurrentDays(); this._autoLockDays(); this._lockDays(this._options.lockBefore, this._options.lockAfter); this.hide(); }); $calendarView.on('over.bs.calendar-view', (event) => { const date = event.relatedTarget.dataset.gregorianDate; const days = this._dataKeyByDay(); const pasoonate = Pasoonate.make().gregorian(date); if(this._startDay == date) { return true; } if(this._startDay === null || this._startDay > date) { return true; } if(this._startDay && this._endDay === null) { //Check Disables let isSelectableDay = {value: false}; $($calendarView).calendarView('hasClass', date, ClassName.SELECTABLE_DAY, isSelectableDay); let isLockDay = {value: false}; $($calendarView).calendarView('hasClass', date, ClassName.LOCK_DAY, isLockDay); const isFirstSelectableDay = !isLockDay.value && isSelectableDay.value; if(days[date] && days[date].disabled && !isFirstSelectableDay) { return true; } while(pasoonate.gregorian().format('yyyy-MM-dd') !== this._startDay) { pasoonate.subDay(1); const d = pasoonate.gregorian().format('yyyy-MM-dd'); if(days[d] && days[d].disabled) { return true; } } $($calendarView) .calendarView('clearRange') .calendarView('selectRange', this._startDay, date); } }); } _dataKeyByDay() { let data = {}; if(this._options.data === undefined) { return data; } for(const item of this._options.data) { data[item.day] = item; } return data; } _autoLockDays() { const $calendarView = $(this._element.parentNode).find(Selector.CALENDAR_VIEW); const days = this._dataKeyByDay(); const range = {}; $calendarView.calendarView('getFirstAndLastDay', range); if(this._startDay) { const startDay = Pasoonate.make().gregorian(this._startDay).setTime(0, 0, 0); let findDisabled = false; let findFirstDisabled = null; const firstDay = Pasoonate.make(range.first).gregorian().setTime(0, 0, 0); const lastDay = Pasoonate.make(range.last).gregorian().setTime(0, 0, 0); while(startDay.beforeThanOrEqual(lastDay)) { startDay.gregorian().addDay(1); const d = startDay.gregorian().format('yyyy-MM-dd'); if(!findDisabled && (days[d] && days[d].disabled)) { findDisabled = true; if(findFirstDisabled === null) { findFirstDisabled = d; } } if(findDisabled && findFirstDisabled !== d) { $($calendarView).calendarView('addClass', d, ClassName.LOCK_DAY) } } findDisabled = false; startDay.gregorian(this._startDay).setTime(0, 0, 0); while(startDay.afterThanOrEqual(firstDay)) { startDay.gregorian().subDay(1); const d = startDay.gregorian().format('yyyy-MM-dd'); if(!findDisabled && days[d] && days[d].disabled) { findDisabled = true; } if(findDisabled) { $($calendarView).calendarView('addClass', d, ClassName.LOCK_DAY) } } } } _lockDays(before, after) { const $calendarView = $(this._element.parentNode).find(Selector.CALENDAR_VIEW); const range = {}; $calendarView.calendarView('getFirstAndLastDay', range); const firstDay = Pasoonate.make(range.first).gregorian().setTime(0, 0, 0); const lastDay = Pasoonate.make(range.last).gregorian().setTime(0, 0, 0); if(before) { const beforeDay = Pasoonate.make().gregorian(before).setTime(0, 0, 0); let isSelectableDay = {value: false}; $($calendarView).calendarView('hasClass', before, ClassName.SELECTABLE_DAY, isSelectableDay); if(isSelectableDay.value) { $($calendarView).calendarView('addClass', before, ClassName.LOCK_DAY); } while(beforeDay.afterThan(firstDay)) { beforeDay.gregorian().subDay(1); const d = beforeDay.gregorian().format('yyyy-MM-dd'); $($calendarView).calendarView('addClass', d, ClassName.LOCK_DAY); } } if(after) { const afterDay = Pasoonate.make().gregorian(after).setTime(0, 0, 0); while(afterDay.beforeThan(lastDay)) { afterDay.gregorian().addDay(1); const d = afterDay.gregorian().format('yyyy-MM-dd'); $($calendarView).calendarView('addClass', d, ClassName.LOCK_DAY) } } } _unlockCurrentDays() { const $calendarView = $(this._element.parentNode).find(Selector.CALENDAR_VIEW); const range = {}; $calendarView.calendarView('getFirstAndLastDay', range); const firstDay = Pasoonate.make(range.first).gregorian().setTime(0, 0, 0); const lastDay = Pasoonate.make(range.last).gregorian().setTime(0, 0, 0); while(firstDay.beforeThanOrEqual(lastDay)) { $calendarView.calendarView('removeClass', firstDay.gregorian().format('yyyy-MM-dd'), ClassName.LOCK_DAY); firstDay.gregorian().addDay(1); } } _assignSelectableDays() { const $calendarView = $(this._element.parentNode).find(Selector.CALENDAR_VIEW); const days = this._dataKeyByDay(); const range = {}; $calendarView.calendarView('getFirstAndLastDay', range); const firstDay = Pasoonate.make(range.first).gregorian().setTime(0, 0, 0); const lastDay = Pasoonate.make(range.last).gregorian().setTime(0, 0, 0); let selectableDay = 0; while(firstDay.beforeThanOrEqual(lastDay)) { const temp = firstDay.gregorian().format('yyyy-MM-dd'); if(days[temp] && days[temp].disabled) { selectableDay = selectableDay === 0 ? 1 : 2; } else { selectableDay = 0; } if(selectableDay === 1) { $($calendarView).calendarView('addClass', temp, ClassName.SELECTABLE_DAY); } firstDay.addDay(1); } } _updateDataOption(inputData) { const data = []; const oldData = this._dataKeyByDay(); let day = null; inputData = inputData || []; for(let i = 0; i < inputData.length; i++) { day = inputData[i].day; oldData[day] = inputData[i]; } for(let i in oldData) { data.push(oldData[i]); } return data; } // Static static get VERSION() { return VERSION } static _jQueryInterface(config, ...args) { return this.each(function () { const $this = $(this); let data = $this.data(DATA_KEY); if (!data) { data = new DatePicker(this); $this.data(DATA_KEY, data); } if (typeof config === 'string') { if (typeof data[config] === 'undefined') { throw new TypeError(`No method named "${config}"`); } data[config](args); } }) } } /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(document) .on(Event.CLICK_DATA_API, Selector.BTN_NEXT_MONTH, function (event) { $(this).closest(Selector.DATE_PICKER).parent().find(Selector.DATA_TOGGLE).datePicker('nextMonth'); }) .on(Event.CLICK_DATA_API, Selector.BTN_PREV_MONTH, function (event) { $(this).closest(Selector.DATE_PICKER).parent().find(Selector.DATA_TOGGLE).datePicker('prevMonth'); }) .on('change.bs.calendar-view', `${Selector.DATE_PICKER} ${Selector.CALENDAR_VIEW}`, function (event) { $(this).find(Selector.YEAR_MONTH).html(Pasoonate.trans(`jalali.month_name.${event.current.getMonth()}`) + ' ' + event.current.getYear()); }) .on('click', Selector.BTN_CLOSE, function () { $(this).closest(Selector.DATE_PICKER).parent().find(Selector.DATA_TOGGLE).datePicker('hide'); }) .on('click', Selector.INPUT_CHECKIN, function () { $(this).closest(Selector.DATE_PICKER).parent().find(Selector.DATA_TOGGLE).datePicker('focusOn', 'start'); }) .on('click', Selector.INPUT_CHECKOUT, function () { $(this).closest(Selector.DATE_PICKER).parent().find(Selector.DATA_TOGGLE).datePicker('focusOn', 'end'); }) .on('click', function (event) { let $activeDatePicker = $('.date-picker.show'); if($activeDatePicker.length) { let $myElements = $activeDatePicker.parent().find($(event.target)); if($myElements.length) { return true; } } $activeDatePicker.datePicker('hide'); }); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = DatePicker._jQueryInterface; $.fn[NAME].Constructor = DatePicker; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT return DatePicker._jQueryInterface }; return DatePicker; })($);
65d866dc2693b2d4835950aa051f2986a1355387
[ "JavaScript" ]
2
JavaScript
ataiemajid63/date-picker
691affd3d46f28792831e3e58ca2c8f16023df9c
345c4c4572828d47b6d5fd161c429c6c40fae4f1
refs/heads/master
<file_sep>package com.epam.jmp.composite.model; import java.util.ArrayList; import java.util.List; public class AstronomicalObject { private String name; private String age; private List<AstronomicalObject> subs; public AstronomicalObject(String name, String age) { this.name = name; this.age = age; subs = new ArrayList<AstronomicalObject>(); } public void add (AstronomicalObject object){ subs.add(object); } public void remove (AstronomicalObject object){ subs.remove(object); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public List<AstronomicalObject> getSubs() { return subs; } public void setSubs(List<AstronomicalObject> subs) { this.subs = subs; } @Override public String toString() { return "AstronomicalObject [name=" + name + ", age=" + age + "]"; } } <file_sep>package com.epam.jmp.first.world; public class Duck { private int xPosition; private int yPosititon; private String name; private int result; public int getxPosition() { return xPosition; } public void setxPosition(int xPosition) { this.xPosition = xPosition; } public int getyPosititon() { return yPosititon; } public void setyPosititon(int yPosititon) { this.yPosititon = yPosititon; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getResult() { return result; } public void setResult(int result) { this.result = result; } } <file_sep>package com.epam.testapp.database; import java.util.List; import com.epam.testapp.exception.DAOException; import com.epam.testapp.model.News; /** * This class consists exclusively of signatures of methods that will be * realized in implementation of this interface. * <p> * The methods of this class all throw a <tt>DAOException</tt> if happens some * SQL exception. * * @author <NAME> * @since 1.0 */ public interface INewsDAO { /** * Fetches an item from database by id. * * @param id * unique identification number of item that should be found. * @return found item * @throws DAOException * if happens some SQL error. */ public News fetchById(Integer id) throws DAOException; /** * Removes an item from database by id. * * @param items * arrays of unique identification numbers of items that should * be removed. * @return true if removing was finished successfully and false if not. * @throws DAOException * if happens some SQL error. */ public void remove(Integer[] items) throws DAOException; /** * Creates new item in database by provided News object. * * @param news * that should be added to database. * @return unique identification number of item that was created. * @throws DAOException * if happens some SQL error. */ public Integer insert(News news) throws DAOException; /** * Updates already existing item in database by provided News object. * * @param news that should be updated with. * @return unique identification number of item that was updated. * @throws DAOException * if happens some SQL error. */ public Integer update(News news) throws DAOException; /** * Gets all existing items from database. * * @return list of items that was loaded from database. * @throws DAOException * if happens some SQL error. */ public List<News> getList() throws DAOException; } <file_sep> public class SupermanSync { private static volatile SupermanSync superman; public static SupermanSync getInstance() { SupermanSync localInstance = superman; if (localInstance == null) { synchronized (SupermanSync.class) { localInstance = superman; if (localInstance == null) { superman = localInstance = new SupermanSync(); } } } return localInstance; } } <file_sep>package com.epam.task02.endpoint; import javax.xml.ws.Endpoint; import com.epam.task02.service.RandomNumberer; public class RandomNumbererPublisher { public static void main(String[] args) { Endpoint.publish("http://localhost:12345/ws/random", new RandomNumberer()); } } <file_sep>Application used for this task is from previous module. 1. Install tomcat. Open server.xml. Uncomment AJP connector definition. <Connector port="18009" protocol="AJP/1.3" redirectPort="8443" enableLookups="false" /> 2. Download and unpack Apache. 3. Download mod_jk from http://tomcat.apache.org/download-connectors.cgi. -> /pub/apache/tomcat/tomcat-connectors/jk/binaries/win32/. Unpack it to Apache's "modules" folder. 4. Open conf/httpd.conf and add following lines: LoadModule jk_module modules/mod_jk.so <IfModule jk_module> JkWorkersFile conf/workers.properties JkLogFile logs/mod_jk.log JkLogStampFormat "[%b %d %Y - %H:%M:%S] " JkRequestLogFormat "%w %V %T" JkLogLevel info JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories Alias /ui "d:/nm_ws/newsmanagament/ui/" <Directory "d:/nm_ws/newsmanagament/ui/"> AllowOverride None Allow from all </Directory> <Location /*/ui/*> deny from all </Location> #JkAutoAlias /usr/share/tomcat6-examples/ JkMount /ui/* myworker JkMount /ui myworker </IfModule> 5. Create workers.properties and insert there: worker.list=myworker worker.myworker.type=ajp13 worker.myworker.host=localhost worker.myworker.port=18009 Save file to Apache conf folder. 6. Verify httpd. Run in cmd from bin folder "httpd.exe -t". Install Apache by running "httpd.exe -k install". Run Apache by "httpd.exe -k start". 7. Start Tomcat and deploy application. 8. Test if everything is okay. Apache - http://localhost:81/ui/ Tomcat - http://localhost:8080/ui/ <file_sep>link.common.list = News List link.common.add = Add News link.common.edit = Edit link.common.delete = Delete link.common.view = View label.common.title = Title: label.common.date = Date: label.common.brief = Brief: label.common.text = Text: label.common.copyright = Copyright &#9400; EPAM 2014. All rights reserved. label.common.header = News Management head.main = News Management Web button.delete = Delete button.edit = Edit button.save = Save button.cancel = Cancel message.nodata = No recent news. menu.news = News menu.list = News List menu.view = News View menu.add = Add News menu.menu = Menu error.message.noselected = At least one news have to be selected error.message.quantity = Max field capacity: error.message.required = All fields required! error.message.daterror = Date format is invalid! Date have to be MM/dd/yyyy formatted! error.message.common = Some error happened, please contact administrator with further details. error.message.dayerror = Day should be from 1 to 31. error.message.montherror = Month should be from 1 to 12. error.message.yearerror = Year should be from 1900 to 2099. error.message.notitle = 'Title' field is required. error.message.nobrief = 'Brief' field is required. error.message.nocontent = 'Text' field is required. error.message.nodate = 'Date' field is required. error.message.newslistempty = No pending news. message.sure = Are you sure you want to complete this action? label.language.english = English label.language.russian = Russian inner.date.format = MM/dd/yyyy <file_sep>package com.epam.jpa.task01.menu; import java.util.List; import com.epam.jpa.task01.model.Employee; import com.epam.jpa.task01.model.Unit; import com.epam.jpa.task01.service.EmployeeService; import com.epam.jpa.task01.service.PersonalService; import com.epam.jpa.task01.service.UnitService; public class ChoiceHandler { public static void handleTheChoice(String stringChoice, EmployeeService employees, PersonalService personals, UnitService units) { int choice = Integer.parseInt(stringChoice); switch (choice) { case 1: // load employees List<Employee> employeeList = employees.getAll(); for (Employee employee: employeeList){ System.out.println(employee); } break; case 2: //load units List<Unit> unitList = units.getAll(); for (Unit unit: unitList){ System.out.println(unit); } break; case 3: // exit System.exit(0); break; default: System.out.println("Wrong choice..."); break; } } } <file_sep>package com.epam.jmp.decorator.runner; import javax.swing.JFrame; import com.epam.jmp.decorator.decorator.ButtonDecorator; import com.epam.jmp.decorator.frontend.CustomButtonMouseListener; import com.epam.jmp.decorator.model.Button; import com.epam.jmp.decorator.model.InterfaceElement; public class Runner { public static void main(String[] args) { InterfaceElement button = new ButtonDecorator(new Button()).getElement(); CustomButtonMouseListener listener = new CustomButtonMouseListener(button); JFrame frame = new JFrame(); frame.setSize(200, 200); frame.add(((Button)button).getButton()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } <file_sep>package com.epam.jmp.threads02.dao; import java.io.File; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import com.epam.jmp.threads02.model.ExchangeRate; import com.epam.jmp.threads02.model.ExchangeRates; public class ExchangeRateDAO implements DAO{ @Override public List<ExchangeRate> getAll() { JAXBContext context; ExchangeRates rates = null; try { context = JAXBContext.newInstance(ExchangeRates.class); Unmarshaller unmarshaller = context.createUnmarshaller(); rates = (ExchangeRates) unmarshaller.unmarshal(new File("src/resources/rates.xml")); } catch (JAXBException e) { e.printStackTrace(); } return rates.getExchangeRates(); } public void saveObject(Object o) { JAXBContext context; try { context = JAXBContext.newInstance(o.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(o, new File("src/resources/rates.xml")); } catch (JAXBException e) { e.printStackTrace(); } } } <file_sep>package com.epam.jmp.factory.model; public class Person implements java.io.Serializable{ private static final long serialVersionUID = 4202210714203614368L; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>package com.epam.testapp.model; import java.io.Serializable; import java.util.Date; public class News implements Serializable { /** * */ private static final long serialVersionUID = 1L; /** * field that contains unique identification number of news item. */ private Integer id; /** * field that contains title of news. */ private String title; /** * field that contains date of news. */ private Date postDate; /** * field that contains short description of news. */ private String brief; /** * field that contains full content of news item. */ private String content; /** * Constructor with all class' fields as a parameters * * @param id * contains unique identification number of news item. * @param title * contains title of news. * @param postDate * contains date of news. * @param brief * contains short description of news. * @param content * contains full content of news item. */ public News(Integer id, String title, Date postDate, String brief, String content) { this.id = id; this.title = title; this.postDate = postDate; this.brief = brief; this.content = content; } /** * Default constructor */ public News() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getPostDate() { return postDate; } public void setPostDate(Date postDate) { this.postDate = postDate; } public String getBrief() { return brief; } public void setBrief(String brief) { this.brief = brief; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } /** * Override method toString for current entity */ @Override public String toString() { return "News [id=" + id + ", title=" + title + ", postDate=" + postDate + ", brief=" + brief + ", content=" + content + "]"; } /** * Override method hashCode for current entity */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((brief == null) ? 0 : brief.hashCode()); result = prime * result + ((content == null) ? 0 : content.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((postDate == null) ? 0 : postDate.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); return result; } /** * Override method equals for current entity */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; News other = (News) obj; if (brief == null) { if (other.brief != null) return false; } else if (!brief.equals(other.brief)) return false; if (content == null) { if (other.content != null) return false; } else if (!content.equals(other.content)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (postDate == null) { if (other.postDate != null) return false; } else if (!postDate.equals(other.postDate)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; } } <file_sep>package com.epam.jmp.factory.tool; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ConsoleTool { public String takeInput() { String input = null; try { BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); input = bufferRead.readLine(); } catch (IOException e) { e.printStackTrace(); } return input; } } <file_sep>package com.epam.jmp.threads02.dao; import java.io.File; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import com.epam.jmp.threads02.model.Currencies; import com.epam.jmp.threads02.model.Currency; public class CurrencyDAO implements DAO { @Override public List<Currency> getAll() { JAXBContext context; Currencies currencies = null; try { context = JAXBContext.newInstance(Currencies.class); Unmarshaller unmarshaller = context.createUnmarshaller(); currencies = (Currencies) unmarshaller.unmarshal(new File("src/resources/currencies.xml")); } catch (JAXBException e) { e.printStackTrace(); } return currencies.getCurrencies(); } public void saveObject(Object o) { JAXBContext context; try { context = JAXBContext.newInstance(o.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(o, new File("src/resources/currencies.xml")); } catch (JAXBException e) { e.printStackTrace(); } } } <file_sep>package com.epam.jmp.threads01.runner; import com.epam.jmp.threads01.menu.ChoiceHandler; import com.epam.jmp.threads01.menu.Output; import com.epam.jmp.threads01.model.Bank; import com.epam.jmp.threads01.tool.DataThreadLoader; public class Runner { public static void main(String[] args) { DataThreadLoader loader = new DataThreadLoader(); loader.run(); Bank bank = Bank.getInstance(); System.out.println(bank); String choice; do { Output out = new Output(); choice = out.init(); ChoiceHandler.handleTheChoice(choice); System.out.println(bank); System.out.println("Wanna try again? no - exit"); choice = out.takeInput(); } while (!choice.equals("no")); } } <file_sep>package com.epam.jmp.decorator.decorator; import java.awt.Color; import javax.swing.border.Border; import com.epam.jmp.decorator.model.InterfaceElement; public abstract class Decorator implements InterfaceElement { protected InterfaceElement element; public Decorator(InterfaceElement element) { this.element = element; } @Override public Color getColor() { return element.getColor(); } @Override public Border getBorder() { return element.getBorder(); } public InterfaceElement getElement(){ return this.element; }; } <file_sep>package com.epam.testapp.service; import java.util.List; import com.epam.testapp.exception.DAOException; import com.epam.testapp.exception.NewsServiceException; import com.epam.testapp.model.News; /** * This interface provides interaction methods with dao layer and validates data. * * @author Anastasiya_Kulesh * */ public interface INewsService { /** * * @param id * @return * @throws NewsServiceException */ public News fetchById(int id) throws NewsServiceException; /** * * @param news * @return * @throws NewsServiceException */ public int save(News news) throws NewsServiceException; /** * * @return * @throws NewsServiceException */ public List<News> getList() throws NewsServiceException; /** * * @param items * @throws DAOException */ public void remove(Integer[] items) throws NewsServiceException; } <file_sep>package com.epam.jmp.decorator.frontend; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import com.epam.jmp.decorator.model.Button; import com.epam.jmp.decorator.model.InterfaceElement; public class CustomButtonMouseListener implements MouseListener{ private Button button; public CustomButtonMouseListener(InterfaceElement element) { super(); this.button = (Button)element; this.button.getButton().addMouseListener(this); } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { button.getButton().setBorder(button.getBorder()); button.getButton().setBackground(button.getColor()); } @Override public void mouseExited(MouseEvent arg0) { button.getButton().setBorder(null); button.getButton().setBackground(null); } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } <file_sep>package com.epam.jpa.task01.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import org.springframework.stereotype.Component; import com.epam.jpa.task01.model.Employee; @Component public class EmployeeDAO { public EntityManager em = Persistence.createEntityManagerFactory( "dbconnect").createEntityManager(); public Employee create(Employee employee) { em.getTransaction().begin(); employee = em.merge(employee); em.getTransaction().commit(); return employee; } public void delete(String id) { em.getTransaction().begin(); em.remove(get(id)); em.getTransaction().commit(); } public Employee get(String id) { return em.find(Employee.class, id); } public void update(Employee employee) { em.getTransaction().begin(); em.merge(employee); em.getTransaction().commit(); } public List<Employee> getAll() { TypedQuery<Employee> namedQuery = em.createNamedQuery("employee.getAll", Employee.class); return namedQuery.getResultList(); } } <file_sep>package com.epam.task01.rest.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.epam.task01.rest.connection.ConnectionPool; import com.epam.task01.rest.model.User; public class UserDAO implements IUserDAO { public static final String SQL_SELECT_ALL_USERS = "SELECT * FROM users"; public static final String SQL_SELECT_USER_BY_ID = "SELECT * FROM users WHERE id = ?"; public static final String SQL_DELETE_USER_BY_ID = "DELETE FROM users WHERE id = ?"; public static final String SQL_CREATE_NEW_USER = "INSERT INTO users (id,firstName,lastName,email,login) VALUES (?,?,?,?,?)" ; public static final String SQL_UPDATE_USER = "UPDATE users firstName = ?, lastName = ?, email = ?, login = ? WHERE id = ?"; protected static ConnectionPool connectionPool = ConnectionPool.getInstance(); public void closeStatement(Statement statement) { if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } public void closeConnection(Connection connection){ connectionPool.closeConnection(connection); } public static void destroyPool(){ connectionPool.destroy(); } public User createUser(User user) { Connection connection = null; PreparedStatement st = null; try{ connection = connectionPool.getConnection(); st = connection.prepareStatement(SQL_CREATE_NEW_USER); st.setString(1, user.getId()); st.setString(2, user.getLastName()); st.setString(3, user.getFirstName()); st.setString(4, user.getLogin()); st.setString(5, user.getEmail()); st.executeUpdate(); } catch(SQLException e){ e.printStackTrace(); } finally { this.closeStatement(st); this.closeConnection(connection); } return user; } public User getUser(String id) { Connection connection = null; PreparedStatement st = null; User user = null; try { connection = connectionPool.getConnection(); st = connection.prepareStatement(SQL_SELECT_USER_BY_ID); st.setString(1, id); ResultSet rs = st.executeQuery(); if (rs.next()) { user = new User(rs.getString("id"), rs.getString("firstName"), rs.getString("lastName"), rs.getString("email"), rs.getString("login")); } } catch (SQLException e) { e.printStackTrace(); } finally { this.closeStatement(st); this.closeConnection(connection); } return user; } public User updateUser(User user) { Connection connection = null; PreparedStatement st = null; try { connection = connectionPool.getConnection(); st = connection.prepareStatement(SQL_UPDATE_USER); st.setString(1, user.getId()); st.setString(2, user.getLastName()); st.setString(3, user.getFirstName()); st.setString(4, user.getLogin()); st.setString(5, user.getEmail()); ResultSet rs = st.executeQuery(); if (rs.next()) { user = new User(rs.getString("id"), rs.getString("firstName"), rs.getString("lastName"), rs.getString("email"), rs.getString("login")); } } catch (SQLException e) { e.printStackTrace(); } finally { this.closeStatement(st); this.closeConnection(connection); } return user; } public boolean removeUser(String id) { Connection connection = null; PreparedStatement st = null; boolean result = false; try{ connection = connectionPool.getConnection(); st = connection.prepareStatement(SQL_DELETE_USER_BY_ID); st.setString(1, id); st.executeUpdate(); result = true; } catch(SQLException e){ e.printStackTrace(); } finally { this.closeStatement(st); this.closeConnection(connection); } return result; } public List<User> getAll() { List<User> userList = new ArrayList<User>(); PreparedStatement st = null; Connection connection = null; try { connection = connectionPool.getConnection(); st = connection.prepareStatement(SQL_SELECT_ALL_USERS); ResultSet rs = st.executeQuery(); while (rs.next()) { User user = new User(rs.getString("id"), rs.getString("firstName"), rs.getString("lastName"), rs.getString("email"), rs.getString("login")); userList.add(user); } } catch(SQLException e){ e.printStackTrace(); } finally { this.closeStatement(st); this.closeConnection(connection); } return userList; } } <file_sep>package com.epam.jmp.threads02.tool; import com.epam.jmp.threads02.dao.CurrencyDAO; public class CurrencyThreadUploader extends Thread{ private Object data; public CurrencyThreadUploader(Object data) { super(); this.data = data; } public CurrencyThreadUploader(){ } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public void run(){ CurrencyDAO dao = new CurrencyDAO(); dao.saveObject(data); } } <file_sep>package com.epam.testapp.util; import java.util.Date; import javax.servlet.ServletException; import org.apache.commons.beanutils.ConvertUtils; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; /** * This class contains plug-in for registering existing converter in system. * * @author Anastasiya_Kulesh * */ public class DatePlugin implements PlugIn{ @Override public void destroy() { } /** * This method initializes existing converter. * * @param servlet * @param config */ @Override public void init(ActionServlet servlet, ModuleConfig config) throws ServletException { DateConverter converter = new DateConverter(); ConvertUtils.register(converter, Date.class); } } <file_sep>package com.epam.jmp.facade.runner; import com.epam.jmp.facade.facade.Facade; public class Runner { public static void main(String[] args) { Facade facade = new Facade(); facade.connect(); } } <file_sep>package com.epam.jmp.threads01.tool.loading; import com.epam.jmp.threads01.model.Bank; public interface Loader { Bank load(); } <file_sep>package com.epam.jmp.threads02.tool; import com.epam.jmp.threads02.dao.PersonDAO; public class ClientThreadUploader extends Thread{ private Object data; public ClientThreadUploader(Object data) { super(); this.data = data; } public ClientThreadUploader(){ } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public void run(){ PersonDAO dao = new PersonDAO(); dao.saveObject(data); } } <file_sep>package com.epam.task02.service; import java.util.Random; import javax.jws.WebService; @WebService(endpointInterface = "com.epam.task02.service.IRandomNumberer") public class RandomNumberer implements IRandomNumberer { public int getRandomNumber(int upper, int lower) { Random random = new Random(); long range = (long)upper - (long)lower + 1; long fraction = (long)(range * random.nextDouble()); int randomNumber = (int)(fraction + lower); return randomNumber; } } <file_sep>package com.epam.jpa.task02.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import org.springframework.stereotype.Component; import com.epam.jpa.task02.model.Account; @Component("accountDAO") public class AccountDAO { public EntityManager em = Persistence.createEntityManagerFactory( "dbconnect").createEntityManager(); public Account create(Account account) { em.getTransaction().begin(); account = em.merge(account); em.getTransaction().commit(); return account; } public void delete(String id) { em.getTransaction().begin(); em.remove(get(id)); em.getTransaction().commit(); } public Account get(String id) { return em.find(Account.class, id); } public void update(Account account) { em.getTransaction().begin(); em.merge(account); em.getTransaction().commit(); } public List<Account> getAll() { TypedQuery<Account> namedQuery = em.createNamedQuery("account.getAll", Account.class); return namedQuery.getResultList(); } } <file_sep>package com.epam.jmp.threads01.model; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "clients") public class Clients { private List<Person> clients; @XmlElement(name = "person") public List<Person> getClients() { return clients; } public void setClients(List<Person> clients) { this.clients = clients; } @Override public String toString() { return "Clients [clients=" + clients + "]"; } } <file_sep>package com.epam.jpa.task02.menu; import java.util.List; import com.epam.jpa.task02.model.Account; import com.epam.jpa.task02.model.Client; import com.epam.jpa.task02.service.AccountService; import com.epam.jpa.task02.service.ClientService; public class ChoiceHandler { public static void handleTheChoice(String stringChoice, AccountService accounts, ClientService clients) { int choice = Integer.parseInt(stringChoice); switch (choice) { case 1: // load clients List<Client> clientList = clients.getAll(); for (Client client: clientList){ System.out.println(client); } break; case 2: //load accounts List<Account> accountList = accounts.getAll(); for (Account account: accountList){ System.out.println(account); } break; case 3: // exit System.exit(0); break; default: System.out.println("Wrong choice..."); break; } } } <file_sep>package com.epam.jpa.task01.model; public enum EmployeeStatus { ACTIVE, FIRED, ONLEAVE } <file_sep>package com.epam.jmp.classloading01.tool; import java.io.File; import com.epam.jmp.classloading01.loading.CustomClassLoader; import org.apache.log4j.Logger; public class ChoiceHandler { private final static Logger logger = Logger.getLogger(ChoiceHandler.class); public static void handleTheChoice(String stringChoice) { int choice = Integer.parseInt(stringChoice); switch (choice) { case 1: // load class logger.info("Loading class..."); File file = new File("ojdbc6-11.2.0.2.0.jar"); new CustomClassLoader().loadClass(file); break; case 2: // exit logger.info("Exit..."); System.exit(0); break; default: logger.info("Wrong choice..."); break; } } } <file_sep>package com.epam.jpa.task03.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "currency") public class Currency { private String id; private String name; private int exchRate; public Currency(String id, String name, int exchRate) { this.id = id; this.name = name; this.exchRate = exchRate; } public Currency(){ } @Id @GeneratedValue public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name="NAME") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="EXCHANGERATE") public int getExchRate() { return exchRate; } public void setExchRate(int exchRate) { this.exchRate = exchRate; } @Override public String toString() { return "Currency [id=" + id + ", name=" + name + ", exchRate=" + exchRate + "]"; } } <file_sep>package com.epam.jmp.threads02.tool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPool { private final ExecutorService executorService = Executors.newFixedThreadPool(10); private static ThreadPool pool; private ThreadPool() { } public static ThreadPool getInstance(){ if (pool == null){ synchronized (ThreadPool.class){ if (pool == null){ pool = new ThreadPool(); } } } return pool; } public void addThread(Runnable thread){ executorService.submit(thread); } } <file_sep>package com.epam.jmp.threads01.tool.datahandler; import com.epam.jmp.threads01.menu.Output; import com.epam.jmp.threads01.model.Bank; import com.epam.jmp.threads01.model.Currencies; import com.epam.jmp.threads01.model.Currency; public class CurrencyHandler { public int exchange(){ Output output = new Output(); String currency = output.enterCurrency(); int amount = new Integer(output.enterAmount()); Currencies currencies = Bank.getInstance().getCurrencies(); int exchRate = 0; for (Currency curr :currencies.getCurrencies()){ if (curr.getId() == currency){ exchRate = curr.getExchRate(); } } return exchRate*amount; } } <file_sep>package com.epam.jmp.bridge.model; import javax.swing.JComponent; import com.epam.jmp.bridge.bridge.DataAPI; public abstract class Data { protected DataAPI dataAPI; protected Data(DataAPI dataAPI){ this.dataAPI = dataAPI; } public abstract JComponent show(); } <file_sep>package com.epam.jmp.threads02.model; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "currency") @XmlType(propOrder = {"id","name", "amount"}) public class Currency { private String id; private String name; private int amount; public Currency(String id, String name, int amount) { this.id = id; this.name = name; this.amount = amount; } public Currency(){ } public String getId() { return id; } @XmlElement public void setId(String id) { this.id = id; } public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public int getAmount() { return amount; } @XmlElement public void setAmount(int amount) { this.amount = amount; } @Override public String toString() { return "Currency [id=" + id + ", name=" + name + "]"; } } <file_sep>package com.epam.testapp.service; import java.util.List; import com.epam.testapp.database.INewsDAO; import com.epam.testapp.exception.DAOException; import com.epam.testapp.exception.NewsServiceException; import com.epam.testapp.model.News; /** * This class provides interaction with dao layer and validates data. * * @author Anastasiya_Kulesh * */ public class NewsServiceImpl implements INewsService { private INewsDAO newsDAO; public void setNewsDAO(INewsDAO newsDAO) { this.newsDAO = newsDAO; } public INewsDAO getNewsDAO() { return newsDAO; } /** * * @param id * @return * @throws NewsServiceException */ public News fetchById(int id) throws NewsServiceException { News news; try { news = newsDAO.fetchById(id); if (news == null) { throw new NewsServiceException("NULL ERROR"); } } catch (DAOException e) { throw new NewsServiceException(e); } return news; } /** * * @param news * @return * @throws NewsServiceException */ public int save(News news) throws NewsServiceException { Integer id = news.getId(); try { if (id == null) { id = newsDAO.insert(news); } else { id = newsDAO.update(news); } if (id == 0) { throw new NewsServiceException("NULL ERROR"); } } catch (DAOException e) { throw new NewsServiceException(e); } return id; } /** * * @return * @throws NewsServiceException */ public List<News> getList() throws NewsServiceException { List<News> allNews; try { allNews = newsDAO.getList(); } catch (DAOException e) { throw new NewsServiceException(e); } return allNews; } /** * * @param items * @throws DAOException */ public void remove(Integer[] items) throws NewsServiceException { try { newsDAO.remove(items); } catch (DAOException e) { throw new NewsServiceException(e); } } } <file_sep>package com.epam.jmp.flyweight.factory; import java.util.HashMap; import com.epam.jmp.flyweight.model.CustomFileList; import com.epam.jmp.flyweight.model.FileList; public class FileListFactory { private static final HashMap<String, FileList> addressMap = new HashMap<>(); public static FileList getFileList(String address){ CustomFileList fileList = (CustomFileList)addressMap.get(address); if (fileList == null) { fileList = new CustomFileList(address); addressMap.put(address, fileList); System.out.println("Creating fileList: " + address); } return fileList; } } <file_sep>package com.epam.task01.rest.dao; import java.util.List; import com.epam.task01.rest.model.User; public interface IUserDAO { User createUser(User User); User getUser(String id); User updateUser(User User); boolean removeUser(String id); List<User> getAll(); } <file_sep>package com.epam.jmp.memory.method; import com.epam.jmp.memory.model.GreatObject; public class ReferenceTaker { /*public void takeAReference(String line){ GreatObject obj = new GreatObject(line); } */ public GreatObject takeAReference(String line){ return new GreatObject(line); } } <file_sep>package com.epam.jmp.threads04.runner; import com.epam.jmp.threads04.model.Car; public class Runner { public static void main(String[] args) { Thread t1 = new Thread(new Car("AAA", 10L, true)); Thread t2 = new Thread(new Car("BBB", 20L, false)); t1.setName("AAA"); t2.setName("BBB"); t1.start(); t2.start(); String winner = null; try { while (true) { Thread.sleep(100); if (!t1.isAlive() && t2.isAlive()){ winner = t1.getName(); } if (!t2.isAlive() && t1.isAlive()){ winner = t2.getName(); } if (!(t1.isAlive() || t2.isAlive())) { System.out.println("Winner is " + winner + "!"); break; } } } catch (InterruptedException e) { } } } <file_sep>db.driverClassName=org.hsqldb.jdbcDriver db.url=jdbc:hsqldb:hsql://localhost/xdb db.username=ak db.password=ak db.dialect=org.hibernate.dialect.HSQLDialect<file_sep>package com.epam.jmp.threads01.menu; import java.io.File; import com.epam.jmp.threads01.model.Account; import com.epam.jmp.threads01.model.Bank; import com.epam.jmp.threads01.model.Person; import com.epam.jmp.threads01.tool.DataThreadLoader; import com.epam.jmp.threads01.tool.DataThreadUploader; import com.epam.jmp.threads01.tool.datahandler.AccountHandler; import com.epam.jmp.threads01.tool.datahandler.ClientHandler; import com.epam.jmp.threads01.tool.datahandler.CurrencyHandler; public class ChoiceHandler { public static void handleTheChoice(String stringChoice) { int choice = Integer.parseInt(stringChoice); DataThreadLoader loader = new DataThreadLoader(); System.out.println("Choice = " + choice); switch (choice) { case 1: loader.run(); break; case 2: AccountHandler aHandler = new AccountHandler(); Account account = aHandler.createAccount(); File aFile = new File("src/resources/accounts.xml"); Bank.getInstance().getAccounts().getAccounts().add(account); DataThreadUploader aUp = new DataThreadUploader(Bank.getInstance().getAccounts(), aFile); aUp.run(); loader.run(); break; case 3: ClientHandler cHandler = new ClientHandler(); Person person = cHandler.createClient(); Bank.getInstance().getClients().getClients().add(person); File pFile = new File("src/resources/clients.xml"); DataThreadUploader pUp = new DataThreadUploader(Bank.getInstance().getClients(), pFile); pUp.start(); loader.run(); break; case 4: CurrencyHandler curHandler = new CurrencyHandler(); int amount = curHandler.exchange(); System.out.println("Amount to give to client = " + amount); break; default: //System.exit(0); break; } } } <file_sep>package com.epam.jpa.task03.model; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "account") public class Account { private String id; private Currency currency; private Person person; private int amount; public Account(String id, Currency currency, Person owner, int amount) { super(); this.id = id; this.currency = currency; this.person = owner; this.amount = amount; } public Account(){ } @Id @GeneratedValue public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name="EXCHANGERATE") public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } @OneToOne(orphanRemoval = true, cascade = CascadeType.ALL) @JoinColumn(name = "CURRENCYID") public Currency getCurrency() { return currency; } public void setCurrency(Currency currency) { this.currency = currency; } @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "personId", nullable = false) public Person getPerson() { return person; } public void setPerson(Person owner) { this.person = owner; } @Override public String toString() { return "Account [id=" + id + ", currency=" + currency + ", owner=" + person + ", amount=" + amount + "]"; } } <file_sep>package com.epam.jmp.memory.runner; import com.epam.jmp.memory.method.ReferenceTaker; public class Runner { public static void main(String[] args) { new ReferenceTaker().takeAReference("Hahahaha"); } } <file_sep>package com.epam.jmp.flyweight.guiutility; import java.awt.Component; import java.io.File; import javax.swing.DefaultListCellRenderer; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.filechooser.FileSystemView; public class FileRenderer extends DefaultListCellRenderer { private boolean pad; private Border padBorder = new EmptyBorder(3, 3, 3, 3); public FileRenderer(boolean pad) { this.pad = pad; } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); JLabel l = (JLabel) c; File f = (File) value; l.setText(f.getName()); l.setIcon(FileSystemView.getFileSystemView().getSystemIcon(f)); if (pad) { l.setBorder(padBorder); } return l; } } <file_sep>function checkLength(len_max, field_id) { var len_current = document.getElementById(field_id).value.length; var rest = len_max - len_current; if (len_current > len_max) { document.getElementById(field_id).value = document .getElementById(field_id).value.substr(0, len_max); if (rest < 0) { rest = 0; } alert(msg.length.quantityerror + ' ' + len_max) } } function countSymbols(len_max, field_id, counter_id) { var len_current = document.getElementById(field_id).value.length; document.getElementById(counter_id).firstChild.data = len_current + ' / ' + len_max; } function requireCheckboxes() { checkboxes = document.getElementsByName('selectedItems'); for (var i = 0, n = checkboxes.length; i < n; i++) { if (checkboxes[i].checked == true) { return sureDelete(); } } alert(msg.length.noselected); return false; } function checkEmptyAreas() { var txt001 = document.getElementById('Txt001'); var txtA001 = document.getElementById('TxtA001'); var txtA002 = document.getElementById('TxtA002'); var lang = document.getElementsByTagName('html')[0].lang; var date = document.getElementById('Txt003').value; var message = validateDate(date, lang); var result = true; if (message != 0) { result = false; } var textmessage = validateText(txtA001, txtA002, txt001); if (textmessage != 0) { message = message + textmessage + '\n'; result = false; } if (result == false) { alert(message); } else { if (lang == 'ru') { var splitted = date.split('/'); var day = splitted[0]; var month = splitted[1]; var year = splitted[2]; var endDate = month + '/' + day + '/' + year; document.getElementById('Txt003').value = endDate; } } return result; } function validateDate(date, lang) { var commonPattern = /^([0-9]{2}\/[0-9]{2}\/[0-9]{4})$/; var dayPattern = /^(0[1-9]|[12]\d|3[01])$/; var monthPattern = /^(0[1-9]|1[0-2])$/; var yearPattern = /^((([1]{1}[9]{1})|([2]{1}[0]{1}))[0-9]{2})$/; var splitted = date.split('/'); var message = ''; var day; var month; var year = splitted[2]; if (commonPattern.test(date)) { if (lang == 'ru') { day = splitted[0]; month = splitted[1]; } else { day = splitted[1]; month = splitted[0]; } if (!dayPattern.test(day) || !monthPattern.test(month) || !yearPattern.test(year)) { if (!dayPattern.test(day)) { message = msg.length.dayerror + '\n'; } if (!monthPattern.test(month)) { message = message + msg.length.montherror + '\n'; } if (!yearPattern.test(year)) { message = message + msg.length.yearerror + '\n'; } } } else { message = msg.length.dateerror + '\n'; } return message; } function validateText(txtA001, txtA002, txt001) { var empty = ''; var message = ''; if (txtA001.value == empty) { message = msg.length.nobrief + '\n'; } if (txtA002.value == empty) { message = message + msg.length.nocontent + '\n'; } if (txt001.value == empty) { message = message + msg.length.notitle + '\n'; } return message; } function sureDelete() { if (confirm(msg.length.sure)) { return true; } else { return false; } } <file_sep>package com.epam.jmp.bridge.bridge; import javax.swing.JComponent; public interface DataAPI { public JComponent getComponent(String[] data); } <file_sep>package com.epam.task02.client; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import com.epam.task02.service.IRandomNumberer; public class ClientRunner { public static void main(String[] args) { URL url = null; try { url = new URL("http://localhost:12345/ws/random?wsdl"); } catch (MalformedURLException e) { e.printStackTrace(); } QName qname = new QName("http://service.task02.epam.com/", "RandomNumbererService"); Service service = Service.create(url, qname); IRandomNumberer numberer = service.getPort(IRandomNumberer.class); System.out.println("Lottery!"); for (int i = 1; i <= 6; i++) { System.out.println("Number ¹ " + i + " is " +numberer.getRandomNumber(49, 0)); } } } <file_sep>package com.epam.jmp.threads01.tool.datahandler; import com.epam.jmp.threads01.menu.Output; import com.epam.jmp.threads01.model.Account; import com.epam.jmp.threads01.model.Bank; public class AccountHandler { public Account createAccount(){ Output output = new Output(); String id = output.enterId(); String curId = output.enterCurrency(); String ownerId = output.enterOwner(); Integer amount = new Integer(output.enterAmount()); Account account = new Account(id, curId, ownerId, amount); return account; } } <file_sep>package com.epam.jpa.task02.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.epam.jpa.task02.dao.ClientDAO; import com.epam.jpa.task02.model.Client; @Component("clientService") public class ClientService { @Autowired @Qualifier("clientDAO") private ClientDAO clientDao; public ClientDAO getClientDao() { return clientDao; } public void setClientDao(ClientDAO clientDao) { this.clientDao = clientDao; } @Transactional public Client create(Client client) { client = clientDao.create(client); return client; } @Transactional public void delete(Client client) { if (client != null) { clientDao.delete(client.getId()); } } @Transactional public Client searchPerson(String id) { Client client = null; client = clientDao.get(id); return client; } @Transactional public List<Client> getAll() { List<Client> clientList = null; clientList = clientDao.getAll(); return clientList; } } <file_sep>package com.epam.jmp.bridge.bridge; import java.awt.Dimension; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; public class ListDataAPI implements DataAPI{ @Override public JComponent getComponent(String[] data) { JList<String> list = new JList<String>(data); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.setLayoutOrientation(JList.VERTICAL_WRAP); list.setVisibleRowCount(-1); JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(250, 80)); return list; } } <file_sep>package com.epam.jmp.decorator.model; import java.awt.Color; import javax.swing.border.Border; public interface InterfaceElement { Color getColor(); Border getBorder(); void setColor(Color color); void setBorder(Border border); } <file_sep>package com.epam.jpa.task02.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import org.springframework.stereotype.Component; import com.epam.jpa.task02.model.Client; @Component("clientDAO") public class ClientDAO { public EntityManager em = Persistence.createEntityManagerFactory("dbconnect").createEntityManager(); public Client create(Client client){ em.getTransaction().begin(); Client clientFromDB = em.merge(client); em.getTransaction().commit(); return clientFromDB; } public void delete(String id){ em.getTransaction().begin(); em.remove(get(id)); em.getTransaction().commit(); } public Client get(String id){ return em.find(Client.class, id); } public void update(Client client){ em.getTransaction().begin(); em.merge(client); em.getTransaction().commit(); } public List<Client> getAll(){ TypedQuery<Client> namedQuery = em.createNamedQuery("client.getAll", Client.class); return namedQuery.getResultList(); } } <file_sep>package com.epam.jmp.third.builder; import java.util.ArrayList; import java.util.List; import com.epam.jmp.third.model.Chair; import com.epam.jmp.third.model.Coachwork; import com.epam.jmp.third.model.Engine; import com.epam.jmp.third.model.SteeringWheel; import com.epam.jmp.third.model.Wheel; public class RenaultCarBuilder extends CarBuilder { @Override public void buildChairs() { int quantity = 5; List<Chair> chairs = new ArrayList<Chair>(); Chair chair; for (int i = 1; i < quantity; i++){ chair = new Chair(); chair.setType("leather"); chairs.add(chair); } car.setChairs(chairs); } @Override public void buildCoachwork() { Coachwork coachwork = new Coachwork(); coachwork.setMaterial("silver"); car.setCoachwork(coachwork); } @Override public void buildEngine() { Engine engine = new Engine(); engine.setCylinders(6); car.setEngine(engine); } @Override public void buildSteeringWheel() { SteeringWheel stWheel = new SteeringWheel(); stWheel.setType("round"); car.setSteeringWheel(stWheel); } @Override public void buildWheels() { int quantity = 4; List<Wheel> wheels = new ArrayList<Wheel>(); Wheel wheel; for (int i = 1; i < quantity; i++){ wheel = new Wheel(); wheel.setType("Bridgestone"); wheels.add(wheel); } car.setWheels(wheels); } } <file_sep>package com.epam.jmp.classloading01.runner; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import com.epam.jmp.classloading01.tool.ChoiceHandler; import com.epam.jmp.classloading01.tool.Output; public class Runner { private final static Logger logger = Logger.getLogger(Runner.class); public static void main(String[] args) { new DOMConfigurator().doConfigure("log4j.xml", LogManager.getLoggerRepository()); String choice; do { Output out = new Output(); choice = out.out(); ChoiceHandler.handleTheChoice(choice); logger.info("Wanna try again? no - exit"); choice = out.takeInput(); } while (!choice.equals("no")); } } <file_sep>package com.epam.jmp.adapter.runner; import javax.swing.JFrame; import com.epam.jmp.adapter.adapter.MapToTableAdapterComposition; import com.epam.jmp.adapter.adapter.MapToTableAdapterInheritance; import com.epam.jmp.adapter.model.DataMap; public class Runner { public static void main(String[] args) { DataMap map = new DataMap(); JFrame frame = new JFrame(); frame.setSize(200, 200); //frame.add(new MapToTableAdapterInheritance().outTo(map).getTable()); frame.add(new MapToTableAdapterComposition().convertMapToTable(map).getTable()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } <file_sep> public class Superman { private static final Superman SUPERMAN = new Superman(); public Superman getSuperman(){ return Superman.SUPERMAN; } } <file_sep>package com.epam.jmp.threads01.tool.loading; import java.io.File; import com.epam.jmp.threads01.model.Accounts; import com.epam.jmp.threads01.model.Bank; import com.epam.jmp.threads01.model.Clients; import com.epam.jmp.threads01.model.Currencies; import com.epam.jmp.threads01.tool.parsing.JaxbParser; public class XMLLoader implements Loader { public Bank load() { Bank bank = Bank.getInstance(); synchronized (XMLLoader.class) { JaxbParser parser = new JaxbParser(); File currFile = new File("src/resources/currencies.xml"); File accFile = new File("src/resources/accounts.xml"); File persFile = new File("src/resources/clients.xml"); Currencies currencies = (Currencies) parser.getObject(currFile, Currencies.class); Accounts accounts = (Accounts) parser.getObject(accFile, Accounts.class); Clients clients = (Clients) parser.getObject(persFile, Clients.class); bank.setAccounts(accounts); bank.setClients(clients); bank.setCurrencies(currencies); } return bank; } } <file_sep>package com.epam.jmp.factory.factorymethod; import com.epam.jmp.factory.model.Person; import com.epam.jmp.factory.model.Resource; public abstract class AbstractDataHandler { protected Resource resource; public Resource getResource() { return resource; } public void setResource(Resource resource) { this.resource = resource; } public abstract void writePerson(Person person); public abstract Person readPerson(); public abstract Person readPerson(String name); } <file_sep>package com.epam.jmp.factory.factorymethod; import com.epam.jmp.factory.abstractfactory.DBResourceFactory; import com.epam.jmp.factory.abstractfactory.FileResourceFactory; import com.epam.jmp.factory.abstractfactory.ResourceFactory; import com.epam.jmp.factory.model.Resource; public class FactoryMethod { public AbstractDataHandler getHandler(Object object) { AbstractDataHandler handler = null; ResourceFactory factory = null; if (object.equals("f")) { handler = new FileDataHandler(); factory = new FileResourceFactory(); } else { handler = new DBDataHandler(); factory = new DBResourceFactory(); } Resource resource = factory.createResource(); handler.setResource(resource); return handler; } } <file_sep>package com.epam.task01.rest.model; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "user") public class User { private String id; private String lastName; private String firstName; private String email; private String login; @XmlElement public String getId() { return id; } public void setId(String id) { this.id = id; } @XmlElement public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @XmlElement public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @XmlElement public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @XmlElement public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public User(String id, String lastName, String firstName, String email, String login) { super(); this.id = id; this.lastName = lastName; this.firstName = firstName; this.email = email; this.login = login; } public User() { } @Override public String toString() { return "User [id=" + id + ", lastName=" + lastName + ", firstName=" + firstName + ", email=" + email + ", login=" + login + "]"; } } <file_sep>package com.epam.jpa.task03.tool.datahandler; import com.epam.jpa.task03.menu.Output; import com.epam.jpa.task03.model.Bank; import com.epam.jpa.task03.model.Person; public class PersonHandler { public Person createClient(){ Output output = new Output(); String firstName = output.enterFirstName(); String lastName = output.enterLastName(); String status = output.enterStatus(); Person person = new Person(); person.setFirstName(firstName); person.setLastName(lastName); person.setStatus(status); return person; } } <file_sep>package com.epam.testapp.util; import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; import org.apache.commons.beanutils.Converter; import org.apache.log4j.Logger; /** * This class contains method for converting date from string to util.date when * it happens to upload data from client side to database. * * @author Anastasiya_Kulesh * */ public class DateConverter implements Converter { private static final Logger LOG = Logger.getLogger(DateConverter.class); /** * This method converts String value to java.util.date * * @param type * @param value */ @Override public Object convert(Class type, Object value) { Date date = null; try { String inputDate = value.toString(); SimpleDateFormat formatter = new SimpleDateFormat( ProjectConstant.EN_DATE_PATTERN); date = formatter.parse(inputDate); } catch (ParseException e) { LOG.error(ProjectConstant.ERROR_CONVERT_DATE + e); } return date; } } <file_sep>package com.epam.jmp.factory.runner; import com.epam.jmp.factory.facade.Facade; public class Runner { public static void main(String[] args) { Facade facade = new Facade(); facade.doTheThing(); } } <file_sep>package com.epam.jmp.factory.factorymethod; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.epam.jmp.factory.model.Person; import com.epam.jmp.factory.model.DBResource; public class DBDataHandler extends AbstractDataHandler { private static final String SQL_QUERY_WRITE_OBJECT = "INSERT INTO persons (?,?)"; private static final String SQL_QUERY_SELECT_OBJECT_BY_NAME = "SELECT * FROM persons WHERE name = ?"; private static final String SQL_QUERY_SELECT_FIRST = "SELECT * FROM persons WHERE ROWNUM <= number"; @Override public void writePerson(Person person) { PreparedStatement pstmt; try { pstmt = ((DBResource) resource).getConnection().prepareStatement(SQL_QUERY_WRITE_OBJECT); pstmt.setObject(1, person); pstmt.setString(2, person.getName()); pstmt.executeUpdate(); pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } @Override public Person readPerson() { PreparedStatement pstmt; Person person = null; try { pstmt = ((DBResource) resource).getConnection().prepareStatement(SQL_QUERY_SELECT_FIRST); ResultSet rs = pstmt.executeQuery(); person = new Person(); rs.next(); person.setName(rs.getString("name")); pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } return person; } @Override public Person readPerson(String name) { PreparedStatement pstmt; Person person = null; try { pstmt = ((DBResource) resource).getConnection().prepareStatement(SQL_QUERY_SELECT_OBJECT_BY_NAME); ResultSet rs = pstmt.executeQuery(); person = new Person(); rs.next(); person.setName(rs.getString("name")); pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } return person; } } <file_sep>package com.epam.jmp.third.runner; import com.epam.jmp.third.builder.CarBuilder; import com.epam.jmp.third.builder.Director; import com.epam.jmp.third.builder.RenaultCarBuilder; import com.epam.jmp.third.model.Car; public class Runner { public static void main(String[] args) { Director director = new Director(); CarBuilder renaultBuilder = new RenaultCarBuilder(); director.setCarBuilder(renaultBuilder); director.constructCar(); Car car = director.getCar(); car.print(); } } <file_sep>package com.epam.jmp.factory.abstractfactory; import com.epam.jmp.factory.model.DBResource; import com.epam.jmp.factory.model.Resource; public class DBResourceFactory extends ResourceFactory{ @Override public Resource createResource() { return new DBResource(); } } <file_sep>package com.epam.jmp.factory.abstractfactory; import com.epam.jmp.factory.model.FileResource; import com.epam.jmp.factory.model.Resource; public class FileResourceFactory extends ResourceFactory{ @Override public Resource createResource() { return new FileResource(); } } <file_sep>package com.epam.jmp.adapter.model; import javax.swing.JTable; public class DataTable implements Data{ private JTable table; public DataTable() {} public DataTable(String[] columns, Object[][] values){ table = new JTable(values, columns); } public JTable getTable() { return table; } public void setTable(JTable table) { this.table = table; } @Override public Object outTo(Data data) { return ((DataTable) data).getTable().toString(); } } <file_sep>package com.epam.jmp.factory.factorymethod; import com.epam.jmp.factory.model.Person; import com.epam.jmp.factory.tool.SerializationTool; public class FileDataHandler extends AbstractDataHandler { @Override public void writePerson(Person person) { new SerializationTool().serialize(person); } @Override public Person readPerson() { throw new UnsupportedOperationException(); } @Override public Person readPerson(String name) { Person person = new SerializationTool().deserialize(name); return person; } } <file_sep>package com.epam.jpa.task03.model; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @Entity @Table(name = "person") public class Person { private String id; private String firstName; private String lastName; private String status; private List<Account> accounts; public Person(String id, String firstName, String lastName, String status, List<Account> accounts) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.status = status; this.accounts = accounts; } public Person() { } @Id @GeneratedValue public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name="FIRSTNAME") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name="LASTNAME") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Column(name="STATUS") public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @OneToMany(fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "person") @PrimaryKeyJoinColumn public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; } @Override public String toString() { return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", status=" + status + ", accounts=" + accounts + "]"; } } <file_sep>package com.epam.jpa.task01.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.epam.jpa.task01.dao.UnitDAO; import com.epam.jpa.task01.model.Unit; @Component("unitService") @Transactional public class UnitService { @Autowired private UnitDAO dao; public UnitDAO getDao() { return dao; } public void setDao(UnitDAO dao) { this.dao = dao; } public Unit create(Unit account) { account = dao.create(account); return account; } public void delete(Unit account) { if (account != null) { dao.delete(account.getId()); } } public Unit getUnit(String id) { Unit account = null; account = dao.get(id); return account; } public List<Unit> getAll() { List<Unit> accountList = null; accountList = dao.getAll(); return accountList; } } <file_sep>package com.epam.jmp.threads06.runner; import java.util.Vector; import com.epam.jmp.threads06.model.Consumer; import com.epam.jmp.threads06.model.Producer; import com.epam.jmp.threads06.tool.Output; public class Runner { @SuppressWarnings("rawtypes") public static void main(String[] args) { Vector sharedQueue = new Vector(); int size = new Integer(new Output().init()); Thread producer = new Thread(new Producer(sharedQueue, size), "Producer"); Thread consumer = new Thread(new Consumer(sharedQueue, size), "Consumer"); producer.start(); consumer.start(); } } <file_sep>package com.epam.jpa.task03.model; import java.util.List; public class Bank { private static Bank bank; private List<Person> clients; private List<Account> accounts; private List<Currency> currencies; private Bank() { } public static Bank getInstance(){ if (bank == null){ synchronized (Bank.class){ if (bank == null){ bank = new Bank(); } } } return bank; } public List<Person> getClients() { return clients; } public void setClients(List<Person> clients) { this.clients = clients; } public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; } public List<Currency> getCurrencies() { return currencies; } public void setCurrencies(List<Currency> currencies) { this.currencies = currencies; } @Override public String toString() { return "Bank: [accounts=" + accounts.toString() + ",\n clients=" + clients.toString() + ",\n currencies=" + currencies.toString() + "]"; } }
1413f67baca75506e0830fe6f1eb3c422eb2e8fa
[ "JavaScript", "Java", "Text", "INI" ]
75
Java
alleinr/JMP-2015-2016-Valiantsin_Charkashyn-Group-1
d6a57914e0003a835d3c1574f925d265c9045c80
0ff1b8fa8b1e4926614b58645a57f6872ac25ebb
refs/heads/master
<file_sep>angular.module("BeskidSlaski") .directive("bsLeaflet", function ($parse) { return { restrict: "E", scope: { menuClick: "&", layers: "=", position: "=" }, link: function (scope, element, attributes) { var map, marker, base, peaks, shelters, paths, attribution, scale; map = L.map(element[0], { center: L.latLng(49.707493, 19.013193), zoom: 11, minZoom: 11, maxZoom: 14, maxBounds: L.latLngBounds(L.latLng(49.3847, 18.7334), L.latLng(49.8013, 19.2443)), zoomControl: false, attributionControl: false }); base = L.tileLayer("img/tiles/{z}/{x}/{y}.png"); marker = L.marker([0, 0], { icon: L.icon({ iconUrl: "img/marker.png", iconSize: [16, 16], iconAnchor: [8, 8] }) }); peaks = L.geoJson.ajax("geo/peaks.json", { pointToLayer: function (feature, latLng) { var icon = L.icon({ iconUrl: "img/peak.png", iconSize: [32, 32], iconAnchor: [16, 16] }), layer = L.marker(latLng, { icon: icon }); layer.bindPopup(feature.properties.name || "brak danych"); return layer; } }); shelters = L.geoJson.ajax("geo/shelters.json", { pointToLayer: function (feature, latLng) { var icon = L.icon({ iconUrl: "img/shelter.png", iconSize: [32, 32], iconAnchor: [16, 16] }), layer = L.marker(latLng, { icon: icon }); layer.bindPopup(feature.properties.name || "brak danych"); return layer; } }); paths = L.geoJson.ajax("geo/paths.json", { onEachFeature: function (feature, layer) { var popup = "<br>" + feature.properties.name + "<br>" + "Czas przejścia: " + feature.properties.times + "<br>" + "Dystans: " + feature.properties.distance + " km"; feature.properties.colors.forEach(function (color) { popup = "" + "<div class='path'><div style='background: " + color + ";'></div></div>&nbsp;" + popup; }); layer.setStyle({ opacity: 1, color: feature.properties.colors[0] }); feature.properties.colors.slice(1).forEach(function (color, i) { var additionalPath = L.polyline(layer.getLatLngs(), { opacity: 1, color: color, className: "path-" + (i + 1) }); additionalPath.bindPopup(popup); paths.addLayer(additionalPath); }); layer.bindPopup(popup); } }); base.addTo(map); attribution = L.control.attribution({ prefix: false, position: "bottomleft" }).addAttribution('&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors').addTo(map); scale = L.control.scale({ imperial: false, position: "bottomright" }).addTo(map); scope.$watch("layers.position", function (visible) { visible ? map.addLayer(marker) : map.removeLayer(marker); }); scope.$watch("layers.peaks", function (visible) { visible ? map.addLayer(peaks) : map.removeLayer(peaks); }); scope.$watch("layers.shelters", function (visible) { visible ? map.addLayer(shelters) : map.removeLayer(shelters); }); scope.$watch("layers.paths", function (visible) { visible ? map.addLayer(paths) : map.removeLayer(paths); }); scope.$watchGroup(["position.latitude", "position.longitude"], function (position) { if (position[0] !== undefined && position[1] !== undefined) { marker.setLatLng(position); } }); } }; }); <file_sep>#!/usr/bin/env bash if [[ $CORDOVA_PLATFORMS == *android* ]] then echo Copying ant.properties cp ant.properties platforms/android/ant.properties fi <file_sep>#!/usr/bin/env node /*global require*/ var exec = require("child_process").exec; function installPlugin(name) { console.log("\033[36m[MO-BILLING]\033[37m Installing plugin: \033[33m" + name + "\033[37m"); exec("cordova plugin add " + name); }; var pluginList = [ "org.apache.cordova.console", "org.apache.cordova.device", "org.apache.cordova.dialogs", "org.apache.cordova.inappbrowser", "org.apache.cordova.statusbar", "org.apache.cordova.device-orientation", "org.apache.cordova.geolocation" ]; console.log("\033[36m[MO-BILLING]\033[37m Install plugins: \033[32mSTART\033[37m"); pluginList.forEach(installPlugin); console.log("\033[36m[MO-BILLING]\033[37m Install plugins: \033[32mEND\033[37m"); <file_sep>key.store=/home/kuba/.android/release.keystore key.alias=release key.store.password=<PASSWORD> key.alias.password=<PASSWORD> <file_sep> <NAME> ============= npm install cordova platform add android Requirements ------------ * node.js * Apache Ant * Android SDK * Android SDK build tools * Android SDK platform tools <file_sep>angular.module("BeskidSlaski") .controller("BeskidSlaskiController", function ($scope, $materialSidenav, $geolocation) { $scope.layers = { position: false, peaks: false, shelters: false, paths: false }; $scope.toggleLeft = function() { $materialSidenav("left").toggle(); }; $scope.$watch("layers.position", function (visible) { if (visible) { $scope.watchId = $geolocation.watchPosition({ enableHighAccuracy: true }); } else { $geolocation.clearWatch($scope.watchId); } }); $scope.position = $geolocation.position.coords; });
c368f22f2a625ce6a750f668fe9e597c36d7ab08
[ "JavaScript", "INI", "Markdown", "Shell" ]
6
JavaScript
pwittchen/beskid-slaski
8610bec42d7c1f260bbf904ae52eea3e9bbd245b
84ebfded1639b64655d646a977455daca14be5f6
refs/heads/master
<repo_name>XUEJS/info-center<file_sep>/public/js/bounce.js 'use strict'; $(function () { var start = moment().subtract(29, 'days'); var end = moment(); var type='web'; if(location.pathname=='/info/bounce' && $('#productsChart')){ $('#demo').daterangepicker({ startDate: start, endDate: end, "opens": "left", ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }, cb); cb(start, end); //Init(); }; function cb(start, end) { console.log(start.format('l') + ' - ' + end.format('l')); $('#demo input').val(start.format('l') + ' - ' + end.format('l')); Init(start,end); } function Init(start,end) { var opt = {}; opt.begin_time = parseInt(start.format('X')); opt.end_time = parseInt(end.format('X')); console.log(opt); var optionWeb = null; var optionTouch = null; var myChart = echarts.init(document.getElementById('productsChart')); $('[data-value="web"]').on('click', function () { myChart.setOption(optionWeb); type='web'; }); $('[data-value="touch"]').on('click', function () { myChart.setOption(optionTouch); type='touch'; }); $.post('http://statistic.xueersi.com/OperationIndex/searchBounce', opt, function (data) { //$('.result').html(data); function compare(value1, value2) { if (value1.timestamp < value2.timestamp) { return -1; } else if (value1.timestamp > value2.timestamp) { return 1; } else { return 0; } } data = JSON.parse(data); data = data.data; //data.sort(compare); var yTime=[],bounceWeb=[],bounceTouch=[]; for(var name in data){ yTime.push(name); var item = data[name][0]; bounceWeb.push((item.bounce_count/item.pv*100).toFixed(1)); bounceTouch.push((item.mbounce_count/item.mpv*100).toFixed(1)); } //data.forEach(function (item) { // var date=transforTime(item.timestamp); // yTime.push(date); // bounceWeb.push((item.bounce_count/item.pv*100).toFixed(1)); // bounceTouch.push((item.mbounce_count/item.mpv*100).toFixed(1)); //}); //console.log(yTime); console.log(data); optionWeb = { tooltip: { trigger: 'axis' }, legend: { data: ['首页跳出率'] }, grid: { left: '3%', right: '4%', //bottom: '3%', containLabel: true }, toolbox: { feature: { dataZoom: {}, //restore: {}, //saveAsImage: {}, dataView: { readOnly: true, optionToContent: function(opt) { var axisData = opt.xAxis[0].data; var series = opt.series; cvsString='日期,'+series[0].name+'\n'; var div = '<div style="height: 100%;overflow: auto">'; var alink='<a id="test" class="btn btn-wide btn-primary" onclick="clickDownload(this)" style="float: right" download="bounce.csv" href="#">Download</a>'; var table = '<table style="width:100%;text-align:center"><tbody><tr>' + '<td>日期</td>' + '<td>' + series[0].name + '</td>' + '</tr>'; for (var i = 0, l = axisData.length; i < l; i++) { table += '<tr>' + '<td>' + axisData[i] + '</td>' + '<td>' + series[0].data[i] + '</td>' + '</tr>'; cvsString+=axisData[i]+','+series[0].data[i]+'\n'; } table += '</tbody></table>'; div+=alink+table+'</div>'; return div; } } } }, xAxis: { type: 'category', boundaryGap: false, data: yTime, }, yAxis: { type: 'value', name:'百分之' }, series: [ { name: '首页跳出率', type: 'line', data: bounceWeb } ], dataZoom: [ { id: 'dataZoomX', type: 'slider', xAxisIndex: [0], filterMode: 'filter', }, { id: 'dataZoomY', type: 'slider', yAxisIndex: [0], filterMode: 'empty' } ] }; optionTouch = { tooltip: { trigger: 'axis' }, legend: { data: ['首页跳出率'] }, grid: { left: '3%', right: '4%', //bottom: '3%', containLabel: true }, toolbox: { feature: { dataZoom: {}, //restore: {}, //saveAsImage: {}, dataView: { readOnly: true } } }, xAxis: { type: 'category', boundaryGap: false, data: yTime }, yAxis: { type: 'value' }, series: [ { name: '首页跳出率', type: 'line', data: bounceTouch } ], dataZoom: [ { id: 'dataZoomX', type: 'slider', xAxisIndex: [0], filterMode: 'filter', }, { id: 'dataZoomY', type: 'slider', yAxisIndex: [0], filterMode: 'empty' } ] }; if(type=='web'){ myChart.setOption(optionWeb); }else{ myChart.setOption(optionTouch); } $(window).on('resize', function () { //console.log('resize'); myChart.resize() }); }); }; }); //$( // function () { // init(); // } //) <file_sep>/public/js/commit.js 'use strict'; $( function () { var grade_names, subject_names, sort_flag, term_id,counselor_id; var type = 0; var searchUrl = ['/HomeworkIndex/searchByFlag', '/HomeworkIndex/searchBySubject', '/HomeworkIndex/searchByGrade', '/HomeworkIndex/searchByCounselor']; var queryFilter={}; var myChart; if (location.pathname == '/info/commit' && $('#productsChart')) { $('#dropFilter1 .dropFilterConfirm').on('click', function () { console.log('click confirm'); grade_names = $(this).parents('.dropFilterBox').find('select[name="grade_names"]').val(); subject_names = $(this).parents('.dropFilterBox').find('select[name="subject_names"]').val(); sort_flag = $(this).parents('.dropFilterBox').find('select[name="sort_flag"]').val(); term_id = $(this).parents('.dropFilterBox').find('select[name="term_id"]').val(); counselor_id = $(this).parents('.dropFilterBox').find('input[name="counselor_id"]').val(); console.log('grade_names:' + grade_names + ',subject_names:' + subject_names + ',sort_flag:' + sort_flag + ',term_id:' + term_id+',counselor_id:'+counselor_id); if(grade_names!='全部'){ queryFilter.grade_names=grade_names; } if(subject_names!='全部'){ queryFilter.subject_names=subject_names; } if(sort_flag!='全部'){ queryFilter.sort_flag=sort_flag; } if(term_id!='全部'){ switch(term_id){ case '春季班': queryFilter.term_id=1; break; case '暑假班': queryFilter.term_id=2; break; case '秋季班': queryFilter.term_id=3; break; case '寒假班': queryFilter.term_id=4; break; } } if (counselor_id){ queryFilter.counselor_id=counselor_id; } Init(type,queryFilter); }); $('#dropFilter1 .resetFilter').on('click', function () { resetFilter(); }); //cb(start, end); setDisable(['sort_flag']); Init(type, queryFilter); $('[id="radio1"]').on('click', function () { type=0; setDisable(['sort_flag']); Init(type,queryFilter); }); $('[id="radio2"]').on('click', function () { type=1; setDisable(['subject_names']); Init(type,queryFilter); }); $('[id="radio3"]').on('click', function () { type=2; setDisable(['grade_names']); Init(type,queryFilter); }); $('[id="radio4"]').on('click', function () { type=3; setDisable(); Init(type,queryFilter); }); $(window).on('resize', function () { //console.log('resize'); myChart.resize() }); }; function Init(type, queryFilter) { var url = searchUrl[type]; var opt = {}; var xAxisName,xdata,chartType; opt.subject_names = queryFilter.subject_names; opt.grade_names = queryFilter.grade_names; opt.term_id = queryFilter.term_id; opt.counselor_id = queryFilter.counselor_id; opt.sort_flag = queryFilter.sort_flag; opt.term_id = queryFilter.term_id; console.log(opt); var option = null; myChart = echarts.init(document.getElementById('productsChart')); $.post(searchBaseUrl+url, opt, function (data) { //$('.result').html(data); function compare(value1, value2) { if (value1.sort_flag < value2.sort_flag) { return -1; } else if (value1.sort_flag > value2.sort_flag) { return 1; } else { return 0; } } data = JSON.parse(data); data = data.data; data.sort(compare); if(type==2){ // 按年级 data.forEach(function(item){ switch(item.grade_names){ case '幼升小': item.grade_num=0; break; case '一年级': item.grade_num=1; break; case '二年级': item.grade_num=2; break; case '三年级': item.grade_num=3; break; case '四年级': item.grade_num=4; break; case '五年级': item.grade_num=5; break; case '六年级': item.grade_num=6; break; case '初一': item.grade_num=7; break; case '初二': item.grade_num=8; break; case '初三': item.grade_num=9; break; case '高一': item.grade_num=10; break; case '高二': item.grade_num=11; break; case '高三': item.grade_num=12; break; } }); data.sort(function(value1, value2) { if (value1.grade_num < value2.grade_num) { return -1; } else if (value1.grade_num > value2.grade_num) { return 1; } else { return 0; } }); } console.log(data); var grade_names=[], subject_names=[], sort_flag=[], term_id=[], revisal_rate1 = [], commit_rate = [],counselor_name=[]; data.forEach(function (item) { sort_flag.push(item.sort_flag); subject_names.push(item.subject_names); grade_names.push(item.grade_names); term_id.push(item.term_id); counselor_name.push(item.counselor_name); commit_rate.push((item.sum_commit_num/item.sum_stu_num * 100).toFixed(1)); revisal_rate1.push((item.sum_revisal_num1/item.sum_stu_num * 100).toFixed(1)); }); //console.log(yTime); switch(type){ case 0: xAxisName='讲次'; xdata=sort_flag; chartType='line'; break; case 1: xAxisName='学科'; xdata=subject_names; chartType='bar'; break; case 2: xAxisName='年级'; xdata=grade_names; chartType='bar'; break; case 3: xAxisName='老师'; xdata=counselor_name; chartType='bar'; break; } option = { tooltip: { trigger: 'axis' }, legend: { //data: ['作业提交数', '作业订正数', '作业提交率', '作业订正率'] data: ['作业提交率', '作业订正率'] }, grid: { left: '4%', right: '10%', //bottom: '3%', containLabel: true }, toolbox: { feature: { dataZoom: {}, //restore: {}, //saveAsImage: {}, dataView: { readOnly: true, optionToContent: function(opt) { var axisData = opt.xAxis[0].data; var series = opt.series; cvsString=xAxisName+','+series[0].name+','+series[1].name+'\n'; var div = '<div style="height: 100%;overflow: auto">'; var alink='<a id="test" class="btn btn-wide btn-primary" onclick="clickDownload(this)" style="float: right" download="'+xAxisName+'.csv" href="#">Download</a>'; var table = '<table style="width:100%;text-align:center"><tbody><tr>' + '<td>'+xAxisName+'</td>' + '<td>' + series[0].name + '</td>' + '<td>' + series[1].name + '</td>' + '</tr>'; for (var i = 0, l = axisData.length; i < l; i++) { table += '<tr>' + '<td>' + axisData[i] + '</td>' + '<td>' + series[0].data[i] + '</td>' + '<td>' + series[1].data[i] + '</td>' + '</tr>'; cvsString+=axisData[i]+','+series[0].data[i]+','+series[1].data[i]+'\n'; } table += '</tbody></table>'; div+=alink+table+'</div>'; return div; } } } }, xAxis: { type: 'category', //boundaryGap: false, data: xdata, name: xAxisName, nameLocation: 'start', nameGap:35 //alignWithLabel:true }, yAxis: [ { type: 'value', name: '作业提交、修改率', axisLabel: { formatter: '{value} %' } }, ], series: [ { name: '作业提交率', type: chartType, data: commit_rate, }, { name: '作业订正率', type: chartType, data: revisal_rate1, markLine:{ data: [ { name: '订正率', yAxis: 75 } ] } }, ], dataZoom: [ { id: 'dataZoomX', type: 'slider', xAxisIndex: [0], filterMode: 'filter', }, { id: 'dataZoomY', type: 'slider', yAxisIndex: [0], filterMode: 'empty' } ] }; myChart.setOption(option); }); }; function resetFilter(){ $('select[name="grade_names"]').val('全部'); $('select[name="subject_names"]').val('全部'); $('select[name="sort_flag"]').val('全部'); $('select[name="term_id"]').val('全部'); $('input[name="counselor_id"]').val(''); queryFilter={}; } function setDisable(disList){ var selectList=$('#dropFilter1 select'); for(var i=0;i<selectList.length;i++){ $(selectList[i]).attr('disabled',false); } if(disList){ disList.forEach(function(item){ $('select[name="'+item+'"]').val('全部'); $('select[name="'+item+'"]').attr("disabled",true); }) } } }); //$( // function () { // init(); // } //) <file_sep>/routes/validate.js let express = require('express'), router = express.Router(); // 用户登录权限验证 router.get( /^\/(info)?(\/\w+)?$/, function ( req, res, next ) { console.log(req.session); if (req.session.login) { return next(); }else{ res.redirect('/users/login'); } }); module.exports = router;<file_sep>/gulpfile.js var gulp = require('gulp'); var cleanCSS = require('gulp-clean-css'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var pump = require('pump'); var ngAnnotate = require('gulp-ng-annotate'); var stripDebug = require('gulp-strip-debug'); var htmlmin = require('gulp-htmlmin'); gulp.task('default', [ 'minify-dependency-css', 'minify-packet-css', 'minify-main-css', 'compress-dependency-js', 'compress-packet-js', 'compress-lib-js']); gulp.task('minify-dependency-css', function () { return gulp.src([ 'public/bower_components/bootstrap/dist/css/bootstrap.min.css', 'public/bower_components/font-awesome/css/font-awesome.min.css', 'public/bower_components/themify-icons/themify-icons.css', 'public/bower_components/flag-icon-css/css/flag-icon.min.css', 'public/bower_components/animate.css/animate.min.css', 'public/bower_components/perfect-scrollbar/css/perfect-scrollbar.min.css', 'public/bower_components/switchery/dist/switchery.min.css', 'public/bower_components/seiyria-bootstrap-slider/dist/css/bootstrap-slider.min.css', 'public/bower_components/ladda/dist/ladda-themeless.min.css', 'public/bower_components/slick.js/slick/slick.css', 'public/bower_components/slick.js/slick/slick-theme.css', ]) .pipe(cleanCSS()) .pipe(concat('dependency.css')) .pipe(gulp.dest('public/dist/css')); }); gulp.task('minify-packet-css', function () { return gulp.src([ 'public/assets/css/styles.css', 'public/assets/css/plugins.css' ]) .pipe(cleanCSS()) .pipe(concat('packet.css')) .pipe(gulp.dest('public/dist/css')); }); gulp.task('minify-main-css', function () { return gulp.src([ 'public/css/lib/daterangepicker.css', 'public/css/main.css' ]) .pipe(cleanCSS()) .pipe(concat('main.css')) .pipe(gulp.dest('public/dist/css')); }); gulp.task('compress-dependency-js', function () { return gulp.src([ 'public/bower_components/jquery/dist/jquery.min.js', 'public/bower_components/bootstrap/dist/js/bootstrap.min.js', 'public/bower_components/components-modernizr/modernizr.js', 'public/bower_components/js-cookie/src/js.cookie.js', 'public/bower_components/perfect-scrollbar/js/perfect-scrollbar.jquery.min.js', 'public/bower_components/jquery-fullscreen/jquery.fullscreen-min.js', 'public/bower_components/switchery/dist/switchery.min.js', 'public/bower_components/jquery.knobe/dist/jquery.knob.min.js', 'public/bower_components/seiyria-bootstrap-slider/dist/bootstrap-slider.min.js', 'public/bower_components/slick.js/slick/slick.min.js', 'public/bower_components/jquery-numerator/jquery-numerator.js', 'public/bower_components/ladda/dist/spin.min.js', 'public/bower_components/ladda/dist/ladda.min.js', 'public/bower_components/ladda/dist/ladda.jquery.min.js', ]) .pipe(concat('dependency.js')) .pipe(uglify()) .pipe(gulp.dest('public/dist/js')); }); gulp.task('compress-packet-js', function () { return gulp.src([ 'public/assets/js/selectFx/classie.js', 'public/assets/js/selectFx/selectFx.js', ]) .pipe(concat('packet.js')) .pipe(uglify()) .pipe(gulp.dest('public/dist/js')); }); gulp.task('compress-lib-js', function () { return gulp.src([ 'public/js/lib/vue.js', 'public/js/lib/echarts.js', 'public/js/lib/moment.min.js', 'public/js/lib/daterangepicker.js', ]) .pipe(concat('lib.js')) .pipe(uglify()) .pipe(gulp.dest('public/dist/js')); }); gulp.task('compress-angular', function () { return gulp.src(['static/jzhApp.js', 'static/controller/*.js', 'static/services/*.js', 'static/directives/*.js', 'static/filters/*.js']) .pipe(concat('main.js')) .pipe(stripDebug()) .pipe(ngAnnotate()) .pipe(uglify()) .pipe(gulp.dest('dist/js')); }); gulp.task('minify-html', function () { return gulp.src('index.html') .pipe(htmlmin({collapseWhitespace: true, removeComments: true})) .pipe(gulp.dest('dist')) }); <file_sep>/public/js/set-sidebarnav.js $(function () { var ulNavLiA=$('#sidebar-nav li a'); //console.log(ulNavLiA); for(var i=0;i<ulNavLiA.length;i++){ //console.log(i); //console.log($(ulNavLiA[i]).attr('href')); var element=$(ulNavLiA[i]); if(element.attr('href')==location.pathname){ if(element.parent().parent().hasClass('sub-menu')){ element.parent().addClass('active'); element.parent().parent().parent().addClass('open').addClass('active'); element.parent().parent().parent().parent().parent().addClass('open').addClass('active'); }else{ element.parent().addClass('active'); element.parent().addClass('open'); } } } var sidebarNav = new Vue( { el: '#sidebar-nav', data: { title:{name:'哈哈啦啦'} } } ) })<file_sep>/routes/users.js let express = require('express'); let router = express.Router(); let querystring = require('querystring'); let http=require('http'); router.get('/login', function (req, res, next) { res.render('login'); console.log(req.session) }); router.get('/logout', function (req, res, next) { //res.render('login'); req.session.login=false; console.log(req.session); res.redirect('/users/login'); }); router.post('/login', function (req, res, next) { console.log(req.body); let postData = {}; postData.username=req.body.username; postData.password=<PASSWORD>; //postDataString=JSON.stringify(postData); //http://searchapi.xueersi.com/statisticuser let postDataString=querystring.stringify(postData); let options = { hostname: 'statistic.xueersi.com', //hostname: '192.168.127.12', //hostname: 'localhost', port: 80, //path: '/users/login', path: '/login/login', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postDataString) } }; let reqPost = http.request(options, (res1) => { console.log(`Got response: ${res1.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res1.headers)}`); res1.setEncoding('utf8'); let _data = [], data; res1.on('data', function (tmp) { console.log(('data:' + tmp)); _data.push(tmp); }); res1.on("end", function () { data = _data.join(""); data=JSON.parse(data); console.log(data); if(data.count>0){ req.session.login=true; req.session.authority_ids=data.data[0].authority_ids; req.session.like_ids=data.data[0].like_ids; req.session.username=data.data[0].username; console.log(req.session); res.end('success'); }else{ res.end('wrong'); } }); } ); reqPost.on('error', (e) => { console.log(`problem with request: ${e.message}`); }); // write data to request body console.log(`postdatastring:`); console.log(postDataString); reqPost.write(postDataString); reqPost.end(); }); module.exports = router; <file_sep>/public/js/config.js var searchBaseUrl='http://statistic.xueersi.com'; var cvsString='';<file_sep>/routes/index.js let express = require('express'); let http=require('http'); let router = express.Router(); router.get('/', (req, res, next) => { //res.render('main', { username: req.session.username,layout: 'layout/index' }); res.redirect('/info/index'); //http.get('http://localhost:3001/',(res1) => { // console.log(`Got response: ${res.statusCode}`); // let html = [],data; // res1.on('data',function(tmp){ // console.log(('data'+tmp)); // html.push(tmp); // }); // res1.on("end",function(){ // data=html.join(""); // console.log(data); // res.render('index', { title: data }); // }); //}) }); router.get('/test', (req, res, next) => { console.log('haja2'); console.log(req.session); res.render('main', { username: req.session.username,layout: 'layout/index' }); }); module.exports = router; <file_sep>/public/js/util.js function transforTime(timestamp){ var date=new Date(parseInt(timestamp)*1000); var month=date.getMonth()+1; var day=date.getDate(); var stringValue; if(day<10){ stringValue='.0'+day; }else{ stringValue='.'+day; } if(month<10){ return '0'+month+stringValue; }else{ return ''+month+stringValue; } return ; } function clickDownload(aLink) { console.log('cvsString:'+cvsString); var str = cvsString; str = encodeURIComponent(str); aLink.href = "data:text/csv;charset=utf-8,\ufeff"+str; $(aLink).removeAttr('onclick'); //aLink.click(); }<file_sep>/public/js/dropFilter.js $( function(){ $('.dropFilter .dropClick').on('click',function(){ console.log('click'); console.log($(this).data('dropid')); var dropId=$(this).data('dropid') $('#'+dropId+' .dropFilterBox').toggle(); }); //$('.dropFilter>.dropFilterBox .dropClick').on('click',function(){ // console.log('click'); // console.log(this); // $(this).parent().find('.dropFilterBox').toggle(); //}); //$('.dropFilter .dropClick').on('click',function(){ // console.log('click'); // console.log(this); // $(this).parent().find('.dropFilterBox').toggle(); //}); } )<file_sep>/public/js/index.js 'use strict'; $(function () { var start = moment().subtract(29, 'days'); var end = moment(); var type='web'; var typePV='pv'; if(location.pathname=='/info/index' && $('#productsChart')){ $('#daterangepicker').daterangepicker({ startDate: start, endDate: end, "opens": "left", ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }, cb); cb(start, end); //Init(start,end); }; function cb(start, end) { console.log(start.format('l') + ' - ' + end.format('l')); $('#daterangepicker input').val(start.format('l') + ' - ' + end.format('l')); Init(start,end); } function Init(start,end) { var opt = {}; opt.begin_time = parseInt(start.format('X')); opt.end_time = parseInt(end.format('X')); console.log(opt); var myChart = echarts.init(document.getElementById('productsChart')); var yTime = []; var pvWeb0 = [];//其他 var pvWeb1 = [];//主站首页 var pvWeb2 = [];//主战筛选页 var pvWeb3 = [];//主站课程详情页 var pvWeb4 = [];//学习报告 var uvWeb0 = []; var uvWeb1 = []; var uvWeb2 = []; var uvWeb3 = []; var uvWeb4 = []; var pvTouch0 = [];//触屏首页 var pvTouch1 = [];//触屏筛选页 var pvTouch2 = [];//触屏课程详情页 var pvTouch3 = [];//触屏其他 var uvTouch0 = []; var uvTouch1 = []; var uvTouch2 = []; var uvTouch3 = []; var pvWeb=getOptions('日期',yTime, [ { name: '主站主页', type: 'line', data: pvWeb1 }, { name: '主站筛选页', type: 'line', data: pvWeb2 }, { name: '主站课程详情页', type: 'line', data: pvWeb3 }, { name: '学习报告', type: 'line', data: pvWeb4 }, { name: '其他', type: 'line', data: pvWeb0 } ]); var uvWeb=getOptions('日期',yTime, [ { name: '主站主页', type: 'line', data: uvWeb1 }, { name: '主站筛选页', type: 'line', data: uvWeb2 }, { name: '主站课程详情页', type: 'line', data: uvWeb3 }, { name: '学习报告', type: 'line', data: uvWeb4 }, { name: '其他', type: 'line', data: uvWeb0 } ]); var pvTouch=getOptions('日期',yTime,[ { name: '触屏主页', type: 'line', data: pvTouch0 }, { name: '触屏筛选页', type: 'line', data: pvTouch1 }, { name: '触屏课程详情页', type: 'line', data: pvTouch2 }, { name: '其他', type: 'line', data: pvTouch3 } ]); var uvTouch=getOptions('日期',yTime,[ { name: '触屏主页', type: 'line', data: uvTouch0 }, { name: '触屏筛选页', type: 'line', data: uvTouch1 }, { name: '触屏课程详情页', type: 'line', data: uvTouch2 }, { name: '其他', type: 'line', data: uvTouch3 } ]); $('[data-value="web"]').on('click', function () { type='web'; myChart.dispose(); myChart = echarts.init(document.getElementById('productsChart')); if(typePV=='pv'){ myChart.setOption(pvWeb); }else{ myChart.setOption(uvWeb); } }); $('[data-value="touch"]').on('click', function () { type='touch'; myChart.dispose(); myChart = echarts.init(document.getElementById('productsChart')); if(typePV=='pv'){ myChart.setOption(pvTouch); }else{ myChart.setOption(uvTouch); } }); $('[id="radio1"]').on('click', function () { typePV='pv'; myChart.dispose(); myChart = echarts.init(document.getElementById('productsChart')); if(type=='web'){ myChart.setOption(pvWeb); } else{ myChart.setOption(pvTouch); } }); $('[id="radio2"]').on('click', function () { typePV='uv'; myChart.dispose(); myChart = echarts.init(document.getElementById('productsChart')); if(type=='web'){ myChart.setOption(uvWeb); } else{ myChart.setOption(uvTouch); } }); $.post('http://statistic.xueersi.com/OperationIndex/searchView', opt, function (data) { data = JSON.parse(data); data = data.data; for(var item in data){ yTime.push(item); var uv=0; var uv2=0; var dataTmp=data[item]; for(var i=0;i<7;i++){ var pvItem=dataTmp[i]; switch(i){ case 0: if (pvItem){ pvWeb0.push(pvItem.pv); uvWeb0.push(pvItem.uv); }else{ pvWeb0.push(0); uvWeb0.push(0); } break; case 1: if (pvItem){ pvWeb1.push(pvItem.pv); uvWeb1.push(pvItem.uv); }else{ pvWeb1.push(0); uvWeb1.push(0); } break; case 2: if (pvItem){ pvTouch0.push(pvItem.pv); uvTouch0.push(pvItem.uv); }else{ pvTouch0.push(0); uvTouch0.push(0); } break; case 3: if (pvItem){ pvWeb2.push(pvItem.pv); uvWeb2.push(pvItem.uv); }else{ pvWeb2.push(0); uvWeb2.push(0); } break; case 4: if (pvItem){ pvTouch1.push(pvItem.pv); uvTouch1.push(pvItem.uv); }else{ pvTouch1.push(0); uvTouch1.push(0); } break; case 5: if (pvItem){ pvWeb3.push(pvItem.pv); uvWeb3.push(pvItem.uv); }else{ pvWeb3.push(0); uvWeb3.push(0); } break; case 6: if (pvItem){ pvTouch2.push(pvItem.pv); uvTouch2.push(pvItem.uv); }else{ pvTouch2.push(0); uvTouch2.push(0); } break; } } var category7=dataTmp[7]; var category8=dataTmp[8]; if(category7&&category8){ pvWeb4.push(category7.pv); uvWeb4.push(category7.uv); pvTouch3.push(category8.pv); uvTouch3.push(category8.uv); }else if(category7&&category7.category==7){ pvWeb4.push(category7.pv); uvWeb4.push(category7.uv); pvTouch3.push(0); uvTouch3.push(0); } else if(category7&&category7.category==8){ pvWeb4.push(0); uvWeb4.push(0); pvTouch3.push(category8.pv); uvTouch3.push(category8.uv); }else{ pvWeb4.push(0); uvWeb4.push(0); pvTouch3.push(0); uvTouch3.push(0); } } //console.log(yTime); //console.log(data); if(type=='web'&&typePV=='pv'){ myChart.setOption(pvWeb); }else if(type=='web'&&typePV=='uv'){ myChart.setOption(uvWeb); }else if(type=='touch'&&typePV=='uv'){ myChart.setOption(uvTouch); }else if(type=='touch'&&typePV=='pv'){ myChart.setOption(pvTouch); } $(window).on('resize', function () { myChart.resize() }); }); }; function getOptions(xname,xdata,series,ydatas){ var length=series.length; var ynames=[]; series.forEach(function(item){ ynames.push(item.name); }) //var csvName,tbName, return{ tooltip: { trigger: 'axis' }, legend: { data: ynames }, grid: { left: '3%', right: '4%', //bottom: '3%', containLabel: true }, toolbox: { feature: { dataZoom: {}, //restore: {}, //saveAsImage: {}, dataView: { readOnly: true, optionToContent: function(opt) { var axisData = opt.xAxis[0].data; var series = opt.series; //表头 cvsString='日期' for(var i=0;i<length-1;i++){ cvsString+=','+series[i].name; } cvsString+=','+series[length-1].name+'\n'; var div = '<div style="height: 100%;overflow: auto">'; var alink='<a id="test" class="btn btn-wide btn-primary" onclick="clickDownload(this)" style="float: right" download="pv&uv.csv" href="#">Download</a>'; var table = '<table style="width:100%;text-align:center"><tbody><tr>' + '<td>'+xname+'</td>'; for(var i=0;i<length-1;i++){ table+='<td>' + series[i].name + '</td>'; } table+='<td>' + series[length-1].name + '</td>' + '</tr>'; //表数据 for (var i = 0, l = axisData.length-1; i < l; i++) { table += '<tr>' + '<td>' + axisData[i] + '</td>' cvsString+=axisData[i]; for(var n=0;n<length-1;n++){ table+='<td>' + series[n].data[i] + '</td>'; cvsString+=','+series[n].data[i]; } table+='<td>' + series[length-1].data[i] + '</td>' + '</tr>'; cvsString+=','+series[length-1].data[i]+'\n'; } table += '</tbody></table>'; div+=alink+table+'</div>'; return div; } } } }, xAxis: { type: 'category', boundaryGap: false, data: xdata, }, yAxis: { type: 'value' }, series: series, dataZoom: [ { id: 'dataZoomX', type: 'slider', xAxisIndex: [0], filterMode: 'filter', }, { id: 'dataZoomY', type: 'slider', yAxisIndex: [0], filterMode: 'empty' } ] }; } }); //$( // function () { // init(); // } //)
7cdd790e880106334be905d9a4b3382e7979339b
[ "JavaScript" ]
11
JavaScript
XUEJS/info-center
6a6c0688175cbf888fe3b2c3859a297069a3c497
2f2d0f7ad94f76be5897e6dd5db9ef98d6cf73c3
refs/heads/master
<file_sep>#!/usr/bin/env bash # at the point a makefile is probably the sensible choice set -o errexit set -o nounset set -o pipefail cd $(dirname "$BASH_SOURCE")/.. source ./buildenv/repo make function release_dev() { docker tag cassandra-operator:latest "${REGISTRY}/cassandra-operator:latest-dev" docker tag cassandra-sidecar:latest "${REGISTRY}/cassandra-sidecar:latest-dev" docker tag cassandra-3.11.7:latest "${REGISTRY}/cassandra-3.11.7:latest-dev" docker tag cassandra-4.0-beta1:latest "${REGISTRY}/cassandra-4.0-beta1:latest-dev" } function release_prod() { docker tag cassandra-operator:latest "${REGISTRY}/cassandra-operator:${TAG}" docker tag cassandra-operator:latest "${REGISTRY}/cassandra-operator:latest" docker tag cassandra-sidecar:latest "${REGISTRY}/cassandra-sidecar:${TAG}" docker tag cassandra-sidecar:latest "${REGISTRY}/cassandra-sidecar:latest" docker tag cassandra-3.11.7:latest "${REGISTRY}/cassandra-3.11.7:${TAG}" docker tag cassandra-3.11.7:latest "${REGISTRY}/cassandra-3.11.7:latest" docker tag cassandra-4.0-beta1:latest "${REGISTRY}/cassandra-4.0-beta1:${TAG}" docker tag cassandra-4.0-beta1:latest "${REGISTRY}/cassandra-4.0-beta1:latest" } if [ "${1}" = "dev" ]; then release_dev elif [ "${1}" = "prod" ]; then release_prod fi
b061295d33c17bf97f7f4c01de6daf8cb4b4755c
[ "Shell" ]
1
Shell
efim-a-efim/cassandra-operator
0d0147cdffdd8c40f889547f72828b42e64c6a4d
24a945f66362db6d14927de93be7818e037e1270
refs/heads/master
<file_sep>--- layout: doc type: lyrics permalink: /lyrics/brian-eno-by-this-river.html title: by this river author: <NAME> version: brian eno genre: rock description: https://en.wikipedia.org/wiki/Brian_Eno --- <pre><span>C</span> Here we are <span>C</span> Stuck by this river, <span>Am</span> You and I <span>Am</span> Underneath a sky that's ever falling <span>F</span> down, down, down <span>Am</span> Ever falling down. <span>C</span> Through the day <span>C</span> As if on an ocean <span>Am</span> Waiting here, <span>Am</span> Always failing to remember why we <span>F</span> came, came, came: <span>Am</span> I wonder why we came. <span>C</span> You talk to me <span>C</span> as if from a distance <span>Am</span> And I reply <span>Am</span> With impressions chosen from another <span>F</span> time, time, time, <span>Am</span> From another time.</pre> <file_sep><!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE11"> <title>Lyrics</title> <link rel="icon" type="image/png" href="dist/img/favicon.ico"> <link rel="stylesheet" type="text/css" href="/dist/css/styles.min.css"> </head> <body> <div class="container"> <div><a href="/index.html">home</a> <main id="main-content"> <!-- --> <div class="container"> <h1 class="title">brian eno - julie with</h1> <p class="author">By <NAME></p> <p>https://en.wikipedia.org/wiki/Brian_Eno</p> <button id="my-button">transpose</button> </div> <!-- Html Elements for Search --> <div id="search-container"> <div class="" style="text-align:right;"><input type="text" id="search-input" placeholder="search..."></div> <ul id="results-container"></ul> </div> <!-- Script pointing to search-script.js --> <script src="/dist/js/simple-search.min.js" type="text/javascript"></script> <!-- Configuration --> <script> SimpleJekyllSearch({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), json: '/search.json' }) </script> <pre class="_1YgOS" style="font-size: 15px; font-family: &quot;Roboto Mono&quot;, monospace;">[Intro] <span>F</span> <span>Am</span> <span>F</span> <span>Am</span> <span>F</span> <span>Am</span> <span>F</span> <span>Am</span> <span>D7sus2</span> [Verse 1] <span>F</span> I am on an open sea <span>Am</span> Just drifting as the hours go slowly by <span>F</span> Julie with her open blouse <span>Am</span> Is gazing up into the empty sky [Chorus] <span>G</span> <span>Em</span> <span>F</span> Now it seems to be so strange here <span>G</span> <span>Em</span> Now it's so blue <span>F</span> <span>C</span> <span>D7sus2</span> The still sea is darker than before [instrumental guitar] <span>D7sus2</span> <span>F</span> <span>Am</span> [Instrumental synth] <span>D</span> <span>G</span> <span>D</span> <span>G</span> <span>D</span> <span>G</span> <span>D</span> <span>Dm</span> <span>D</span> <span>F</span> <span>Am</span> [Verse 2] <span>F</span> No wind disturbs our colored sail <span>Am</span> The radio is silent, so are we <span>F</span> Julie's head is on her arm <span>Am</span> Her fingers brush the surface of the sea [Chorus] <span>G</span> <span>Em</span> <span>F</span> Now I wonder if we'll be seen, here <span>G</span> <span>Em</span> Or if time has left us all alone <span>F</span> <span>C</span> <span>D7sus2</span> The still sea is darker than before [Instrumental <span>F</span> <span>Am</span> <span>F</span> <span>Am</span> <span>F</span> <span>Am</span> <span>F</span> <span>Am</span> <span>F</span> <span>Am</span></pre> </main> </div> </div> <script src="/dist/js/transpose.min.js"></script> </body> </html> <file_sep><!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE11"> <title>Lyrics</title> <link rel="icon" type="image/png" href="dist/img/favicon.ico"> <link rel="stylesheet" type="text/css" href="/dist/css/styles.min.css"> </head> <body> <div class="container"> <div><a href="/index.html">home</a> <main id="main-content"> <!-- --> <div class="container"> <h1 class="title">america - horse with no name</h1> <p class="author">By <NAME></p> <p>https://en.wikipedia.org/wiki/A_Horse_with_No_Name</p> <button id="my-button">transpose</button> </div> <!-- Html Elements for Search --> <div id="search-container"> <div class="" style="text-align:right;"><input type="text" id="search-input" placeholder="search..."></div> <ul id="results-container"></ul> </div> <!-- Script pointing to search-script.js --> <script src="/dist/js/simple-search.min.js" type="text/javascript"></script> <!-- Configuration --> <script> SimpleJekyllSearch({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), json: '/search.json' }) </script> <pre>[Verse 1] <span>Em</span> <span>D6/9</span> On the first part of the journey <span>Em</span> <span>D6/9</span> I was lookin at all the life <span>Em</span> <span>D6/9</span> There were plants and birds and rocks and things <span>Em</span> <span>D6/9</span> There were sand and hills and rings <span>Em</span> <span>D6/9</span> The first thing I met was a fly with a buzz <span>Em</span> <span>D6/9</span> and the sky with no clouds <span>Em</span> <span>D6/9</span> the heat was hot and the ground was dry <span>Em</span> <span>D6/9</span> but the air was full of sound [Chorus] <span>Em9</span> <span>Dmaj9</span> I've been through the desert on a horse with no name <span>Em9</span> <span>Dmaj9</span> it felt good to be out of the rain <span>Em9</span> <span>Dmaj9</span> in the desert you can remember your name <span>Em9</span> <span>Dmaj9</span> 'cause there ain't no one for to give you no pain <span>Em9</span> <span>Dmaj9</span> La la la la lala la lala <span>Em9</span> <span>Dmaj9</span> la la la [Verse 2] <span>Em</span> <span>D6/9</span> After two days in the desert sun <span>Em</span> <span>D6/9</span> my skin began to turn red <span>Em</span> <span>D6/9</span> After three days in the desert fun <span>Em</span> <span>D6/9</span> I was looking at a river bed <span>Em</span> <span>D6/9</span> And the story it told of a river that flowed <span>Em</span> <span>D6/9</span> made me sad to think it was dead [Chorus] <span>Em9</span> <span>Dmaj9</span> I've been through the desert on a horse with no name <span>Em9</span> <span>Dmaj9</span> it felt good to be out of the rain <span>Em9</span> <span>Dmaj9</span> in the desert you can remember your name <span>Em9</span> <span>Dmaj9</span> 'cause there ain't no one for to give you no pain <span>Em9</span> <span>Dmaj9</span> la la la la lala la lala <span>Em9</span> <span>Dmaj9</span> la la la [Verse 3] <span>Em</span> <span>D6/9</span> After nine days I let the horse run free <span>Em</span> <span>D6/9</span> 'cause the desert had turned to sea <span>Em</span> <span>D6/9</span> there were plants and birds and rocks and things <span>Em</span> <span>D6/9</span> there were sand and hills and rings <span>Em</span> <span>D6/9</span> The ocean is a desert with it's life underground <span>Em</span> <span>D6/9</span> and the perfect disguise above <span>Em</span> <span>D6/9</span> Under the cities lies a heart made of ground <span>Em</span> <span>D6/9</span> but the humans will give no love [Chorus] <span>Em9</span> <span>Dmaj9</span> I've been through the desert on a horse with no name <span>Em9</span> <span>Dmaj9</span> it felt good to be out of the rain <span>Em9</span> <span>Dmaj9</span> in the desert you can remember your name <span>Em9</span> <span>Dmaj9</span> 'cause there ain't no one for to give you no pain <span>Em9</span> <span>Dmaj9</span> la la la la lala la lala <span>Em9</span> <span>Dmaj9</span> la la la </pre> </main> </div> </div> <script src="/dist/js/transpose.min.js"></script> </body> </html> <file_sep>'use strict'; var gulp = require('gulp'); var shell = require('gulp-shell'); var util = require('gulp-util'); var plumber = require('gulp-plumber'); var rename = require('gulp-rename'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var watch = require('gulp-watch'); var cp = require('child_process'); //var scsslint = require('gulp-scss-lint'); var browserSync = require('browser-sync').create(); var sass = require('gulp-sass'); var autoprefixer = require('gulp-autoprefixer'); var sourcemaps = require('gulp-sourcemaps'); var jshint = require('gulp-jshint'); var stylish = require('jshint-stylish'); gulp.task('style', () => { return gulp.src('_scss/*.scss') .pipe(plumber({ errorHandler: function (err) { console.log(err); this.emit('end'); } })) .pipe(sourcemaps.init()) .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError)) .pipe(rename({suffix: '.min'})) .pipe(sourcemaps.write()) .pipe(autoprefixer({ browsers: ["last 50 versions", "ie >= 9"], cascade: false })) .pipe(gulp.dest('dist/css')) // .pipe(browserSync.stream()); }); // gulp.task('sprites', function () { // return gulp.src('assets/svg/*.svg') // .pipe(svgSprite({mode: "symbols"})) // .pipe(gulp.dest("dist")); // }); gulp.task('script-lib', () => { return gulp.src('_js/lib/*.js') .pipe(plumber({ errorHandler: function (err) { console.log(err); this.emit('end'); } })) .pipe(concat('lib.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist/js')); }); gulp.task('script-kakudo', () => { return gulp.src('_js/kakudo/*.js') .pipe(plumber({ errorHandler: function (err) { console.log(err); this.emit('end'); } })) .pipe(concat('kakudo.js')) .pipe(gulp.dest('dist/js')) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('dist/js')); }); gulp.task('script-site', () => { return gulp.src('_js/*.js') .pipe(plumber({ errorHandler: function (err) { console.log(err); this.emit('end'); } })) .pipe(jshint()) .pipe(jshint.reporter(stylish)) .pipe(rename({suffix: '.min'})) .pipe(uglify()) .pipe(gulp.dest('dist/js')); }); gulp.task('scss-lint', function() { return gulp.src('/scss/*.scss') .pipe(scsslint()); }); gulp.task('build', shell.task(['bundle exec jekyll build --config _config.yml,_config_dev.yml'])); gulp.task('reload', ['build'], () => { browserSync.reload(); }); gulp.task('script', ['script-lib', 'script-kakudo', 'script-site'], () => {}); gulp.task('serve', ['style', 'script', 'build'], () => { browserSync.init({ server: {baseDir: '_site/'} }); }); gulp.task('watch', () => { gulp.watch('_scss/**/*.scss', ['style']); gulp.watch('_js/**/*.js', ['script']); gulp.watch(['*.html', '_data/*', '_includes/**/*', '_js/**/*', '_layouts/*', '_scss/**/*', 'assets/**/*', 'lyrics/**/*', 'global/**/*'], ['reload']); }); gulp.task('default', ['serve', 'watch'], () => {}); <file_sep>//var toggablePanel = document.querySelectorAll('.whi--panel--collapsible'); var matches = document.querySelectorAll('span'); console.log(matches.length) var transposeValue = '1'; var ammount; function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function transposeChord(chord, amount) { var scale = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] var normalizeMap = {"Cb":"B", "Db":"C#", "Eb":"D#", "Fb":"E", "Gb":"F#", "Ab":"G#", "Bb":"A#", "E#":"F", "B#":"C"} return chord.replace(/[CDEFGAB](b|#)?/g, function(match) { var i = (scale.indexOf((normalizeMap[match] ? normalizeMap[match] : match)) + amount) % scale.length; return scale[ i < 0 ? i + scale.length : i ]; }) } //originalChord = "Bmaj7/G#"; // originalChord = "Am add9"; // originalChord = "F#dim7"; // originalChord = "F#"; // originalChord = "F#"; //var j=transposeChord(originalChord, -1) var myButton = document.getElementById('my-button'); myButton.onclick = function() { for (var i = 0; i < matches.length; i++) { var mySpan = matches[i]; myChord = capitalizeFirstLetter(matches[i].innerHTML); console.log (myChord); mySpan.innerHTML = transposeChord(myChord, 1); } } var myMenu = document.getElementById('menu'); myMenu.onclick = function() { console.log('menu'); } // //console.log('matches is ' + matches.length); // console.log('originalChord is ' + originalChord); // tokenizing = Tonal.Chord.tokenize(originalChord); // originalNote = tokenizing[0]; // chordAddOn = tokenizing[1]; // console.log ('originalNote '+originalNote); // console.log ('chordAddOn '+chordAddOn); // newNote = Tonal.transpose(originalNote, transposeValue) // console.log ('newNote '+newNote); // if (chordAddOn.indexOf('/') > -1) { // splitAddOn = chordAddOn.split('/'); // chordType = splitAddOn[0]; // chordBass = splitAddOn[1]; // if(isNaN(chordBass)){ // console.log('is not a number'); // newChordBass = Tonal.transpose(chordBass, transposeValue); // console.log ('newChordBass '+newChordBass); // } else{ // console.log('is is a numbeer '+chordBass); // } // console.log('chordType is ' + chordType); // console.log('chordBass is ' + chordBass); // // console.log('var4[1] is ' + var4[1]); // // var5 = var4[0] + '/' + Tonal.transpose(var4[1], transposeValue) // // console.log('var5 is ' + var5); // // var2[1] = var5; // } //console.log('length is ' + var2.length); // => [ "C", "maj7" ]); //console.log('array 0 = ' + var2[0]) //console.log('array 1 = ' + var2[1]) //var7 = Tonal.transpose(var2[0], "3M"); //console.log('transposing ' + var7); // => "F#" //console.log('final ' + var7 + var2[1]); var myButton = document.getElementById('my-button'); //console.log('tomal is ' + Tonal.transpose('C4', '8P')); function panelHeader(index) { var bar = toggablePanel[index]; //on return key pressed bar.onkeypress = function(e) { if (e.which == 13) { this.click(); //console.log('enter key down' + e); } } //clicking on tab bar.onclick = function() { var contentWrapper = this.nextElementSibling; //console.log (contentWrapper.clientHeight); //using firstchild would return #text if there's a white space, so... var content = contentWrapper.getElementsByTagName('div')[0]; var contentWrapperHeight = contentWrapper.clientHeight; if (this.classList.contains('whi--panel--collapsed')) { //console.log('showing-----------------'); contentWrapper.classList.remove('whi--panel--collapsed'); this.classList.remove('whi--panel--collapsed'); this.setAttribute("aria-hidden", "false"); } else { //console.log('hiding-----------------'); contentWrapper.classList.add('whi--panel--collapsed'); this.classList.add('whi--panel--collapsed'); this.setAttribute("aria-hidden", "true"); } } }; <file_sep>--- layout: doc type: lyrics permalink: /lyrics/judy-garland-somewhere-0ver-the-rainbow.html title: somewhere over the rainbow author: music by <NAME> and lyrics by <NAME> version: judy garland genre: jazz description: https://en.wikipedia.org/wiki/Over_the_Rainbow --- <pre>[Verse] <span>A</span> <span>F#m</span> <span>C#m</span> <span>D</span> <span>A</span> somewhere over the rainbow, way up high <span>D</span> <span>Dm</span> <span>A</span> <span>F#m</span> <span>Bm</span> <span>E</span> <span>A</span> theres a land that i heard of once in a lullaby <span>A</span> <span>F#m</span> <span>C#m</span> <span>D</span> <span>A</span> somewhere over the rainbow skies are blue <span>D</span> <span>Dm</span> <span>A</span> <span>F#m</span> <span>Bm</span> <span>E</span> <span>A</span> and the dreams that you dare to dream really do come true [Middle] <span>A</span> someday ill wish upon a star <span>Bm</span> <span>F#m</span> <span>Bm</span> <span>E</span> and wake up where the clouds are far behind me <span>A</span> where troubles melt like lemon drops <span>G#m</span> away above the chimney tops <span>C#m</span> <span>Bm</span> <span>E</span> thats where you'll find me [Verse] <span>A</span> <span>F#m</span> <span>C#m</span> <span>D</span> <span>A</span> somewhere over the rainbow skies are blue <span>D</span> <span>Dm</span> <span>A</span> <span>F#m</span> <span>Bm</span> <span>E</span> <span>A</span> and the dreams that you dare to dream really do come true [Middle] <span>A</span> someday ill wish upon a star <span>Bm</span> <span>F#m</span> <span>Bm</span> <span>E</span> and wake up where the clouds are far behind me <span>A</span> where troubles melt like lemon drops <span>G#m</span> away above the chimney tops <span>C#m</span> <span>Bm</span> <span>E</span> thats where you'll find me [Verse] <span>A</span> <span>F#m</span> <span>C#m</span> <span>D</span> <span>A</span> Somewhere over the rainbow, Bluebirds fly <span>D</span> <span>Dm</span> <span>A</span> <span>F#m</span> <span>Bm</span> <span>E</span> <span>A</span> Birds fly over the rainbow. Why, then oh why can't I? [outro] <span>A</span> <span>Bm</span> if happy little bluebirds fly beyond the rainbow <span>E</span> <span>A</span> why oh why can't i?</pre> <file_sep><!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE11"> <title>Lyrics</title> <link rel="icon" type="image/png" href="dist/img/favicon.ico"> <link rel="stylesheet" type="text/css" href="/dist/css/styles.min.css"> </head> <body> <div class="container"> <div><a href="/index.html">home</a> <main id="main-content"> <!-- --> <div class="container"> <h1 class="title">beatles - eleanor rigby</h1> <p class="author">By lennon & mcCartney</p> <p>https://en.wikipedia.org/wiki/Eleanor_Rigby</p> <button id="my-button">transpose</button> </div> <!-- Html Elements for Search --> <div id="search-container"> <div class="" style="text-align:right;"><input type="text" id="search-input" placeholder="search..."></div> <ul id="results-container"></ul> </div> <!-- Script pointing to search-script.js --> <script src="/dist/js/simple-search.min.js" type="text/javascript"></script> <!-- Configuration --> <script> SimpleJekyllSearch({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), json: '/search.json' }) </script> <pre> [Intro] <span>Bb</span> <span>Dm</span> Ah, look at all the lonely people <span>Bb</span> <span>Dm</span> Ah, look at all the lonely people [Verse] <span>Dm</span> <span>Bb</span> Eleanor rigby picks up the rice in the church where a wedding has been Lives in a dream <span>Dm</span> <span>Bb</span> Waits at the window, wearing the face that she keeps in a jar by the door <span>Dm</span> Who is it for? [Chorus] <span>Dm7</span> <span>Dm6</span> All the lonely people <span>Bb</span> <span>Dm</span> Where do they all come from ? <span>Dm7</span> <span>Dm6</span> All the lonely people <span>Bb</span> <span>Dm</span> Where do they all belong ? [Verse 2] <span>Dm</span> <span>Bb</span> <NAME> writing the words of a sermon that no one will hear No one comes near. <span>Dm</span> <span>Bb</span> Look at him working. darning his socks in the night when there's nobody there <span>Dm</span> What does he care? [Chorus] <span>Dm7</span> <span>Dm6</span> All the lonely people <span>Bb</span> <span>Dm</span> Where do they all come from? <span>Dm7</span> <span>Dm6</span> All the lonely people <span>Bb</span> <span>Dm</span> Where do they all belong? <span>Bb</span> <span>Dm</span> Ah, Look at all the lonely People <span>Bb</span> <span>Dm</span> Ah Look at All the lonely people [Verse 3] <span>Dm</span> <span>Bb</span> Eleanor rigby died in the church and was buried along with her name Nobody came <span>Dm</span> <span>Bb</span> Father mckenzie wiping the dirt from his hands as he walks from the grave <span>Dm</span> No one was saved [Chorus] <span>Dm7</span> <span>Dm6</span> All the lonely people <span>Bb</span> <span>Dm</span> Where do they all come from? <span>Dm7</span> <span>Dm6</span> All the lonely people <span>Bb</span> <span>Dm</span> Where do they all belong?</pre> </main> </div> </div> <script src="/dist/js/transpose.min.js"></script> </body> </html> <file_sep>--- layout: doc type: lyrics permalink: /lyrics/kamakawiwo-somewhere-over-the-rainbow.html title: somewhere over the rainbow version: kamakawiwo'ole author: music by <NAME> and lyrics by <NAME> genre: pop description: --- <pre> Intro: <span>F</span> <span>Fmaj7</span> <span>Dm</span> <span>Bb</span> <span>F</span> <span>C</span> <span>Dm</span> <span>Bb</span> <span>Bbadd9</span> <span>Bb</span> Intro part 2: <span>F</span> <span>Am</span> <span>Bb</span> <span>F</span> Oooo, oooo, oooo... <span>Bb</span> <span>A7</span> <span>Dm</span> <span>Bb</span> Oooo, oooo, oooo... Verse <span>F</span> <span>Am</span> Somewhere over the rainbow <span>Bb</span> <span>F</span> Way up high <span>Bb</span> <span>F</span> And the dreams that you dream of <span>C</span> <span>Dm</span> <span>Bb</span> Once in a lullaby... <span>F</span> <span>Am</span> Oh, somewhere over the rainbow <span>Bb</span> <span>F</span> Blue birds fly <span>Bb</span> <span>F</span> And the dreams that you dream of <span>C</span> <span>Dm</span> <span>Bb</span> Dreams really do come true... <span>F</span> Someday I'll wish upon a star <span>C</span> <span>Dm</span> <span>Bb</span> Wake up where the clouds are far behind me <span>F</span> Where trouble melts like lemon drops <span>C</span> High above the chimney tops <span>Dm</span> <span>Bb</span> That's where you'll find me <span>F</span> <span>Am</span> Oh, somewhere over the rainbow <span>Bb</span> <span>F</span> Blue birds fly <span>Bb</span> <span>F</span> And the dream that you dare to <span>C</span> <span>Dm</span> <span>Bb</span> Why oh why can't I... <span>F</span> Someday I'll wish upon a star <span>C</span> <span>Dm</span> <span>Bb</span> Wake up where the clouds are far behind me <span>F</span> Where trouble melts like lemon drops <span>C</span> High above the chimney tops <span>Dm</span> <span>Bb</span> That's where you'll find me <span>F</span> <span>Am</span> Oh, somewhere over the rainbow <span>Bb</span> <span>F</span> Way up high <span>Bb</span> <span>F</span> And the dreams that you dare to <span>Bb</span> <span>C</span> <span>Dm</span> <span>Bb</span> Why oh why can't I Intro part 2: <span>F</span> <span>Am</span> <span>Bb</span> <span>F</span> Oooo, oooo, oooo... <span>Bb</span> <span>A7</span> <span>Dm</span> <span>Bb</span> Oooo, oooo, oooo...</pre>
1f01f45fb41b06a0d2327a7e200234c2597beb88
[ "JavaScript", "HTML" ]
8
HTML
notsozen/ongaku
38e12cc2ac4ce68cd8ba405c93082a28b0fc9d73
77202b0f7a086f2e8296132cfaed066bf005095f
refs/heads/master
<file_sep><?php date("Y-m-d", time()) ?><file_sep># klizmach.github.io klizmach.github.io
54faebfe5da64ba5b551ddbfc68c740076c30d57
[ "Markdown", "PHP" ]
2
PHP
anphemouZ/12351351351324t62
749bf56a0394f6e596f744f2f8f15f11b3e9b707
9f76143694c197c04abcbb75dd8710713755a87e
refs/heads/master
<repo_name>KarolinaHajzer/clearcode_task2<file_sep>/README.md # clearcode_task2 A script that findes all (almost) buttons on website. <file_sep>/buttonz-counter.py import csv import re import sys from urllib.request import urlopen from bs4 import BeautifulSoup as bs argList = sys.argv file_with_websites_path = argList[1] counted_websites_path = argList[2] final_result = [] data_to_send = [] def doing_all_the_magic(): """ As the first argument in the command line, enter a text file, where there are urls with web pages that we want to search. As the second argument, we give the csv file to which we want to save the results. Name of th page in text file must by with http:// at the beginning e.g. http://www.boredbutton.com/ With the help of bs4 the given web page is searched in order to count the buttons. The buttons are found after the tag, type or class. Counted buttons along with the page name are saved to a csv file. """ with open(file_with_websites_path) as txt_file: address = txt_file.readlines() address = [x.strip() for x in address] for one_path in address: sauce = urlopen(one_path).read().lower() soup = bs(sauce, 'lxml') result_for_tag = soup.find_all("button") for result in result_for_tag: if result not in final_result: final_result.append(result) result_for_type_reset = soup.find_all('input', {'type': 'reset'}) for result in result_for_type_reset: if result not in final_result: final_result.append(result) result_for_type_submit = soup.find_all('input', {'type': 'submit'}) for result in result_for_type_submit: if result not in final_result: final_result.append(result) result_for_type_button = soup.find_all('input', {'type': 'button'}) for result in result_for_type_button: if result not in final_result: final_result.append(result) result_for_class_btn = soup.find_all(class_=re.compile("btn")) for result in result_for_class_btn: if result not in final_result: final_result.append(result) result_for_class_button = soup.find_all(class_=re.compile("button")) for result in result_for_class_button: if result not in final_result: final_result.append(result) final_data = [one_path, len(final_result)] data_to_send.append(final_data) with open(counted_websites_path, "w") as csvfile: writer = csv.writer(csvfile) first_row = ["address", "number_of_buttons"] writer.writerow(first_row) for x in data_to_send: writer.writerow(x) doing_all_the_magic()
c5530b080d1eb213860c6b101eaf98e29c928ab4
[ "Markdown", "Python" ]
2
Markdown
KarolinaHajzer/clearcode_task2
1eabd1fe80a5b3ff4b51417a81bd84408965e611
30a2e036620f0545e70c3d7cf779fd9b6d182f16
refs/heads/master
<file_sep>#!/bin/bash #################################################################### # Elog is a depedency of Eternal Scanner (Denveloped by peterpt) # # https://github.com/peterpt/eternal_scanner # #################################################################### #setup colors green='\033[92m' yellow='\e[0;33m' orange='\e[38;5;166m' # Default directory for eternal scanner data defdir="/usr/local/share/Eternal_Scanner" # When CTRL+C is pressed trap ctrl_c INT function ctrl_c() { kill "$PID" >/dev/null 2>&1 } echo -e "$orange" "+-------------------------+" echo -e "$orange" "|$green Metasploit IPS Checkout$orange |" echo -e "$orange" "+-------------------------+" echo -e "$orange" "|$yellow Please wait $orange |" echo -e "$orange" "+-------------------------+" # Timer start value to wait for msflog file generated by metasploit tm="0" # variable used to check in msflog for percentage a="" # Read Process ID for msfconsole generated by escan PID=$(cat $defdir/pid.tmp) # Loop start function start(){ # Define where it should be msflog file mlog="$defdir/msflog.log" # Check if msfconsole pid is running ps --pid "$PID" &>/dev/null pd="$?" # Start routine to grab the value "100% from msflog file" # In case metasploit already exited then if [ "$pd" -eq "1" ] then # Check if msflog file exists if [ -f "$mlog" ] then # open the log and search in last lines the value (Scanned)" gmsft=$(grep "Scanned" $mlog | tail -1) # Compare output with current value of variable (a) # At this point variable (a) should be at < (Scanned 90%) from msflog if [ "$gmsft" != "$a" ] then # In case the values are different then display that line (100%) and exit elog echo "$gmsft" exit 0 fi fi else # In case msflog does not exists yet then start a timing process to wait for it . # Some machines may take a while to load metasploit , and this is why this timming exists if [ ! -f "$mlog" ] then # Increase tm value + 1 from its current value tm=$((tm+1)) # until 120s if msflog is not created then elog will exit if [ "$tm" == "120" ] then echo -e "$yellow" "Metasploit Not Detected" exit 0 else # Timmer is not yet at 120 , pause 1 second and loop again sleep 1 start fi else # At this point msfconsole PID is running and msflog was generated to be consulted # gmsft will grab the last value (scanned) from msflog gmsft=$(grep "Scanned" $mlog | tail -1) # In case gmsft is equal to variable (a) then set variable a with same value and wait 1 second if [ "$gmsft" == "$a" ] then a="$gmsft" sleep 1 # timer value sets to 119 of 120 seconds , this way when elog ends its job it will reach 120s in 1 second and will exit itself so escan can continue its job tm="119" #start loop start else # In case gmsft is different then variable (a) then setup a with same value # this process avoids repeating the same percentage on screen from msflog echo "$gmsft" a="$gmsft" tm="119" sleep 1 # start loop start fi fi fi } start
d734e14efdbe53fc2cebe88ec4ba1565009dcc77
[ "Shell" ]
1
Shell
hybridious/eternal_scanner
e3da8baf2dc7f29b36dc2920c97176bd39221e03
1bb604bdb75a831b789ab8eae1ad02f46e986625
refs/heads/main
<file_sep>#Lista de mensagens a comentar message = ["@Friend1", "@Friend2", "@MuchFriendsIsBetter"] repeat = 200 chrome_driver = './drivers/chromedriver' bin_location = "/opt/brave.com/brave/brave-browser" # Insira o link da postagem do sorteio abaixo link = "https://www.instagram.com/p/CMzObxeDbCC/?igshid=1kx8u0i6ypj19" <file_sep>#Insira login e Senha entre as aspas user = "" password = "" <file_sep># Trava insta ### step-by-step #### abra o arquivo login.py insira suas informações de login e senha entre as aspas #### abra o arquivo config.py Insira as mensagens na lista conforme o modelo. insira a localização do seu navegador (Chrome based) #### troubleshot O sistema precisa do driver do chrome driver referente a versão do seu navegador caso seja imcompatível é necessario baixar a versao correspondente e subistituir dentro da pasta drivers. <file_sep>from travainsta import TravaInsta bot = TravaInsta() bot.start() <file_sep>from config import message, repeat, chrome_driver, link, bin_location from login import user, password from selenium import webdriver from random import randint from time import sleep from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options class TravaInsta: opt = Options() opt.binary_location = bin_location driver = webdriver.Chrome(options=opt, executable_path=chrome_driver) wait_a_min_or = WebDriverWait(driver, 60) def start(self): self.driver.get("https://www.instagram.com/") self.driver.maximize_window() # Type login and password self.wait_a_min_or.until(EC.presence_of_element_located((By.XPATH, '//*[@id="loginForm"]/div/div[1]/div/label/input'))) self.driver.find_element(By.XPATH, '//*[@id="loginForm"]/div/div[1]/div/label/input').send_keys(user) self.driver.find_element(By.XPATH, '//*[@id="loginForm"]/div/div[2]/div/label/input').send_keys(password) # Submit self.wait_a_min_or.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="loginForm"]/div/div[3]/button'))) self.driver.find_element(By.XPATH, '//*[@id="loginForm"]/div/div[3]/button').click() self.wait_a_min_or.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="react-root"]/section/main/div/div/div/div/button'))) self.driver.find_element(By.XPATH, '//*[@id="react-root"]/section/main/div/div/div/div/button').click() # Close push notification pop-up self.wait_a_min_or.until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[4]/div/div/div/div[3]/button[2]'))) self.driver.find_element(By.XPATH, '/html/body/div[4]/div/div/div/div[3]/button[2]').click() self.driver.get(link) self.send(message, repeat) def send(self, message, repeat): count = 0 errors = 0 while(True): for j in range(5): try: self.wait_a_min_or.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="react-root"]/section/main/div/div[1]/article/div[3]/section[3]/div/form/textarea'))) self.driver.find_element(By.XPATH, '//*[@id="react-root"]/section/main/div/div[1]/article/div[3]/section[3]/div/form/textarea').click() self.driver.find_element(By.XPATH, '//*[@id="react-root"]/section/main/div/div[1]/article/div[3]/section[3]/div/form/textarea').send_keys(self.get_comment()) self.wait_a_min_or.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="react-root"]/section/main/div/div[1]/article/div[3]/section[3]/div/form/button[2]'))) self.driver.find_element(By.XPATH, '//*[@id="react-root"]/section/main/div/div[1]/article/div[3]/section[3]/div/form/button[2]').click() count+=1 print(count) except: print("Pause for comment limit") sleep(600) self.driver.refresh() errors+=1 if(errors>2): break if(errors>2): print("Stoped by dially comment limit") break sleep(300) print("fim") def get_comment(self): index1 = randint(0,len(message)-1) index2 = index1 while(index2 == index1): index2 = randint(0,len(message)-1) comment = message[index1]+ " "+message[index2] return comment
8b27f4fb8ee6cb59b3469b68724e390e9fb73c58
[ "Markdown", "Python" ]
5
Python
Gabriel-Aragao/trava-insta
a8cd1c9eb426f7c45ef3548cd4c74a2e7227f88f
90507de332f51c2e9b9643edc70a31d69b9f59e0
refs/heads/master
<file_sep>'use strict'; const AWS = require('aws-sdk'); const functions = require('./lib/functions'); const classifier = require('./lib/classifier'); const key = process.env.key; const secret = process.env.secret; const rekognition = new AWS.Rekognition({ region: 'us-east-1', apiVersion: '2016-06-27', accessKeyId: key, secretAccessKey: secret }); const analyzeByDataUri = classifier.analyze(rekognition, functions.byDataUri); exports.handler = (event, context, callback) => { analyzeByDataUri(event) .then( (data) => { callback(null, message(data)); }) .catch((err) => { callback(null, message({msg: 'what!?'})); }); }; function message(body){ return { statusCode: '200', body: JSON.stringify(body), headers: { 'Content-type': 'application/json', 'Access-Control-Allow-Headers': 'Content-Type,X-Api-Key', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Origin': '*' } }; }<file_sep> exports.byDataUri = (rekognition, dataURI) => { let params = { Image: { Bytes: Buffer.from(dataURI,'base64') }, MaxLabels: 20, MinConfidence: 25 }; return new Promise( (resolve, reject) => { rekognition.detectLabels(params, function(err, data) { if (err) resolve(err) else resolve(data); }); }); }; <file_sep> const validateInput = (event) => event.body && JSON.parse(event.body).analyze; exports.analyze = (rekognition, func) => { return (event) => { const analyze = validateInput(event); if (!analyze){ return Promise.reject({message: 'invalid input'}); } return func(rekognition, analyze); }; } exports.validateInput = validateInput;<file_sep>const td = require("testdouble"); const chai = require("chai"); const expect = chai.expect; const classifier = require('../lib/classifier'); describe('classifier', function (){ const callback = (rekognition, data) => Promise.resolve([rekognition, data]); const data = '1234'; const rekognition = '5678'; const event = {body: JSON.stringify({analyze: data}) }; describe('validateInput()', function (){ it("valid input", function() { const ok = classifier.validateInput(event); expect(ok).equal(data); }); it("invalid input", function() { const ok = classifier.validateInput({body: '{}'}); expect(ok).to.be.undefined; }); }); describe('analyze', function (){ it('should analyze', function (){ const analyze = classifier.analyze(rekognition, callback); return analyze(event).then( (arr) => { expect(arr[0]).to.equal(rekognition); expect(arr[1]).to.equal(data); }); }); }); }); <file_sep>#!/bin/bash rm package.zip zip -r package.zip package.json index.js src/classifier.js node_modules/<file_sep> https://docs.aws.amazon.com/lambda/latest/dg/test-sam-local.html sam local start-api --env-vars env.json
660491e87aab38d1d54c8dc2d4eadaded65e66d2
[ "JavaScript", "Markdown", "Shell" ]
6
JavaScript
mrkarppinen/visual-recognition-aws
8d8642dd03ded48786f6bf8f0306837384f2e72a
9151d766d44107a499f55858106824c92ac7dd7e
refs/heads/master
<repo_name>ideacrew/poly_press<file_sep>/lib/poly_press/serializers/excel.rb require 'rubyXL' require 'rubyXL/convenience_methods/cell' module PolyPress module Serializers class Excel send(:include, Dry::Monads[:result, :do]) send(:include, Dry::Monads[:try]) DATA_FEATURE_KEYS = %w(sheet page_group rows row cells checkboxes split_fields) DERIVED_INPUT_KINDS = %w(checkboxes split_fields) # @param[Dry::Struct] data (required) # @param[String] form_namespace (required) # @param[Dry::Container] registry # @return [Dry::Monad::Result<PolyPress::Document>] document def call(data:, form_namespace:, registry:) @registry = registry template = yield get_template(registry, form_namespace) data_features = yield get_data_features(registry, form_namespace) document = yield create(data, template, data_features, form_namespace) Success(document) end private def get_template(registry, form_namespace) form_name = form_namespace.split('.')[-1] template_feature = [form_name, 'template'].join('_') template = registry[template_feature].item Success(template) end def get_data_features(registry, form_namespace) data_features = registry.features_by_namespace(form_namespace).collect do |feature_key| feature = registry[feature_key] feature if DATA_FEATURE_KEYS.include?(feature.item.to_s) end.compact Success(data_features) end def create(data, template, data_features, form_namespace) sheet = data_features.detect{|feature| feature.item == :sheet} sheet_namespaces = sheet.setting(:sheet_namespaces).item workbook = RubyXL::Parser.parse(template) sheet.setting(:data_elements).item.each do |index, elements| form_name = sheet_namespaces[index] features = data_features.select{|feature| elements.include?(feature.key.to_sym) } worksheet_index = index page_group_features = features.select{|feature| feature.item == :page_group} if page_group_features.present? feature = page_group_features[0] if matched = feature.key.to_s.match(/^#{form_name}_(.*)$/) page_group_data = data.send(matched[1]) rescue data end page_group_data.each do |page_data| worksheet = workbook[worksheet_index] derived_features = features.select{|feature| DERIVED_INPUT_KINDS.include?(feature.item.to_s) } cell_features = features.select{|feature| feature.item == :cells} worksheet = process_cell_features(worksheet, cell_features, data, form_name, derived_features) worksheet = process_page_group(worksheet, page_data || data, feature, derived_features, form_name) worksheet_index += 1 end workbook.worksheets.delete(workbook["OSHA Form 300 (#{worksheet_index})"]) else worksheet = workbook[index] cell_features = features.select{|feature| feature.item == :cells} derived_features = features.select{|feature| DERIVED_INPUT_KINDS.include?(feature.item.to_s) } worksheet = process_cell_features(worksheet, cell_features, data, form_name, derived_features) end end file = workbook.write("tmp/#{template.to_s.split(/\//)[-1]}") Success(file) end def process_cell_features(worksheet, cell_features, data, form_name, derived_features) cell_features.each do |feature| if matched = feature.key.to_s.match(/^#{form_name}_(.*)$/) feature_data = data.send(matched[1]) rescue data end worksheet = populate_cells(worksheet, feature_data || data, feature, derived_features) end worksheet end def populate_cells(worksheet, data, feature, derived_features, begin_index = nil) feature.settings.each do |setting| value = fetch_value(setting.key.to_s, data) if value.to_s.present? value = parse_dates(value) if setting.item.is_a?(Hash) setting_location = setting.item else derived_input_keys = setting.item.split('.') derived_feature = derived_features.detect{|feature| feature.item == derived_input_keys[0].to_sym } setting = derived_feature.setting(derived_input_keys[1..-1].join('.')) derived_feature_type = derived_feature.item if derived_feature_type == :split_fields value = data.send(derived_input_keys[-1]) cells = setting.item[:cells] cells[(cells.length - value.length)..-1].each_with_index do |points, index| worksheet.sheet_data[points[0]][points[1]].change_contents(value[index]) end next else setting_location = setting.item[(boolean?(value) ? value : value.to_sym)] if derived_feature_type == :checkboxes value = 'X' end end end points = setting_location[:cell] worksheet.sheet_data[begin_index || points[0]][points[1]].change_contents(value) end end worksheet end def process_page_group(worksheet, data, feature, derived_features, form_name) feature.setting(:sections).item.each do |feature_key| section_feature = @registry[feature_key] if section_feature.item == :rows rows = [] if matched = section_feature.key.to_s.match(/^#{form_name}_(.*)$/) rows = data.send(matched[1]) rescue data end begin_index = section_feature.setting(:begin_row_index).item row_feature = @registry[section_feature.setting(:row).item] rows.each do |row| worksheet = populate_cells(worksheet, row, row_feature, derived_features, begin_index) begin_index += 1 end end end worksheet end def fetch_value(attribute, data) attributes = attribute.split('.') if attributes.count > 1 fetch_value(attributes[1..-1].join('.'), data.send(attributes[0])) else data.send(attributes[0]) end end def boolean?(value) value.is_a?(TrueClass) || value.is_a?(FalseClass) end def parse_dates(value) if value.is_a?(Date) value.strftime('%m/%d/%Y') elsif value.is_a?(DateTime) value else value end end end end end <file_sep>/lib/poly_press/document.rb # frozen_string_literal: true require_relative 'operations/documents/create' module PolyPress HTML_FORMATTER = lambda do |context| end PDF_FORMATTER = lambda do |context| end EDI_834_FORMATTER = {} JSON_FORMATTER = lambda do |context| end TEXT_FORMATTER = lambda do |context| puts("*** #{context.title} ***") context.text.each { |line| puts "#{line}\n" } end XML_FORMATTER = lambda do |context| end class Document < Dry::Struct attribute :document, Types::String end end<file_sep>/lib/poly_press/serializers/base_struct.rb module PolyPress module Serializers class BaseStruct < Dry::Struct def self.to_hash(object, type = self) type.schema.each_with_object({}) do |key, item| name = key.name attr = key.type if array?(attr) values = ::Array.wrap(object.public_send(name)) item[name] = values.map { |value_item| serialize(value_item, attr.member) } elsif bool?(attr) value = object.public_send("#{name}?") item[name] = value else value = object.public_send(name) item[name] = serialize(value, attr) end end end private def serialize(object, type) complex?(type) ? to_hash(object, type) : object end def complex?(attribute) attribute.respond_to?(:<) && attribute < BaseStruct end def bool?(attribute) attribute.primitive?(true) end def array?(attribute) attribute.primitive?([]) end end end end <file_sep>/lib/poly_press/types.rb # frozen_string_literal: true require 'dry-types' module PolyPress module Types send(:include, Dry.Types()) include Dry::Logic Formatter = Types::Coercible::String.default("csv").enum("csv", "pdf", "text", "xml", "json") HashOrNil = Types::Hash | Types::Nil StringOrNil = Types::String | Types::Nil RequiredString = Types::Strict::String.constrained(min_size: 1) StrippedString = Types::String.constructor(&:strip) SymbolOrString = Types::Symbol | Types::String NilOrString = Types::Nil | Types::String StrictSymbolizingHash = Types::Hash.schema({}).strict.with_key_transform(&:to_sym) Callable = Types.Interface(:call) end end <file_sep>/lib/poly_press/formatters.rb # frozen_string_literal: true require_relative 'formatters/csv' module PolyPress module Formatters end end <file_sep>/lib/poly_press/template.rb # frozen_string_literal: true require_relative 'operations/templates/list' require_relative 'operations/templates/create' require_relative 'operations/templates/update' require_relative 'operations/templates/find' # require_relative 'operations/templates/delete' module PolyPress # A Template contains structured and unstructured text and associated content to be output into a document class Template < Dry::Struct attribute :key, Types::Symbol.meta(omittable: false) # unique identifier attribute :title, Types::String.meta(omittable: false) # human name for display purposes attribute :entity_class_name, Types::String.meta(omittable: false) # Application entity # attribute :namespace, Types::Array.of(PolyPress::Namespace).meta(omittable: true) # unique identifier attribute :token_set, Types::Array.of(Types::Symbol).meta(omittable: true) # cached list of substitution attributes used in the composition attribute :compositions, Types::Array.of(PolyPress::Composition).meta(omittable: true) attribute :options, Types::Array.of(PolyPress::Option).meta(omittable: true) # settings passed into the formatter(s) to build documents end end<file_sep>/lib/poly_press/composition.rb # frozen_string_literal: true # require_relative 'operations/document/create' module PolyPress # A Template contains structured and unstructured text and associated content to # be output into a document class Composition < Dry::Struct # attribute :content, Types::String.meta(omittable: true) # Literal text with embedded markdown attribute :locale, Types::String.meta(omittable: false) # Composition's written Language attribute :resources, Types::Array.of(PolyPress::Resource).meta(omittable: true) end end<file_sep>/lib/poly_press/operations/documents/create.rb # frozen_string_literal: true module PolyPress module Operations module Documents # Generate a {Document} using the entity instance values with {Template} composition # in the Format and Locale class Create send(:include, Dry::Monads[:result, :do]) send(:include, Dry::Monads[:try]) # @param[Dry::Struct] entity_instance (required) # @param[Symbol] formatter (required) # @param[Symbol] template_key # @param[String] locale # @return [Dry::Monad::Result<PolyPress::Document>] document def call(params) values = yield validate(params) content = yield merge(values) formatter_klass = yield formatter_class(values.to_h[:formatter]) document = yield create(formatter_klass: formatter_klass, content: content) Success(document) end private def validate(params) PolyPress::Validations::CreateDocumentContract.new(params) end def merge(values) values_hash = values.to_h template = Operations::Templates::Find.new.call(key: values_hash[:template_key], locale: values_hash[:locale]) template.new.call(values: values_hash[:entity_instance]).to_result end def formatter_klass(formatter) Try { ("PolyPress::Formatters::" + "#{formatter}.classify").constantize }.to_result end def create(formatter_klass, content) document = formatter_klass.new.call(content) Success(document) end end end end end <file_sep>/lib/poly_press/operations/templates/find.rb # frozen_string_literal: true module PolyPress module Operations module Templates # Generate a {Template} class Find def call(params) end end end end end<file_sep>/spec/support/poly_press_data_seed.rb # frozen_string_literal: true require_relative 'record_array_struct' require_relative 'record_hash_struct' module PolyPressDataSeed def x_files_header %w(first_name last_name age gender) end def x_files_rows [ %w(fox mulder 35 male), %w(jeffrey spender 25 male), %w(dana scully 31 female), %w(<NAME> 40 male), %w(samantha mulder 12 female), %w(<NAME> 33 male), %w(smoking man 64 male), %w(<NAME> 38 male), ] end def x_files_hash [ {first_name: "fox", last_name: "mulder", age: 35, gender: "male"}, {first_name: "jeffrey", last_name: "spender", age: 25, gender: "male"}, {first_name: "dana", last_name: "scully", age: 31, gender: "female"}, {first_name: "walter", last_name: "skinner", age: 40, gender: "male"}, {first_name: "samantha", last_name: "skully", age: 12, gender: "female"}, {first_name: "alex", last_name: "krychek", age: 33, gender: "male"}, {first_name: "smoking", last_name: "man", age: 64, gender: "male"}, {first_name: "john", last_name: "doggett", age: 38, gender: "male"}, ] end def x_files_array_struct RecordArrayStruct.new(list: x_files_rows) end def x_files_array_with_header_struct RecordArrayStruct.new(header: x_files_header, list: x_files_rows) end def x_files_hash_struct RecordHashStruct.new(list: x_files_hash) end end <file_sep>/spec/support/record_array_struct.rb # frozen_string_literal: true module PolyPressDataSeed class RecordArrayStruct < Dry::Struct attribute :header, PolyPress::Types::Array.of(PolyPress::Types::String).meta(omittable: true) attribute :list, PolyPress::Types::Array.of(PolyPress::Types::Any).meta(omittable: false) end end <file_sep>/spec/support/record_hash_struct.rb # frozen_string_literal: true module PolyPressDataSeed class RecordHashStruct < Dry::Struct attribute :list, PolyPress::Types::Array.of(PolyPress::Types::Hash).meta(omittable: false) end end <file_sep>/poly_press.gemspec require_relative 'lib/poly_press/version' Gem::Specification.new do |spec| spec.name = "poly_press" spec.version = PolyPress::VERSION spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.summary = %q{Engine for generating template-based output in common formats for volumes both small and large} spec.description = %q{Engine for generating template-based output in common formats for volumes both small and large} spec.homepage = "https://github.com/ideacrew/poly_press.git" spec.license = "MIT" spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0") # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = "https://github.com/ideacrew/poly_press.git" spec.metadata["changelog_uri"] = "https://github.com/ideacrew/poly_press/blob/master/CHANGELOG" # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_dependency 'i18n', '~> 1.6' spec.add_dependency 'dry-validation', '~> 1.2' spec.add_dependency 'dry-struct', '~> 1.0' spec.add_dependency 'dry-monads', '~> 1.2' spec.add_dependency 'dry-matcher', '~> 0.7' spec.add_dependency 'rubyXL', '~> 3.4', '>= 3.4.14' # spec.add_dependency 'rails', '>= 6.0' spec.add_development_dependency "bundler", "~> 2.0" spec.add_development_dependency "rubocop", '~> 0.74.0' spec.add_development_dependency "yard", "~> 0.9" spec.add_development_dependency 'pry-byebug' end <file_sep>/lib/poly_press/validations/create_document_contract.rb # frozen_string_literal: true module PolyPress module Validations # Schema and validation rules for the {PolyPress::Operations::Documents::Create} operation class CreateDocumentContract < ApplicationContract # @!method call(opts) # @param [Hash] opts the parameters to validate using this contract # @option opts [Dry::Struct] :entity_instance (required) # @option opts [PolyPress::Types::Formatter] :formatter (required) # @option opts [Symbol] :template_key # @option opts [Symbol] :locale # @return [Dry::Monads::Result] result params do required(:entity_instance).filled(Dry::Struct) required(:formatter).filled(PolyPress::Types::Formatter) optional(:template_key).value(:symbol) optional(:locale).value(:string) # @!macro [attach] beforehook # @!method $0($1) # Coerce locale string value if present before(:value_coercer) do |result| result.to_h.merge!({ locale: config.messages.default_locale }) if (result[:locale].nil? || result[:locale].empty?) end end # Template key must exist and use the same entity class rule(:template_key) do if key? && value param_class = value[:entity_instance].class.name expected_class = Operations::Templates.find.new.call(key) key.failure(text: "template not found: #{key}") if (result[:template_key].nil? || result[:template_key].empty?) key.failure(text: "feature #{expected_class} expected, got #{param_class}", error: result.errors.to_h) if expected_class != param_class end end # Template for locale must exist rule(:locale) do end end end end <file_sep>/lib/poly_press.rb require "poly_press/version" # # require 'i18n' require 'dry-struct' require 'dry/validation' require 'dry/monads' require 'dry/monads/result' require 'dry/monads/do' require 'poly_press/types' require 'poly_press/resource' require 'poly_press/composition' require 'poly_press/document' require 'poly_press/option' require 'poly_press/template' require 'poly_press/formatters' require 'poly_press/serializers/base_struct' require 'poly_press/serializers/excel' module PolyPress # I18n.load_path << Dir[File.expand_path("config/locales") + "/*.yml"] # I18n.default_locale = :en class Error < StandardError; end # # Your code goes here... end <file_sep>/spec/poly_press/formatters/csv_spec.rb # frozen_string_literal: true require 'spec_helper' require 'support/poly_press_data_seed' RSpec.describe PolyPress::Formatters::Csv do include PolyPressDataSeed context "Params passed in array form" do context "with a header record" do let(:x_files_people) { x_files_array_with_header_struct } it "should do something" end context "without a header record" do let(:x_files_people) { x_files_array_struct } it "should do something" end end context "Params passed in hash form" do let(:x_files_people) { x_files_hash_struct } let(:csv_out) { "FirstName,LastName,Age,Gender\n" + "fox,mulder,35,male\n" + "jeffrey,spender,25,male\n" + "dana,scully,31,female\n" + "walter,skinner,40,male\n" + "samantha,skully,12,female\n" + "alex,krychek,33,male\n" + "smoking,man,64,male\n" + "john,doggett,38,male\n" } it "should generate csv header and rows for each record" do result = subject.call(content: x_files_people) expect(result.success?).to be_truthy expect(result.value!).to eq csv_out end end end <file_sep>/lib/poly_press/option.rb # frozen_string_literal: true # require_relative 'operations/options/create' module PolyPress # An Option os a key/value pair class Option < Dry::Struct attribute :key, Types::Symbol.meta(omittable: false) attribute :value, Types::Any.meta(omittable: false) end end<file_sep>/lib/poly_press/formatters/csv.rb # frozen_string_literal: true require 'csv' module PolyPress module Formatters class Csv send(:include, Dry::Monads[:result, :do]) send(:include, Dry::Monads[:try]) # @param[Dry::Struct] content (required) # @return [Dry::Monad::Result<PolyPress::Document>] document def call(content:) output = yield format(content) Success(output) end private def format(content) # klass = content.class columns = content[:list].first.keys Try { CSV.generate do |csv| csv << columns.map { |column| camelize(column) } content[:list].each do |item| csv << columns.map do |column| column == :tags ? item[:tags].join(' ') : item[column] end end end }.to_result end def camelize(string) string = string.to_s.sub(/^[a-z\d]*/) { |match| match.capitalize } string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub("/", "::") end end end end <file_sep>/lib/poly_press/resource.rb # frozen_string_literal: true # require_relative 'operations/attachments/create' module PolyPress # A Resource is keyed references to local content -- such as images -- embedded # at the Composition location class Resource < Dry::Struct attribute :key, Types::Symbol.meta(omittable: false) attribute :ref, Types::Any.meta(omittable: false) end end
b65abe4e83698ef88a54f0bb59478f08d1c71d4e
[ "Ruby" ]
19
Ruby
ideacrew/poly_press
dfeab26e2f6d551939fc1237d726b029a48596bd
82fe8b9d1d751add1421581561110af9aec3a73f
refs/heads/master
<repo_name>githubfun/ksmv<file_sep>/mkt_data_view_v1.1_Vol.R require(quantmod) require(pastecs) require(ggplot2) require(corrgram) require(car) sapply(list.files(pattern="[.]R$", path='functions/', full.names=TRUE), source) ## Retrieving Data & Refining file1 <- "./data/SX5E_Vol.csv" Asset_data <- read.csv(file1) Asset_data <- as.xts(Asset_data[,-1], order.by=as.POSIXct(Asset_data[,1])) # Change Asset data into return data and add Vol Index return data Asset_data[,1] <- ROC(Asset_data[,1], n=1, type="continuous") for(i in 2:5) { Asset_data <- cbind(Asset_data,ROC(Asset_data[,i], n=1, type="continuous")) names(Asset_data)[NCOL(Asset_data)] <- paste(names(Asset_data)[i],"return",sep="_") } # Add difference Asset_data <- cbind(Asset_data, Asset_data[,2] - Asset_data[,3]) #Imp-HIst names(Asset_data)[NCOL(Asset_data)] <- "Imp_Hist" Asset_data <- cbind(Asset_data, Asset_data[,3] - Asset_data[,4]) #Short-Long names(Asset_data)[NCOL(Asset_data)] <- "Short_Long" Asset_data <- cbind(Asset_data, Asset_data[,3] - Asset_data[,5]) #HIst-PHIst names(Asset_data)[NCOL(Asset_data)] <- "Hist_Phist" Asset_data <- cbind(Asset_data, Asset_data[,2] - Asset_data[,5]) #Imp-Phist names(Asset_data)[NCOL(Asset_data)] <- "Imp-Phist" Asset_data <- cbind(Asset_data, MACD(Asset_data[,2])$macd) #macd Asset_data <- cbind(Asset_data, MACD(Asset_data[,2])$macd - MACD(Asset_data[,2])$signal) #macd signal gap names(Asset_data)[NCOL(Asset_data)] <- "macd_sig" ## Lagging for(i in 2:NCOL(Asset_data)) { Asset_data[,i] <- lag(Asset_data[,i], k=2) } ##1.Summary of Statistics #stat.desc(Indicators) #for (i in 1:14) { # hist(Indicators[,i]) #} #2.Correlation Table cor_out <- {} cor_out <- corstarsl(Asset_data)[1] names(cor_out)[NCOL(cor_out)] <- "All" cor_out <- cbind(cor_out, corstarsl(Asset_data['2008-03/'])[1]) names(cor_out)[NCOL(cor_out)] <- "5yr" cor_out <- cbind(cor_out, corstarsl(Asset_data['2012-03/'])[1]) names(cor_out)[NCOL(cor_out)] <- "1yr" #3.Scatter Plot plot(coredata(GTAA_data[,5]), coredata(lag(GTAA_data[,18],k=0)), pch=19) abline(v=0, h=1) abline(h=-1) scatterplotMatrix(cbind(coredata(GTAA_data['2005/',6]),coredata(GTAA_data['2005/',8:13]))) scatterplotMatrix(cbind(coredata(GTAA_data['2005/',1]),coredata(Macro_sig['2005/']))) #4.Regression<file_sep>/pf_optimizer_weekly.R require(quantmod) require(tseries) require(quadprog) require(corpcor) sapply(list.files(pattern="[.]R$", path='functions/', full.names=TRUE), source) ## Retrieving Data & Refining file1 <- "./data/pf_opt_data.csv" pf_opt_data <- read.csv(file1) pf_opt_data <- as.xts(pf_opt_data[,-1], order.by=as.POSIXct(pf_opt_data[,1])) prc_pf_opt_data <- pf_opt_data w_pf_opt_data <- {} w_pf_opt_data <- to.period(pf_opt_data[,i], period='weeks')[,4] # To Weekly for (i in 2:7) { w_pf_opt_data <- cbind(w_pf_opt_data, to.period(pf_opt_data[,i], period='weeks')[,4]) } names(w_pf_opt_data) <- names(pf_opt_data) # Change to return data for (i in 1:7) { w_pf_opt_data[,i] <- ROC(w_pf_opt_data[,i], type="discrete") } ## end of data refining ## backtesting part # 1: SPX, 2:NKY, 3: SX5E, 4:Copper, 5:WTI, 6:Gold, 7:UST10Y Fut # settings: 1.Selecting assets to optimize, 2.Target Vol level, 3.lookback period assetsToTest <- c(1,2,3,4,5,6,7) cash_asset <- 7 targetVolLv <- 0.1 lookback <- 13 return_series <- xts(x=matrix(c(0,0), nrow=1), order.by=index(w_pf_opt_data[lookback])) #loop for(i in (lookback+1):(nrow(w_pf_opt_data)-1)) { #cov.mat cov.mat <- cov(w_pf_opt_data[(i-lookback+1):i,assetsToTest]) cov.mat <- make.positive.definite(cov.mat, 0.000000001) ### Optimizing part D.mat <- 2*cov.mat d.vec <- rep(0,7) A.mat <- cbind(rep(1,7)) b.vec <- c(1) optimized <- solve.QP(Dmat=D.mat, dvec=d.vec, Amat=A.mat, bvec=b.vec, meq=1) adj_w <- optimized$solution # #calculate max sharpe ratio weight # ef <- effFrontier_k(mu.vec, cov.mat) # #adjust vol to certain level # adj_w <- targetVolLv/ef$mx_vol*ef$w #ef$w_tgt_vol #calculate realized return return_i <- matrix(w_pf_opt_data[i], nrow=1) %*% adj_w return_c <- return_i#as.numeric((1-targetVolLv/ef$mx_vol)*(coredata(monthly_data[i+1,cash_asset])/coredata(monthly_data[i,cash_asset])-1)) #add to return index return_series <- rbind(return_series,xts(x=matrix(c(return_i, return_c),nrow=1), order.by=index(w_pf_opt_data[i]))) } #end of loop plot(ef$vol, ef$ret)<file_sep>/pf_optimizer.R require(quantmod) require(tseries) sapply(list.files(pattern="[.]R$", path='functions/', full.names=TRUE), source) ## Retrieving Data & Refining file1 <- "./data/pf_opt_data.csv" pf_opt_data <- read.csv(file1) pf_opt_data <- as.xts(pf_opt_data[,-1], order.by=as.POSIXct(pf_opt_data[,1])) prc_pf_opt_data <- pf_opt_data # Change to return data for (i in 1:7) { pf_opt_data[,i] <- ROC(pf_opt_data[,i], type="discrete") } monthly_data <- to.period(prc_pf_opt_data[,1], period = 'months', indexAt='endof')[,4] # Change to return data for (i in 2:7) { monthly_data <- cbind(monthly_data, to.period(prc_pf_opt_data[,i], period = 'months', indexAt='endof')[,4]) } names(monthly_data) <- names(prc_pf_opt_data) ## end of data refining ## backtesting part # 1: SPX, 2:NKY, 3: SX5E, 4:Copper, 5:WTI, 6:Gold, 7:UST10Y Fut # settings: 1.Selecting assets to optimize, 2.Target Vol level, 3.lookback period assetsToTest <- c(1,2,3,4,5,6) cash_asset <- 7 targetVolLv <- 0.1 lookback <- 3 vollookback <- 12 return_series <- xts(x=matrix(c(0,0), nrow=1), order.by=index(monthly_data[lookback])) #loop for(i in (vollookback+2):(nrow(monthly_data)-1)) { #get today and lookback date date_today <- index(monthly_data[i]) date_lookback <- index(monthly_data[i-lookback]) #mu.vec mu.vec <- matrix(coredata(monthly_data[date_today,assetsToTest])/coredata(monthly_data[date_lookback,assetsToTest])-1, nrow=1)*12/lookback #cov.mat cov.mat <- cov(pf_opt_data[paste(index(monthly_data[i-vollookback]), index(monthly_data[i]), sep="/"),assetsToTest])*252 #calculate max sharpe ratio weight ef <- effFrontier_k(mu.vec, cov.mat) ef2 <- effFrontier_k2(as.vector(mu.vec), cov.mat, reslow=rep(-1,6), reshigh=rep(1,6)) ef3 <- effFrontier_k3(mu.vec, cov.mat, reslow=rep(-1,6), reshigh=rep(1,6)) #adjust vol to certain level adj_w <- ef3$w #targetVolLv/ef2$mx_vol*ef2$w #ef$w_tgt_vol #calculate realized return return_i <- matrix(coredata(monthly_data[i+1,assetsToTest])/coredata(monthly_data[i,assetsToTest])-1,nrow=1) %*% adj_w return_c <- as.numeric((1-targetVolLv/ef$mx_vol)*(coredata(monthly_data[i+1,cash_asset])/coredata(monthly_data[i,cash_asset])-1)) #add to return index return_series <- rbind(return_series,xts(x=matrix(c(return_i, return_c),nrow=1), order.by=index(monthly_data[i]))) } #end of loop plot(ef$vol, ef$ret) plot(ef2$vol, ef2$ret)<file_sep>/performance_analysis_k.R require(PerformanceAnalytics) table.Stats(return_series) table.CalendarReturns(return_series[,2], geometric=FALSE) charts.PerformanceSummary(return_series[,1],main="Performance", geometric=FALSE) charts.PerformanceSummary(return_series,main="Performance", geometric=FALSE) chart.RiskReturnScatter(return_series) table.AnnualizedReturns(return_series) <file_sep>/mkt_data_view_CH_v1.1.R require(quantmod) require(pastecs) require(ggplot2) require(corrgram) require(car) sapply(list.files(pattern="[.]R$", path='functions/', full.names=TRUE), source) ## Retrieving Data & Refining file1 <- "./data/Stock_Indice.csv" Asset_data <- read.csv(file1) Asset_data <- as.xts(Asset_data[,-1], order.by=as.POSIXct(Asset_data[,1])) file2 <- "./data/CH_Econ_Indicators.csv" Indicators <- read.csv(file2) Indicators <- as.xts(Indicators[,-1], order.by=as.POSIXct(Indicators[,1])) # Change Asset data into return data for (i in 1:NCOL(Asset_data)) { Asset_data[,i] <- ROC(Asset_data[,i], n=1, type="continuous") } # Change Indicators ## Apply change for (i in 1:9) { Indicators[,i] <- Indicators[,i] - lag(Indicators[,i]) } #for (i in 9:9) { # Indicators[,i] <- ROC(Indicators[,i], type="continuous") #} ## Lagging for (i in 1:9) { Indicators[,i] <- lag(Indicators[,i], k=2) } #1.Summary of Statistics stat.desc(Indicators) for (i in 1:14) { hist(Indicators[,i]) } #2.Correlation Table corstarsl(Indicators) corstarsl(cbind(Asset_data, Indicators)[-3:-1])[6:14,1:5] #Pearson Corr corstarsl(cbind(Asset_data, Indicators)[-3:-1],type="spearman")[6:14,1:5] #Spearman Corr corstarsl(cbind(Asset_data, Indicators)['2008-03/'])[6:14,1:5] #Pearson Corr corstarsl(cbind(Asset_data, Indicators)['2008-03/'],type="spearman")[6:14,1:5] #Spearman Corr #3.Scatter Plot plot(coredata(Asset_data[,"HSCEI.Index"]), coredata(Indicators[,"CPMINDX.Index"]), pch=19) abline(v=0, h=1) abline(h=-1) scatterplotMatrix(cbind(coredata(GTAA_data['2005/',6]),coredata(GTAA_data['2005/',8:13]))) scatterplotMatrix(cbind(coredata(GTAA_data['2005/',1]),coredata(Macro_sig['2005/']))) #4.Regression<file_sep>/monthly_strat_v1.0.R require(quantmod) ## MOnthly ## Retrieving Data & Refining file1 <- "./data/Stock_Indice.csv" Asset_data <- read.csv(file1) Asset_data <- as.xts(Asset_data[,-1], order.by=as.POSIXct(Asset_data[,1])) index(Asset_data) <- as.Date(as.yearmon(index(Asset_data))+1/12)-1 file2 <- "./data/Econ_Indicators.csv" Indicators <- read.csv(file2) Indicators <- as.xts(Indicators[,-1], order.by=as.POSIXct(Indicators[,1])) index(Indicators) <- as.Date(as.yearmon(index(Indicators))+1/12)-1 # Change Asset data into return data for (i in 1:NCOL(Asset_data)) { Asset_data[,i] <- ROC(Asset_data[,i], n=1, type="continuous") } for (i in 1:NCOL(Indicators)) { Indicators[,i] <- ifelse(Indicators[,i] > lag(Indicators[,i], k=1), 1, 0) } for (i in 1:1) { Indicators[,i] <- lag(Indicators[,i], k=1) } for (i in 2:3) { Indicators[,i] <- lag(Indicators[,i], k=2) } results <- {} for(i in 1:NCOL(Asset_data)) { results <- cbind(results,Asset_data[,i]) for(j in 1:NCOL(Indicators)) { results <- cbind(results, Asset_data[,i] * Indicators[,j]) } } results[is.na(results)] <- 0 write.zoo(results, file="./data/results.csv", sep=",") ## Daily ## Retrieving Data & Refining file1 <- "./data/Stock_Indice_d.csv" Asset_data <- read.csv(file1) Asset_data <- as.xts(Asset_data[,-1], order.by=as.POSIXct(Asset_data[,1])) file2 <- "./data/signal_d.csv" Indicators <- read.csv(file2) Indicators <- as.xts(Indicators[,-1], order.by=as.POSIXct(Indicators[,1])) # Change Asset data into return data for (i in 1:NCOL(Asset_data)) { Asset_data[,i] <- ROC(Asset_data[,i], n=1, type="discrete") } for (i in 1:5) { Indicators[,i] <- ifelse(Indicators[,i] > lag(Indicators[,i], k=5), 1, 0) } for (i in 1:5) { Indicators[,i] <- lag(Indicators[,i], k=1) #Enter based on today value } results <- {} for(i in 1:NCOL(Asset_data)) { results <- cbind(results, Asset_data[,i]) results <- cbind(results, Asset_data[,i] * Indicators[,i]) } results[is.na(results)] <- 0 write.zoo(results, file="./data/results_d.csv", sep=",")<file_sep>/ksm_factor_view.R # Retrieving Data file1 <- "./Stock_mkt_viewer.csv" file2 <- "./Stock_mkt_viewer_f.csv" mkt_data <- read.csv(file1) f_data <- read.csv(file2) merge_data <- merge(mkt_data,f_data, by.x="Code", by.y="Code", all=FALSE) rm(mkt_data) rm(f_data) names(merge_data) require(psych) require(ggplot2) # Choose, change Variable to Plot plot_data <- merge_data names(plot_data) #### 1.Standardize Net Buy with Mkt.Cap elements <- c("Inst_1D", "Inst_5D", "Inst_20D", "Inst_60D", "Inst_120D", "Inst_250D", "Sec_1D", "Sec_5D", "Sec_20D", "Sec_60D", "Sec_120D", "Sec_250D", "Fund_1D", "Fund_5D", "Fund_20D", "Fund_60D", "Fund_120D", "Fund_250D", "Pension_1D", "Pension_5D", "Pension_20D", "Pension_60D", "Pension_120D", "Pension_250D", "Others_1D", "Others_5D", "Others_20D", "Others_60D", "Others_120D", "Others_250D", "Foreign_1D", "Foreign_5D", "Foreign_20D", "Foreign_60D", "Foreign_120D", "Foreign_250D") for(element in elements) { plot_data[[element]] <- plot_data[[element]]/plot_data$Mkt.Cap } #### 2.ROE, PBR, PER ## ROE plot_data$ROE_Trailing <- (plot_data$NI_FQ_3 + plot_data$NI_FQ_2 + plot_data$NI_FQ_1 + plot_data$NI_FQ0)/plot_data$Equity_FQ0 plot_data$ROE_FY1 <- plot_data$NI_FY1/plot_data$Equity_FY1 plot_data$ROE_FY2 <- plot_data$NI_FY2/plot_data$Equity_FY2 ## PBR plot_data$PBR_Trailing <- plot_data$Mkt.Cap/plot_data$Equity_FQ0 plot_data$PBR_FY1 <- plot_data$Mkt.Cap/plot_data$Equity_FY1 plot_data$PBR_FY2 <- plot_data$Mkt.Cap/plot_data$Equity_FY2 ## PER plot_data$PER_Trailing <- plot_data$Mkt.Cap/(plot_data$NI_FQ_3 + plot_data$NI_FQ_2 + plot_data$NI_FQ_1 + plot_data$NI_FQ0) plot_data$EY_Trailing <- 1/plot_data$PER_Trailing plot_data[which(plot_data$PER_Trailing < 0),]$PER_Trailing <- NA # NA Negative PER plot_data$PER_FY1 <- plot_data$Mkt.Cap/plot_data$NI_FY1 plot_data$EY_FY1 <- 1/plot_data$PER_FY1 plot_data[which(plot_data$PER_FY1 < 0),]$PER_FY1 <- NA # NA Negative PER plot_data$PER_FY2 <- plot_data$Mkt.Cap/plot_data$NI_FY2 plot_data$EY_FY2 <- 1/plot_data$PER_FY2 plot_data[which(plot_data$PER_FY2 < 0),]$PER_FY2 <- NA # NA Negative PER ## Growth plot_data$NI_Growth_FQ0 <- plot_data$NI_FQ0/plot_data$NI_FQ_4 - 1 plot_data[which((plot_data$NI_FQ_4 < 0) | (plot_data$NI_FQ0 <0)),]$NI_Growth_FQ0 <- NA # NA Negative NI plot_data$NI_Growth_FY1 <- plot_data$NI_FY1/plot_data$NI_FY0-1 plot_data[which((plot_data$NI_FY1 < 0) | (plot_data$NI_FY0 <0)),]$NI_Growth_FY1 <- NA # NA Negative NI plot_data$NI_Growth_FY2 <- plot_data$NI_FY2/plot_data$NI_FY1-1 plot_data[which((plot_data$NI_FY2 < 0) | (plot_data$NI_FY1 <0)),]$NI_Growth_FY2 <- NA # NA Negative NI fit <- lm(get(y_var)~get(x_var), data=plot_data[which((plot_data[[x_var]] < xlim_u) & (plot_data[[x_var]] > xlim_d) & (plot_data[[y_var]] < ylim_u) & (plot_data[[y_var]] > ylim_d)),c(y_var,x_var)]) summary(fit)<file_sep>/functions/ntop.R ntop = function ( data, topn=1 ) { temp = coredata(data) out <- {} for(i in 1:topn) { out <- rbind(out,which(temp == sort(temp, decreasing=TRUE)[i])) } return(as.vector(out)) }<file_sep>/pf_optimizer_monthly_v1.0.R require(quantmod) require(tseries) require(quadprog) require(corpcor) sapply(list.files(pattern="[.]R$", path='functions/', full.names=TRUE), source) ## Retrieving Data & Refining file1 <- "./data/pf_opt_data.csv" pf_opt_data <- read.csv(file1) pf_opt_data <- as.xts(pf_opt_data[,-1], order.by=as.POSIXct(pf_opt_data[,1], tz="UTC")) prc_pf_opt_data <- pf_opt_data getSymbols("SPY", src = 'yahoo', from = '2004-01-01', auto.assign = T) pf_opt_data <- Cl(adjustOHLC(get("SPY"), use.Adjusted=T)) tickers <- c("EFA", "EWJ", "EEM", "IYR", "RWX", "IEF", "TLT", "DBC", "GLD") for(ticker in tickers) { getSymbols(ticker, src = 'yahoo', from = '2004-01-01', auto.assign = T) pf_opt_data <- cbind(pf_opt_data, Cl(adjustOHLC(get(ticker), use.Adjusted=T))) } w_pf_opt_data <- {} w_pf_opt_data <- to.period(pf_opt_data[,1], period='months')[,4] # To Weekly for (i in 2:NCOL(pf_opt_data)) { w_pf_opt_data <- cbind(w_pf_opt_data, to.period(pf_opt_data[,i], period='months')[,4]) } names(w_pf_opt_data) <- names(pf_opt_data) prc_pf_opt_data <- w_pf_opt_data # Change to return data for (i in 1:NCOL(pf_opt_data)) { w_pf_opt_data[,i] <- ROC(w_pf_opt_data[,i], type="discrete") } # Change to return data for (i in 1:NCOL(pf_opt_data)) { pf_opt_data[,i] <- ROC(pf_opt_data[,i], type="discrete") } ## end of data refining ## backtesting part # 1: SPX, 2:NKY, 3: SX5E, 4:Copper, 5:WTI, 6:Gold, 7:UST10Y Fut # settings: 1.Selecting assets to optimize, 2.Target Vol level, 3.lookback period topn <- 3 start_i <- 2#167#2#60 assetsToTest <- 1:NCOL(w_pf_opt_data) cash_asset <- 7 targetVolLv <- 0.1 lookback <- 3 vollookback <- 12 return_series <- xts(x=matrix(rep(0,4), nrow=1), order.by=index(w_pf_opt_data[lookback+start_i])) names(return_series) <- c("All_Min_Var","Equal_W","Momentum","Momentum_Min_Var") weight <- xts(x=matrix(c(rep(0,NCOL(w_pf_opt_data))), nrow=1), order.by=index(w_pf_opt_data[lookback+start_i])) weight2 <- xts(x=matrix(c(rep(0,NCOL(w_pf_opt_data))), nrow=1), order.by=index(w_pf_opt_data[lookback+start_i])) #loop for(i in (vollookback+start_i):(nrow(w_pf_opt_data)-1)) { #Checking Return uplimit <- as.vector(ifelse(coredata(prc_pf_opt_data[i]) /coredata(prc_pf_opt_data[i-lookback])-1>0, 1,0)) downlimit <- as.vector(ifelse(coredata(prc_pf_opt_data[i]) /coredata(prc_pf_opt_data[i-lookback])-1<0, -1,0)) mu.vec <- as.vector(coredata(prc_pf_opt_data[i]) /coredata(prc_pf_opt_data[i-lookback])-1)*12/lookback #Momentum Part topindex <- ntop(mu.vec,topn) #cov.mat cov.mat <- cov(pf_opt_data[paste(index(monthly_data[i-vollookback]), index(monthly_data[i]), sep="/"),assetsToTest])*252 ef <- effFrontier_k(t(mu.vec), cov.mat) ef2 <- effFrontier_k2(mu.vec, cov.mat, nports=20, reslow=rep(-1,NCOL(w_pf_opt_data)), reshigh=rep(1,NCOL(w_pf_opt_data)), psum=1, tgt_vol=0.1) #effFrontier_k2(mu.vec, cov.mat, nports=20, reslow=downlimit, reshigh=uplimit, tgt_vol=0.1) ef3 <- effFrontier_k3(t(mu.vec), cov.mat, nports=20, reslow=rep(0,NCOL(w_pf_opt_data)), reshigh=rep(1,NCOL(w_pf_opt_data)), tgt_vol=0.1) adj_w <- ef2$w if(is.null(adj_w)) { print(paste("warning no weight for",index(w_pf_opt_data[i]),sep=" ")) adj_w <- rep(0,NCOL(w_pf_opt_data)) } adj_w <- round(adj_w, digit=2) mu.vec <- as.vector(coredata(prc_pf_opt_data[i,topindex]) /coredata(prc_pf_opt_data[i-lookback+1,topindex])-1)*12/lookback cov.mat <- cov(pf_opt_data[paste(index(monthly_data[i-vollookback]), index(monthly_data[i]), sep="/"),topindex])*252 ef4 <- effFrontier_k2(mu.vec, cov.mat, nports=20, reslow=rep(-1,topn), reshigh=rep(1,topn), tgt_vol=0.1) adj_w2 <- ef4$w if(is.null(adj_w2)) { print(paste("warning no weight for",index(w_pf_opt_data[i]),sep=" ")) adj_w2 <- rep(0,topn) } adj_w2 <- round(adj_w2, digit=2) weight <- rbind(weight,xts(x=matrix(adj_w,nrow=1), order.by=index(w_pf_opt_data[i+1]))) if (!is.null(ef2$w_tgt_vol)) { weight2 <- rbind(weight2,xts(x=matrix(ef2$w_tgt_vol,nrow=1), order.by=index(w_pf_opt_data[i+1]))) } else { weight2 <- rbind(weight2,xts(x=matrix(c(rep(NA,NCOL(w_pf_opt_data))),nrow=1), order.by=index(w_pf_opt_data[i+1]))) } #calculate realized return return_w <- matrix(w_pf_opt_data[i+1], nrow=1) %*% adj_w return_e <- matrix(w_pf_opt_data[i+1], nrow=1) %*% rep(1/NCOL(w_pf_opt_data),NCOL(w_pf_opt_data)) return_me <- matrix(w_pf_opt_data[i+1, topindex], nrow=1) %*% rep(1/topn,topn) return_mw <- matrix(w_pf_opt_data[i+1, topindex], nrow=1) %*% adj_w2 #add to return index return_series <- rbind(return_series,xts(x=matrix(c(return_w, return_e, return_me, return_mw),nrow=1), order.by=index(w_pf_opt_data[i+1]))) } #end of loop plot(ef$vol, ef$ret)<file_sep>/pf_optimizer_test.R require(quantmod) require(tseries) require(quadprog) ## Retrieving Data & Refining file1 <- "./data/pf_opt_data.csv" pf_opt_data <- read.csv(file1) pf_opt_data <- as.xts(pf_opt_data[,-1], order.by=as.POSIXct(pf_opt_data[,1])) prc_pf_opt_data <- pf_opt_data # Change to return data for (i in 1:6) { pf_opt_data[,i] <- ROC(pf_opt_data[,i], type="discrete") } mu.vec <- matrix(coredata(prc_pf_opt_data['2012-12-31',1:6])/coredata(prc_pf_opt_data['2012-09-28',1:6])-1, nrow=1)*4 cov.mat <- cov(pf_opt_data['2012-09-28/2012-12-31',1:6])*252 D.mat <- 2*cov.mat d.vec <- rep(0,6) A.mat <- cbind(as.vector(mu.vec), rep(1,6), diag(6)) b.vec <- c(-0.1, 1, rep(0,6)) #c(-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.4)) solve.QP(Dmat=D.mat, dvec=d.vec, Amat=A.mat, bvec=b.vec, meq=2) D.mat <- 2*cov.mat d.vec <- rep(0,7) A.mat <- cbind(rep(1,7)) b.vec <- c(1) solve.QP(Dmat=D.mat, dvec=d.vec, Amat=A.mat, bvec=b.vec, meq=1) D.mat <- 2*cov.mat d.vec <- rep(0,6) A.mat <- cbind(as.vector(mu.vec)) b.vec <- c(-1) solve.QP(Dmat=D.mat, dvec=d.vec, Amat=A.mat, bvec=b.vec, meq=1) D.mat <- 2*cov.mat d.vec <- rep(0,7) A.mat <- cbind(diag(7), -diag(7)) b.vec <- c(c(-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.4), -c(0.1,0.1,0.1,0.1,0.1,0.1,0.4)) solve.QP(Dmat=D.mat, dvec=d.vec, Amat=A.mat, bvec=b.vec, meq=0) w_step = 0.01 reshigh <- c(0.1,0.1,0.1,0,0,0,1) reslow <- c(0,0,0,0,0,-0.1,0) each_w <- array(data=rep(0,7),dim=7) ret <- {} vol <- {} max_sr <- 0 max_w <- {} for(i in seq(reslow[1],reshigh[1],by=w_step)) { for(j in seq(reslow[2],reshigh[2],by=w_step)) { for(k in seq(reslow[3],reshigh[3],by=w_step)) { for(l in seq(reslow[4],reshigh[4],by=w_step)) { for(m in seq(reslow[5],reshigh[5],by=w_step)) { for(n in seq(reslow[6],reshigh[6],by=w_step)) { # for(o in seq(reslow[7],reshigh[7],by=0.05)) { w_pf <- c(i,j,k,l,m,n,o) mu_pf <- mu.vec%*%w_pf vol_pf <- sqrt(252*t(w_pf)%*%cov.mat%*%w_pf) if(!is.nan(mu_pf/vol_pf) & (mu_pf/vol_pf > max_sr)) { max_w <- w_pf max_sr <- mu_pf/vol_pf } ret <- append(ret, mu_pf) vol <- append(vol, vol_pf) # } } } } } } } mu.vec%*%max_w sqrt(252*t(max_w)%*%cov.mat%*%max_w) for(arr.test in 1:3) { print(arr.test[1]) } ## Weight w_pf <- rep(1,6)/6 ## Mean, cov mu.vec <- matrix(colMeans(pf_opt_data['2012-09-30/2012-12-31',1:6]), nrow=1) cov.mat <- cov(pf_opt_data['2012-09-30/2012-12-31',1:6]) reshigh <- c(1,1,1,1,1,1) reslow <- c(0,0,0,0,0,0)/6 mu.vec <- matrix(coredata(prc_pf_opt_data['2012-12-31',1:6])/coredata(prc_pf_opt_data['2012-09-28',1:6])-1, nrow=1)*4 cov.mat <- cov(pf_opt_data['2012-09-28/2012-12-31',1:6])*252 ef <- effFrontier(mu.vec, cov.mat, shorts=T) ef <- effFrontier2(mu.vec, cov.mat, nports = 100, rlow=reslow, rhigh=reshigh) ef plot(ef$vol, ef$ret) ef$ret[which.max(ef$ret/ef$vol)] ## pf mean, sig mu_pf <- crossprod(w_pf, mu.vec) sqrt(252*t(w_pf)%*%cov(pf_opt_data[2101:2321,1:2])%*%w_pf) portfolio.optim(x=mu.vec, covmat=cov.mat, shorts = T) portfolio.optim(x=mu.vec, covmat=cov.mat, shorts = T, reslow = reslow, reshigh=reshigh) effFrontier2 = function (averet, rcov, nports = 20, shorts=T, rlow, rhigh) { mxret = max(abs(averet))/3 mnret = -mxret n.assets = ncol(averet) reshigh = rhigh reslow = rlow min.rets = seq(mnret, mxret, len = nports) vol = rep(NA, nports) ret = rep(NA, nports) for (k in 1:nports) { port.sol = NULL try(port.sol <- portfolio.optim(x=averet, pm=min.rets[k], covmat=rcov, reshigh=reshigh, reslow=reslow,shorts=shorts),silent=T) #print(min.rets[k]) if ( !is.null(port.sol) ) { vol[k] = sqrt(as.vector(port.sol$pw %*% rcov %*% port.sol$pw)) ret[k] = averet %*% port.sol$pw } } return(list(vol = vol, ret = ret)) } ## using this functions.. effFrontier_k = function (averet, rcov, nports = 20, shorts=T, wmax=1) { mxret = max(abs(averet)) mnret = -mxret n.assets = ncol(averet) reshigh = rep(wmax,n.assets) if( shorts ) { reslow = rep(-wmax,n.assets) } else { reslow = rep(0,n.assets) } min.rets = seq(mnret, mxret, len = nports) vol = rep(NA, nports) ret = rep(NA, nports) mx_sr <- 0 w <- {} for (k in 1:nports) { port.sol = NULL try(port.sol <- portfolio.optim(x=averet, pm=min.rets[k], covmat=rcov, reshigh=reshigh, reslow=reslow,shorts=shorts),silent=T) if ( !is.null(port.sol) ) { vol[k] = sqrt(as.vector(port.sol$pw %*% rcov %*% port.sol$pw)) ret[k] = averet %*% port.sol$pw if(mx_sr < ret[k]/vol[k]) { mx_sr <- ret[k]/vol[k] w <- port.sol$pw } } } return(list(vol = vol, ret = ret, mx_sr=mx_sr, w=w)) } if(require(PerformanceAnalytics)){ charts.PerformanceSummary(return_series[,1]+return_series[,2],main="Performance", geometric=FALSE) }<file_sep>/functions/effFrontier_k.R effFrontier_k = function (averet, rcov, nports = 20, shorts=T, wmax=1, tgt_vol=0.1) { mxret = max(abs(averet)) mnret = -mxret n.assets = ncol(averet) reshigh = rep(wmax,n.assets) if( shorts ) { reslow = rep(-wmax,n.assets) } else { reslow = rep(0,n.assets) } min.rets = seq(mnret, mxret, len = nports) vol = rep(NA, nports) ret = rep(NA, nports) mx_sr <- 0 mx_vol <- 0 mx_ret <- 0 w <- {} w_tgt_vol <- {} for (k in 1:nports) { port.sol = NULL try(port.sol <- portfolio.optim(x=averet, pm=min.rets[k], covmat=rcov, reshigh=reshigh, reslow=reslow,shorts=shorts),silent=T) if ( !is.null(port.sol) ) { vol[k] = sqrt(as.vector(port.sol$pw %*% rcov %*% port.sol$pw)) ret[k] = averet %*% port.sol$pw if(mx_sr < ret[k]/vol[k]) { mx_sr <- ret[k]/vol[k] w <- port.sol$pw mx_vol <- vol[k] mx_ret <- ret[k] } if(tgt_vol == round(vol[k],1)) { w_tgt_vol <- port.sol$pw } } } return(list(vol = vol, ret = ret, mx_sr=mx_sr, mx_vol = mx_vol, mx_ret = mx_ret, w=w, w_tgt_vol=w_tgt_vol)) }<file_sep>/pf_optimizer_weekly_w_sits.R require(quantmod) require(tseries) require(quadprog) require(corpcor) sapply(list.files(pattern="[.]R$", path='functions/', full.names=TRUE), source) ## Retrieving Data & Refining file1 <- "./data/pf_opt_data.csv" pf_opt_data <- read.csv(file1) pf_opt_data <- as.xts(pf_opt_data[,-1], order.by=as.POSIXct(pf_opt_data[,1], tz="UTC")) prc_pf_opt_data <- pf_opt_data getSymbols("SPY", src = 'yahoo', from = '2003-01-01', auto.assign = T) pf_opt_data <- Cl(adjustOHLC(get("SPY"), use.Adjusted=T)) tickers <- c("QQQ", "EEM", "IWM", "EFA", "TLT", "IYR", "GLD") for(ticker in tickers) { getSymbols(ticker, src = 'yahoo', from = '2003-01-01', auto.assign = T) pf_opt_data <- cbind(pf_opt_data, Cl(adjustOHLC(get(ticker), use.Adjusted=T))) } w_pf_opt_data <- {} w_pf_opt_data <- to.period(pf_opt_data[,1], period='weeks')[,4] # To Weekly for (i in 2:NCOL(pf_opt_data)) { w_pf_opt_data <- cbind(w_pf_opt_data, to.period(pf_opt_data[,i], period='weeks')[,4]) } names(w_pf_opt_data) <- names(pf_opt_data) prc_pf_opt_data <- w_pf_opt_data # Change to return data for (i in 1:NCOL(pf_opt_data)) { w_pf_opt_data[,i] <- ROC(w_pf_opt_data[,i], type="discrete") } ## end of data refining ## backtesting part # 1: SPX, 2:NKY, 3: SX5E, 4:Copper, 5:WTI, 6:Gold, 7:UST10Y Fut # settings: 1.Selecting assets to optimize, 2.Target Vol level, 3.lookback period start_i <- 2 assetsToTest <- 1:NCOL(w_pf_opt_data) cash_asset <- 7 targetVolLv <- 0.1 lookback <- 13 return_series <- xts(x=matrix(c(0,0), nrow=1), order.by=index(w_pf_opt_data[lookback+start_i])) weight <- xts(x=matrix(c(rep(0,NCOL(w_pf_opt_data))), nrow=1), order.by=index(w_pf_opt_data[lookback+start_i])) #loop for(i in (lookback+start_i):(nrow(w_pf_opt_data)-1)) { #Checking Return uplimit <- as.vector(ifelse(coredata(prc_pf_opt_data[i]) /coredata(prc_pf_opt_data[i-lookback+1])-1>0, 1,0)) downlimit <- as.vector(ifelse(coredata(prc_pf_opt_data[i]) /coredata(prc_pf_opt_data[i-lookback+1])-1<0, -1,0)) mu.vec <- as.vector(coredata(prc_pf_opt_data[i]) /coredata(prc_pf_opt_data[i-lookback+1])-1) #cov.mat cov.mat <- cov(w_pf_opt_data[(i-lookback+1):i,assetsToTest]) cov.mat <- make.positive.definite(cov.mat, 0.000000001) ### Optimizing part D.mat <- 2*cov.mat d.vec <- rep(0,NCOL(w_pf_opt_data)) # A.mat <- cbind(rep(1,NCOL(w_pf_opt_data))) # b.vec <- c(1) #b.vec <- c(1, rep(-1,6), -rep(1,6)) A.mat <- cbind(mu.vec, diag(NCOL(w_pf_opt_data)), -diag(NCOL(w_pf_opt_data))) b.vec <- c(0.1, downlimit, -uplimit) #rep(-1,NCOL(w_pf_opt_data)),-rep(1,NCOL(w_pf_opt_data))) # optimized <- solve.QP(Dmat=D.mat, dvec=d.vec, Amat=A.mat, bvec=b.vec, meq=1) optimized$solution adj_w <- optimized$solution weight <- rbind(weight,xts(x=matrix(adj_w,nrow=1), order.by=index(w_pf_opt_data[i+1]))) #pp <- portfolio.optim(x=matrix(mu.vec, nrow=1), pm=0.1, covmat=cov.mat, # reshigh=rep(1,NCOL(w_pf_opt_data)), reslow=rep(-1,NCOL(w_pf_opt_data)),shorts=TRUE,silent=T) #sqrt(optimized$solution %*% cov.mat %*% optimized$solution) #sqrt(pp$pw %*% cov.mat %*% pp$pw) # #calculate max sharpe ratio weight # ef <- effFrontier_k(mu.vec, cov.mat) # #adjust vol to certain level # adj_w <- targetVolLv/ef$mx_vol*ef$w #ef$w_tgt_vol #calculate realized return return_i <- matrix(w_pf_opt_data[i+1], nrow=1) %*% adj_w return_c <- return_i#as.numeric((1-targetVolLv/ef$mx_vol)*(coredata(monthly_data[i+1,cash_asset])/coredata(monthly_data[i,cash_asset])-1)) #add to return index return_series <- rbind(return_series,xts(x=matrix(c(return_i, return_c),nrow=1), order.by=index(w_pf_opt_data[i+1]))) } #end of loop plot(ef$vol, ef$ret)<file_sep>/pf_optimizer_weekly_v1.0.R require(quantmod) require(tseries) require(quadprog) require(corpcor) sapply(list.files(pattern="[.]R$", path='functions/', full.names=TRUE), source) ## Retrieving Data & Refining file1 <- "./data/pf_opt_data.csv" pf_opt_data <- read.csv(file1) pf_opt_data <- as.xts(pf_opt_data[,-1], order.by=as.POSIXct(pf_opt_data[,1], tz="UTC")) prc_pf_opt_data <- pf_opt_data getSymbols("SPY", src = 'yahoo', from = '2004-01-01', auto.assign = T) pf_opt_data <- Cl(adjustOHLC(get("SPY"), use.Adjusted=T)) tickers <- c("EFA", "EWJ", "EEM", "IYR", "RWX", "IEF", "TLT", "DBC", "GLD") for(ticker in tickers) { getSymbols(ticker, src = 'yahoo', from = '2004-01-01', auto.assign = T) pf_opt_data <- cbind(pf_opt_data, Cl(adjustOHLC(get(ticker), use.Adjusted=T))) } w_pf_opt_data <- {} w_pf_opt_data <- to.period(pf_opt_data[,1], period='weeks')[,4] # To Weekly for (i in 2:NCOL(pf_opt_data)) { w_pf_opt_data <- cbind(w_pf_opt_data, to.period(pf_opt_data[,i], period='weeks')[,4]) } names(w_pf_opt_data) <- names(pf_opt_data) ## Add Cash w_pf_opt_data <- cbind(w_pf_opt_data, rep(100,NROW(w_pf_opt_data))) names(w_pf_opt_data)[NCOL(w_pf_opt_data)] <- "Cash" prc_pf_opt_data <- w_pf_opt_data # Change to return data for (i in 1:NCOL(w_pf_opt_data)) { w_pf_opt_data[,i] <- ROC(w_pf_opt_data[,i], type="discrete") } ## end of data refining ## backtesting part # 1: SPX, 2:NKY, 3: SX5E, 4:Copper, 5:WTI, 6:Gold, 7:UST10Y Fut # settings: 1.Selecting assets to optimize, 2.Target Vol level, 3.lookback period topn <- 4 start_i <- 2#167#2#60 assetsToTest <- 1:NCOL(w_pf_opt_data) cash_asset <- 7 targetVolLv <- 0.1 lookback <- 13 vollookback <- 52 return_series <- xts(x=matrix(rep(0,4), nrow=1), order.by=index(w_pf_opt_data[lookback+start_i])) names(return_series) <- c("All_Min_Var","Equal_W","Momentum","Momentum_Min_Var") weight <- xts(x=matrix(c(rep(0,NCOL(w_pf_opt_data))), nrow=1), order.by=index(w_pf_opt_data[lookback+start_i])) weight2 <- xts(x=matrix(c(rep(0,topn)), nrow=1), order.by=index(w_pf_opt_data[lookback+start_i])) volhist <- xts(x=matrix(c(rep(0,1)), nrow=1), order.by=index(w_pf_opt_data[lookback+start_i])) #loop for(i in (vollookback+start_i):(nrow(w_pf_opt_data)-1)) { #Checking Return uplimit <- as.vector(ifelse(coredata(prc_pf_opt_data[i]) /coredata(prc_pf_opt_data[i-lookback])-1>0, 1,0)) downlimit <- as.vector(ifelse(coredata(prc_pf_opt_data[i]) /coredata(prc_pf_opt_data[i-lookback])-1<0, -1,0)) uplimit[7] <- 1 downlimit[7] <- -1 uplimit[8] <- 1 downlimit[8] <- 0 mu.vec <- as.vector(coredata(prc_pf_opt_data[i]) /coredata(prc_pf_opt_data[i-lookback])-1)*52/lookback #Momentum Part topindex <- ntop(mu.vec,topn) #nbottom(mu.vec, topn) #cov.mat cov.mat <- cov(w_pf_opt_data[(i-vollookback):i,assetsToTest])*52 ef2 <- effFrontier_k2(mu.vec, cov.mat, nports=20, reslow=rep(-1,NCOL(w_pf_opt_data)), reshigh=rep(1,NCOL(w_pf_opt_data)), tgt_vol=0.1) #effFrontier_k2(mu.vec, cov.mat, nports=20, reslow=downlimit, reshigh=uplimit, tgt_vol=0.1) ef3 <- effFrontier_k2(mu.vec, cov.mat, nports=20, reslow=downlimit, reshigh=uplimit, psum=1, tgt_vol=0.1) adj_w <- ef3$w_tgt_vol if(is.null(adj_w)) { print(paste("warning no weight for",index(w_pf_opt_data[i]),sep=" ")) adj_w <- rep(0,NCOL(w_pf_opt_data)) } adj_w <- round(adj_w, digit=2) #Storing data volhist <- rbind(volhist,xts(x=matrix(sqrt(adj_w%*%cov.mat%*%adj_w),nrow=1), order.by=index(w_pf_opt_data[i]))) mu.vec <- as.vector(coredata(prc_pf_opt_data[i,topindex]) /coredata(prc_pf_opt_data[i-lookback,topindex])-1)*52/lookback cov.mat <- cov(w_pf_opt_data[(i-vollookback):i,topindex])*52 ef4 <- effFrontier_k2(mu.vec, cov.mat, nports=20, reslow=rep(0,topn), reshigh=rep(1,topn), psum=1, tgt_vol=0.1) adj_w2 <- ef4$w if(is.null(adj_w2)) { print(paste("warning2 no weight for",index(w_pf_opt_data[i]),sep=" ")) adj_w2 <- rep(0,topn) } adj_w2 <- round(adj_w2, digit=2) # Storing Value weight <- rbind(weight,xts(x=matrix(adj_w,nrow=1), order.by=index(w_pf_opt_data[i+1]))) if (!is.null(adj_w2)) { weight2 <- rbind(weight2,xts(x=matrix(adj_w2,nrow=1), order.by=index(w_pf_opt_data[i+1]))) } else { weight2 <- rbind(weight2,xts(x=matrix(c(rep(NA,topn)),nrow=1), order.by=index(w_pf_opt_data[i+1]))) } #calculate realized return return_w <- matrix(w_pf_opt_data[i+1], nrow=1) %*% adj_w return_e <- matrix(w_pf_opt_data[i+1], nrow=1) %*% rep(1/NCOL(w_pf_opt_data),NCOL(w_pf_opt_data)) return_me <- matrix(w_pf_opt_data[i+1, topindex], nrow=1) %*% rep(1/topn,topn) return_mw <- matrix(w_pf_opt_data[i+1, topindex], nrow=1) %*% adj_w2 #add to return index return_series <- rbind(return_series,xts(x=matrix(c(return_w, return_e, return_me, return_mw),nrow=1), order.by=index(w_pf_opt_data[i+1]))) } #end of loop plot(ef3$vol, ef3$ret)<file_sep>/functions/effFrontier_k3.R effFrontier_k3 = function (averet, rcov, nports = 20, reslow, reshigh, tgt_vol=0.1) { # Return Setting mxret = max(abs(averet)) mnret = -mxret min.rets = seq(mnret, mxret, len = nports) # Setting Output Variables vol <- rep(NA, nports) ret<- rep(NA, nports) mx_sr <- 0 mx_vol <- 0 mx_ret <- 0 w <- {} w_tgt_vol <- {} # Loading libarary for solve.QP require(quadprog) require(corpcor) for (k in 2:nports) { port.sol <- NULL try(port.sol <- portfolio.optim(x=averet, pm=min.rets[k], covmat=rcov, reshigh=reshigh, reslow=reslow, shorts=TRUE),silent=T) if ( !is.null(port.sol) ) { vol[k] = sqrt((port.sol$pw %*% rcov %*% port.sol$pw)) ret[k] = averet %*% port.sol$pw if(mx_sr < ret[k]/vol[k]) { mx_sr <- ret[k]/vol[k] w <- port.sol$pw mx_vol <- vol[k] mx_ret <- ret[k] } if(tgt_vol == round(vol[k],1)) { w_tgt_vol <- port.sol$pw } } } return(list(vol = vol, ret = ret, mx_sr=mx_sr, mx_vol = mx_vol, mx_ret = mx_ret, w=w, w_tgt_vol=w_tgt_vol)) }<file_sep>/mkt_data_view_EC_v1.1.R require(quantmod) require(pastecs) require(ggplot2) require(corrgram) require(car) sapply(list.files(pattern="[.]R$", path='functions/', full.names=TRUE), source) ## Retrieving Data & Refining file1 <- "./data/Stock_Indice.csv" Asset_data <- read.csv(file1) Asset_data <- as.xts(Asset_data[,-1], order.by=as.POSIXct(Asset_data[,1])) file2 <- "./data/EC_Econ_Indicators.csv" Indicators <- read.csv(file2) Indicators <- as.xts(Indicators[,-1], order.by=as.POSIXct(Indicators[,1])) # Change Asset data into return data for (i in 1:NCOL(Asset_data)) { Asset_data[,i] <- ROC(Asset_data[,i], n=1, type="continuous") } # Change Indicators ## Add 100 to negative value for (i in 1:4) { Indicators[,i] <- Indicators[,i] + 100 } ## Apply change for (i in 1:10) { Indicators[,i] <- ROC(Indicators[,i], type="continuous") } ## Lagging for (i in 1:11) { Indicators[,i] <- lag(Indicators[,i], k=1) } for (i in 12:14) { Indicators[,i] <- lag(Indicators[,i], k=2) } for (i in 15:20) { Indicators[,i] <- lag(Indicators[,i], k=3) } #1.Summary of Statistics stat.desc(Indicators) for (i in 1:14) { hist(Indicators[,i]) } #2.Correlation Table corstarsl(Indicators) corstarsl(cbind(Asset_data, Indicators)[-3:-1])[6:25,1:5] #Pearson Corr corstarsl(cbind(Asset_data, Indicators)[-3:-1],type="spearman")[6:25,1:5] #Spearman Corr corstarsl(cbind(Asset_data, Indicators)['2008-03/'])[6:25,1:5] #Pearson Corr corstarsl(cbind(Asset_data, Indicators)['2008-03/'],type="spearman")[6:25,1:5] #Spearman Corr #3.Scatter Plot plot(coredata(GTAA_data[,5]), coredata(lag(GTAA_data[,18],k=0)), pch=19) abline(v=0, h=1) abline(h=-1) scatterplotMatrix(cbind(coredata(GTAA_data['2005/',6]),coredata(GTAA_data['2005/',8:13]))) scatterplotMatrix(cbind(coredata(GTAA_data['2005/',1]),coredata(Macro_sig['2005/']))) #4.Regression<file_sep>/mkt_data_view_v1.0.R require(quantmod) require(pastecs) require(ggplot2) require(corrgram) require(car) sapply(list.files(pattern="[.]R$", path='functions/', full.names=TRUE), source) ## Retrieving Data & Refining file1 <- "./data/GTAA_data.csv" GTAA_data <- read.csv(file1) GTAA_data <- as.xts(GTAA_data[,-1], order.by=as.POSIXct(GTAA_data[,1])) tmp <- GTAA_data[,c(9,11)] # Change Asset data into return data # filter1. 3M return for (i in 1:7) { GTAA_data <- cbind(GTAA_data,ROC(GTAA_data[,i], n=3, type="discrete")) GTAA_data[,i+13] <- GTAA_data[,20+i] / GTAA_data[,i+13]*100 # Filter3 Sharpe Ratio } GTAA_data[,21:27] <- lag(GTAA_data[,21:27]) GTAA_data[,14:20] <- lag(GTAA_data[,14:20]) for (i in 1:13) { GTAA_data[,i] <- ROC(GTAA_data[,i], type="discrete") } GTAA_data[,c(9,11)] <- tmp GTAA_data[,9] <- GTAA_data[,9] - lag(GTAA_data[,9]) GTAA_data[,8:11] <- lag(GTAA_data[,8:11], k=2) GTAA_data[,12:13] <- lag(GTAA_data[,12:13], k=1) # Filter2 lagging. Difference applied ## Others are all rate of change except cpi yoy which apply net change Macro_sig <- ifelse(GTAA_data[,8] > 0, 1, -1) for (i in 9:12) { Macro_sig <- Macro_sig + ifelse(GTAA_data[,i] > 0, 1, -1) } Macro_sig <- Macro_sig + ifelse(GTAA_data[,13] < 0, 1, -1) #1.Summary of Statistics stat.desc(GTAA_data) for (i in 1:27) { hist(GTAA_data[,i]) } #2.Correlation Table corstarsl(GTAA_data[,1:7]) corstarsl(GTAA_data[,8:13]) corstarsl(GTAA_data['2005/']) corrgram(coredata(GTAA_data['2005/']), order=FALSE, lower.panel=panel.shade, upper.panel=panel.pie, text.panel=panel.txt) #3.Scatter Plot plot(coredata(GTAA_data[,5]), coredata(lag(GTAA_data[,18],k=0)), pch=19) abline(v=0, h=1) abline(h=-1) scatterplotMatrix(cbind(coredata(GTAA_data['2005/',6]),coredata(GTAA_data['2005/',8:13]))) scatterplotMatrix(cbind(coredata(GTAA_data['2005/',1]),coredata(Macro_sig['2005/']))) #4.Regression<file_sep>/functions/effFrontier_k2.R effFrontier_k2 = function (averet, rcov, nports = 20, reslow, reshigh, psum=1, tgt_vol=0.1) { # Return Setting if(!is.null(reslow) && !is.null(reshigh)) { mxret = max(abs(c(averet*reslow, averet*reshigh))) } else { mxret = max(abs(averet)) } mnret = -mxret min.rets = seq(mnret, mxret, len = nports) # Setting Output Variables vol <- rep(NA, nports) ret<- rep(NA, nports) mx_sr <- 0 mx_vol <- 0 mx_ret <- 0 w <- {} w_tgt_vol <- {} w_min_vol <- {} # Loading libarary for solve.QP require(quadprog) require(corpcor) ### Optimizing part1 cov.mat <- make.positive.definite(rcov, 0.000000001) D.mat <- 2*cov.mat d.vec <- rep(0,length(averet)) for (k in 1:nports) { port.sol <- NULL ### Optimizing part2 if(!is.null(psum)) { A.mat <- cbind(averet, rep(1,length(averet)), diag(length(averet)), -diag(length(averet))) b.vec <- c(min.rets[k], psum, reslow, -reshigh) } else { A.mat <- cbind(averet, diag(length(averet)), -diag(length(averet))) b.vec <- c(min.rets[k], reslow, -reshigh) } try(port.sol <- solve.QP(Dmat=D.mat, dvec=d.vec, Amat=A.mat, bvec=b.vec, meq=2),silent=T) if ( !is.null(port.sol) ) { vol[k] = sqrt((port.sol$solution %*% rcov %*% port.sol$solution)) ret[k] = averet %*% port.sol$solution if(mx_sr < ret[k]/vol[k]) { mx_sr <- ret[k]/vol[k] w <- port.sol$solution mx_vol <- vol[k] mx_ret <- ret[k] } if(tgt_vol == round(vol[k],1)) { w_tgt_vol <- port.sol$solution } } } ## Calculate Min Var A.mat <- cbind(rep(1,length(averet)), diag(length(averet)), -diag(length(averet))) b.vec <- c(psum, reslow, -reshigh) try(port.sol <- solve.QP(Dmat=D.mat, dvec=d.vec, Amat=A.mat, bvec=b.vec, meq=2),silent=T) w_min_vol <- port.sol$solution return(list(vol = vol, ret = ret, mx_sr=mx_sr, mx_vol = mx_vol, mx_ret = mx_ret, w=w, w_tgt_vol=w_tgt_vol, w_min_vol=w_min_vol)) }
bff497ca45f7018df1100e09338d1a77cf14f528
[ "R" ]
17
R
githubfun/ksmv
44b89a1cda67908fb6ba0b0847121b8ddc0c4bb2
f799e7525e9ee9ce643e3966424148388fb86886
refs/heads/master
<file_sep># blog 使用nodejs的框架express+mongodb实现多人博客,使用路由实现单页应用 主要实现的功能有: 登录注册  博客浏览  发表博客  评论  划分博客标签  统计博客量  统计浏览量 ... <file_sep>var crypto = require('crypto'), //是 nodejs的一个核心模块,用来生成散列值来加密密码 User = require('../models/user.js'); Post = require('../models/post.js'); Comment = require('../models/comment.js'); // var express = require('express'); // var router = express.Router(); /* GET home page. */ // router.get('/', function(req, res, next) { // res.render('index', { title: 'Express' }); // }); // module.exports = router; module.exports = function(app){ app.get('/',function (req,res) { //判断是否是第一页,并把请求的页数装换成number类型 var page = req.query.p ? parseInt(req.query.p):1; //查询并返回第page页的10篇文章 Post.getTen(null,page,function(err,posts,total){ if (err) { posts = []; }; res.render('index',{ title:'主页', user:req.session.user, posts: posts, page:page, isFirstPage:(page - 1)==0, isLastPage:((page - 1)*10 + posts.length)==total, success:req.flash('success').toString(), error:req.flash('error').toString() }) }) }); app.get('/reg',checkNotLogin); app.get('/reg',function(req,res){ res.render('reg',{ title:'注册', user:req.session.user, success:req.flash('success').toString(), error:req.flash('error').toString() }) }); app.post('/reg',checkNotLogin); app.post('/reg',function(req,res){ var name = req.body.name, password = req.body.password, password_re = req.body['password-repeat']; //检验用户两次输入的密码是否一致 if(password_re != password){ req.flash('error','两次输入的密码不一致!'); return res.redirect('/reg');//返回注册页 } //生成密码的md5值 var md5 = crypto.createHash('md5'), password = md5.update(req.body.password).digest('hex'); var newUser = new User({ name: req.body.name, password: <PASSWORD>, email: req.body.email }); //检查用户名是否已经存在 User.get(newUser.name,function(err, user){ if(err){ req.flash('error', err); return res.redirect('/'); } if(user){ req.flash('error','用户已存在!'); return res.redirect('/reg');//返回注册页 } //如果不存在则新增用户 newUser.save(function(err,user){ if(err){ req.flash('error',err); return res.redirect('/reg');//注册失败返回注册页 } req.session.user = user;//用户信息存入session req.flash('success','注册成功!'); res.redirect('/');//注册成功后返回主页 }); }); }); app.get('login',checkNotLogin); app.get('/login',function(req,res){ res.render('login',{ title:'登录', user:req.session.user, success:req.flash('success').toString(), error:req.flash('error').toString() }) }); app.post('/login',checkNotLogin); app.post('/login',function(req,res){ //生成密码的md5值 var md5 = crypto.createHash('md5'), password = md5.update(req.body.password).digest('hex'); //检查用户是否存在 User.get(req.body.name,function(err, user){ if (!user) { req.flash('error','用户不存在!'); return res.redirect('/login');//用户不存在则跳转到登录页 }; //检查密码是否一致 if (user.password != password) { console.log(user.password+"="+password) req.flash('error','密码错误!'); return res.redirect('/login');//密码错误则跳转到登录页 }; //用户名密码都匹配之后,将用户信息存入session req.session.user = user; req.flash('success','登录成功!'); res.redirect('/');//登录成功后跳转到首页 }) }); app.get('/post',checkLogin); app.get('/post',function(req,res){ res.render('post',{ title:'发表', user:req.session.user, success:req.flash('success').toString(), error:req.flash('error').toString() }); }); app.post('/post',checkLogin); app.post('/post',function(req,res){ var currentUser = req.session.user, tags = [req.body.tag1,req.body.tag2,req.body.tag3], post = new Post(currentUser.name, currentUser.head ,req.body.title,tags,req.body.post); post.save(function(err){ if (err) { req.flash('error',err); return res.redirect('/'); }; req.flash('success','发布成功!'); res.redirect('/');//发表成功跳转到主页 }); }); app.get('/logout',checkLogin); app.get('/logout',function(req,res){ req.session.user = null; req.flash('success','登出成功!'); res.redirect('/');//登出成功后跳转到首页 }) app.get('/upload',checkLogin); app.get('/upload',function(req, res){ res.render('upload',{ title: '文件上传', user: req.session.user, success:req.flash('success').toString(), error:req.flash('error').toString() }) }) app.post('/upload',checkLogin); app.post('/upload',function(req,res){ req.flash('success','文件上传成功!'); res.redirect('/upload'); }) app.get('/archive',function(req,res){ Post.getArchive(function(err,posts){ if (err) { req.flash('error',err); return res.redirect('/'); }; res.render('archive',{ title:'存档', posts:posts, user:req.session.user, success:req.flash('success').toString(), error:req.flash('error').toString() }) }) }) app.get('/tags',function(req,res){ Post.getTags(function(err,posts){ if (err) { req.flash('error',err); return res.redirect('/'); }; res.render('tags',{ title:'标签', posts:posts, user:req.session.user, success:req.flash('success').toString(), error:req.flash('error').toString() }) }) }) app.get('/tags/:tag',function(req,res){ Post.getTag(req.params.tag, function(err,posts){ if (err) { req.flash('error',err); return res.redirect('/'); }; res.render('tag',{ title:'TAG:'+ req.params.tag, posts: posts, user:req.session.user, success:req.flash('success').toString(), error:req.flash('error').toString() }) }) }) app.get('/links', function(req,res){ res.render('links',{ title:'友情链接', user:req.session.user, success:req.flash('success').toString(), error:req.flash('error').toString() }) }) app.get('/search', function(req,res){ Post.search(req.query.keyword, function(err, posts){ if (err) { req.flash('error',err); return res.redirect('/'); }; res.render('search',{ title:'SEARCH:'+req.query.keyword, posts:posts, user:req.session.user, success:req.flash('success').toString(), error:req.flash('error').toString() }) }) }) app.get('/u/:name',function(req, res){ var page = req.query.p ? parseInt(req.query.p):1; //检查用户是否存在 User.get(req.params.name, function(err, user){ if(!user){ req.flash('error','用户不存在!'); return res.redirect('/');//用户不存在则跳转到主页 }; //查询并返回该用户的第page页的10篇文章 Post.getTen(user.name, page,function(err, posts, total){ if (err) { req.flash('error',err); return redirect('/'); }; res.render('user',{ title:'主页', user:req.session.user, posts: posts, page:page, isFirstPage:(page - 1)==0, isLastPage:((page - 1)*10 + posts.length)==total, success:req.flash('success').toString(), error:req.flash('error').toString() }) }) }) }) app.get('/u/:name/:day/:title',function(req,res){ Post.getOne(req.params.name,req.params.day, req.params.title, function(err,post){ if (err) { req.flash('error',err); return res.redirect('/'); }; res.render('article',{ title: req.params.title, post:post, user:req.session.user, success:req.flash('success').toString(), error:req.flash('error').toString() }) }) }) app.post('/u/:name/:day/:title',function(req,res){ var date = new Date(), time = date.getFullYear() + '-' + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + (date.getMinutes()<10?'0' + date.getMinutes():date.getMinutes()); var md5 = crypto.createHash('md5'), email_MD5 = md5.update(req.body.email.toLowerCase()).digest('hex'), head = "http://www.gravatar.com/avatar/"+ email_MD5 + "?s=48"; var comment = { name: req.body.name, head: head, email:req.body.email, website:req.body.website, time:req.body.time, content:req.body.content }; var newComment = new Comment(req.params.name, req.params.day, req.params.title, comment); newComment.save(function(err){ if (err) { req.flash('error',err); return res.redirect('back'); }; req.flash('success','留言成功!'); res.redirect('back'); }) }) app.get('/edit/:name/:day/:title',checkLogin); app.get('/edit/:name/:day/:title',function(req,res){ var currentUser = req.session.user; Post.edit(currentUser.name, req.params.day,req.params.title, function(err,post){ if (err) { req.flash('error',err); return res.redirect('back'); }; res.render('edit',{ title:'编辑', post:post, user: req.session.user, success: req.flash('success').toString(), error:req.flash('error').toString() }) }) }) app.post('/edit/:name/:day/:title',checkLogin); app.post('/edit/:name/:day/:title',function(req,res){ var currentUser = req.session.user; Post.update(currentUser.name, req.params.day, req.params.title, req.body.post, function(err){ var url = encodeURI('/u/'+ req.params.name+'/' + req.params.day + '/' + req.params.title); if (err) { req.flash('error',err); return res.redirect('url');//出错,返回文章页 }; req.flash('success','修改成功!'); res.redirect(url);//成功!返回文章页 }) }) app.get('/remove/:name/:day/:title',checkLogin); app.get('/remove/:name/:day/:title', function(req, res){ var currentUser = req.session.user; Post.remove(currentUser.name, req.params.day, req.params.title, function(err){ if (err) { req.flash('error',err); return res.redirect('back'); }; req.flash('success','删除成功!'); res.redirect('/'); }) }) app.get('/reprint/:name/:day/:title',checkLogin); app.get('/reprint/:name/:day/:title', function(req, res){ Post.edit(req.params.name, req.params.day, req.params.title, function(err, post){ if (err) { req.flash('error' ,err); return res.redirect('back'); }; var currentUser = req.session.user, reprint_from = { name:post.name, day:post.time.day, title:post.title } reprint_to = { name:currentUser.name, head:currentUser.head } Post.reprint(reprint_from, reprint_to, function(err, post){ if (err) { req.flash('error', '失败'); // console.log(err) return res.redirect('back'); }; req.flash('success', '转载成功!'); var url=encodeURI('/u/' + post.name+'/'+post.time.day+'/'+post.title); //跳转到转载后的文章页面 res.redirect(url); }) }) }) app.use(function(req,res){ res.render('404'); }) function checkLogin(req, res, next){ if(!req.session.user) { req.flash('error','未登录!'); res.redirect('/login'); } next();//?转移控制权 } function checkNotLogin(req, res, next){ if( req.session.user){ req.flash('success', '已登录!'); res.redirect('back');//返回之前的页面 } next(); } }
08e5de1503372edc4d94aca6187b97ddc1094fd5
[ "Markdown", "JavaScript" ]
2
Markdown
chenshaoling/blog
e341d5ceb4b32069a5cc1011f8bf90bed5e4d811
498473d1507bb7cd7c3450c79dbfee95ae934ad4
refs/heads/master
<file_sep>#include "LList.hpp" #include <iostream> using namespace std; int main() { LList<int> intList; LList<string> stringList; cout << "Integer list: " << intList << endl; cout << "String list: " << stringList << endl; intList.InsertLast (-1); intList.InsertFirst(10); stringList.InsertFirst("Hello"); stringList.InsertLast("World"); cout << "Integer list: " << intList << endl; cout << "String list: " << stringList << endl; intList.SetDirection (BACKWARD); stringList.SetDirection (BACKWARD); cout << "Integer list: " << intList << endl; intList.SetDirection(FORWARD); stringList.SetDirection (FORWARD); cout << "Integer list: " << intList << endl; cout << "String list: " << stringList << endl; return 0; } <file_sep>/********************************************************************* * Assignment: Lab 10 - Sincgly Linked List implementation * * Author: <NAME> * * Date: Fall 2017 * * File: LList.hpp * * * * Description: This file contains the class for LList and its * * components * *********************************************************************/ #ifndef LLIST_HPP #define LLIST_HPP #include <iostream> using namespace std; enum dtype {FORWARD,BACKWARD}; template <class LT> class LList; template <class LT> ostream & operator << (ostream & outs, const LList <LT> & L); /********************************************************************* * Class: LList * * * * Description: This class is designed to hold all the member functions * and parts of the linked list, the LNode struct and its contents. * *********************************************************************/ template <class LT> class LList { private: struct LNode { LNode (); void PrintNode (ostream & output); LT data; LNode * next; }; public: LList (); LList (const LList & other); ~LList (); LList & operator = (const LList & other); bool operator == (const LList & other); int Size () const; void SetDirection (dtype dir); dtype GetDirection () const; friend ostream & operator << <> (ostream & outs, const LList<LT> & L); // friend ostream & operator << (ostream & outs, const LList & L); bool InsertFirst ( const LT & value); bool InsertLast (const LT & value); //bool InsertFirst (const int & value); // bool InsertLast (const int & value); bool DeleteFirst (); bool DeleteLast (); private: LNode * first; LNode * last; int size; dtype direction; }; /******************************************************************************* * Function: LList::LNode::LNode() * * * * Parameters: None * * Return value: None * * Description: This function will initialize the variables for the LNodes. * *******************************************************************************/ template <class LT> LList<LT>::LNode::LNode () { // data = 0; next = NULL; } // template <class LT> void LList<LT>::LNode::PrintNode (ostream & output) { if (next != NULL) next -> PrintNode (output); if (next != NULL) output << ' '; output << data; } /******************************************************************************* * Function: LList:: LList() * * * * Parameters: None * * Return value: None * * Description: This function will initialize all of the variables of the LList * * class * *******************************************************************************/ template <class LT> LList<LT>::LList () { size = 0; first = NULL; direction = FORWARD; } /********************************************************************* * Function: LList::LList (const LList & other) * * * * Parameters: LList , other * * Return value: none; * * Description: This function will copy the data values of other to * * *********************************************************************/ template <class LT> LList<LT>::LList (const LList & other) { size = 0; first = NULL; last = NULL; LNode * temp= first; for (LNode *n = other.first; n != NULL; n = n-> next) { InsertLast(n -> data); } direction = other.direction; } /********************************************************************* * Function: LList::~LList() * * * * Parameters: NONE * * Return value: NONE * * Description: This function will delete first. * *********************************************************************/ template <class LT> LList<LT>::~LList () { while (first != NULL) DeleteFirst(); } /********************************************************************* * Function: LList & LList :: operator = (const LList & other) * * * * Parameters: LList, other * * Return value: this * * Description: This function will assign all the elements in the * * current list and make it equal to other. * *********************************************************************/ template <class LT> LList<LT> & LList<LT>::operator = (const LList<LT> & other) { if (this == & other) { return * this; } while (first != NULL) DeleteFirst(); for (LNode * n = other.first; n!= NULL; n= n-> next) InsertLast(n->data); direction = other.direction; return * this; } /********************************************************************* * Function:bool LList::operator == (const LList & other) * * * * Parameters: LList, other * * Return value: bool * * Description: This function will copy the data from other into the * * LList. * *********************************************************************/ template <class LT> bool LList<LT>::operator == (const LList & other) { if (size != other.size) return false; LNode * n = first; LNode * m = other.first; while (n!= NULL) { if (n->data != m -> data) return false; n = n-> next; m = m->next; } return true; } /********************************************************************* * Function: int LList::Size() * * * * Parameters: None * * Return value: size * * Description: This function will return the value of size * *********************************************************************/ template <class LT> int LList<LT>::Size () const { return size; } template <class LT> void LList<LT>::SetDirection (dtype dir) { direction = dir; } template <class LT> dtype LList<LT>::GetDirection () const { return direction; } /********************************************************************* * Function: ostream & operator << (ostream & outs, const LList & L * * * * Parameters: LList, L, ostream, outs * * Return value: outs * * Description: This function will display the data values followed by* * spaces. * *********************************************************************/ template <class LT> ostream & operator << (ostream & outs, const LList<LT> & L) { if (L.first == NULL) return outs; if (L.direction == FORWARD) {//print the lsit from beginning (first) to end outs << L.first -> data; typename LList<LT>::LNode * n; for (n = L.first -> next; n != NULL; n = n->next) outs << ' ' << n-> data; } else //L.direction == Backward { //print the list from end to beginning L.first->PrintNode(outs); } return outs; /* LList::LNode * n = L.first; while (n!=NULL) { outs << n->data << ' '; n= n-> next; } return outs; */ } /********************************************************************* * Function: bool LList::InsertFirst (const int & value) * * * * Parameters: value * * Return value: True or False * * Description: This function will insert a new LNode at the beginning * of the linked list and increment size. * *********************************************************************/ template <class LT> bool LList<LT>::InsertFirst (const LT & value) { LNode * nn = new LNode; if (nn==NULL) return false; nn->data = value; nn -> next = first; first = nn; if (size ==0) { last = nn; } size++; return true; } /********************************************************************* * Function: bool LList::InsertLast(const int & value) * * * * Parameters: value * * Return value: bool * * Description: This function will check whether the linked list is * * empty and and insert a node as the first and last, if it is not * * empty it will insert a LNode at the end and update the size. * *********************************************************************/ template <class LT> bool LList<LT>::InsertLast (const LT & value) { if (size == 0) return InsertFirst(value); LNode * nn = new LNode; if (nn == NULL) return false; nn -> data = value; last -> next = nn; last = nn; size++; return true; } /********************************************************************* * Function:bool LList::DeleteFirst() * * * * Parameters: NONE * * Return value: bool * * Description: This function will delete the first data object in the* * linked list and decrement size. * *********************************************************************/ template <class LT> bool LList<LT>::DeleteFirst () { if (first == NULL ) return false; LNode * n = first; first = n -> next; delete n; size--; if (size == 0) last = NULL; return true; } /********************************************************************* * Function: bool LList::DeleteLast() * * * * Parameters: None * * Return value: bool * * Description: This function will delete that last data object in the* * linked list and decrement size. * *********************************************************************/ template <class LT> bool LList<LT>::DeleteLast () { if (size == 0 ) return false; if (size ==1) return DeleteFirst(); LNode *p = first; while (p-> next != last) p = p->next; p->next = NULL; delete last; last = p; size--; return false; } #endif
964596bf67cddcf7bb3f6278003ccdc9b4857dcc
[ "C++" ]
2
C++
jongil16/Lab10
bc91cfb4bcf6a7262231b001f6aef6df58b909c7
7874ae72705dd0067bd67e7c5486aef5f8eadf1b
refs/heads/master
<repo_name>ernesto2108/helpnwn-service<file_sep>/account-service/internal/infrastructure/web/account_endpoint.go package account_service import ( "net/http" service "github.com/ernesto2108/helpnwn-service/account-service/internal/domain/ports" ) func SignIn(w http.ResponseWriter, r *http.Request) { } func SignUp(w http.ResponseWriter, r *http.Request) { } type UserEndPoint struct { service.AccountService }<file_sep>/account-service/internal/infrastructure/utils/null/data_null.go package user_service import ( "database/sql" "time" "github.com/lib/pq" ) func TimeToNull(t time.Time) pq.NullTime { r := pq.NullTime{} r.Time = t if !t.IsZero() { r.Valid = true } return r } func StringToNull(s string) sql.NullString { r := sql.NullString{} r.String = s if s != "" { r.Valid = true } return r } func Int64ToNull(i int64) sql.NullInt64 { r := sql.NullInt64{} r.Int64 = i if i > 0 { r.Valid = true } return r } func Float64ToNull(f float64) sql.NullFloat64 { r := sql.NullFloat64{} r.Float64 = f if f > 0 { r.Valid = true } return r } func BollToNull(b *bool) sql.NullBool { r := sql.NullBool{} if b != nil { r.Bool = *b r.Valid = true } return r }<file_sep>/account-service/internal/domain/ports/account_repository.go package account_service import ( persistence "github.com/ernesto2108/helpnwn-service/account-service/internal/application/persistence" ) type AccountRepository interface { SignUp() SingIn() } type AccountService struct { persistence.PostgresAccountRepository } <file_sep>/account-service/internal/domain/ports/account_service.go package account_service func (s AccountService) SignUp() { } func (s AccountService) SingIn() { } <file_sep>/business-service/go.mod module "github.com/ernesto2108/helpnwn-service/business-service"<file_sep>/account-service/internal/domain/model/user.go package account_service type User struct { Uuid string `json:"uuid"` UserId string `json:"user_id"` Lastname string `json:"lastname"` Email string `json:"email"` Nickname string `json:"nickname"` Password string `json:"<PASSWORD>"` CreateAt string `json:"_"` UpdateAt string `json:"_"` DeleteAt string `json:"_"` } <file_sep>/account-service/internal/infrastructure/utils/loggers/logger.go package user_service import ( "go.uber.org/zap" ) var log *zap.Logger var sugar *zap.SugaredLogger func Logger(env string) { } func Log() *zap.Logger { _ = log.Sync() return log } func Sugar() *zap.SugaredLogger { _ = sugar.Sync() return sugar }<file_sep>/account-service/internal/domain/model/profile.go package account_service type Profile struct { Uuid string `json:"uuid"` ProfileId string `json:"profile_id"` Name string `json:"name"` State string `json:"state"` CreateAt string `json:"_"` UpdateAt string `json:"_"` DeleteAt string `json:"_"` } <file_sep>/account-service/internal/infrastructure/http/routes.go package account_service import "github.com/go-chi/chi" func Routes() *chi.Mux { mux := chi.NewMux() return mux }<file_sep>/account-service/go.mod module github.com/ernesto2108/helpnwn-service/account-service go 1.14 require ( github.com/go-chi/chi v4.1.2+incompatible github.com/lib/pq v1.8.0 go.uber.org/zap v1.16.0 ) <file_sep>/user-service/go.mod module "github.com/ernesto2108/helpnwn-service/user-service"<file_sep>/account-service/internal/application/persistence/postgres_account_service.go package account_service func (s PsqlService) signUp() { } func (s PsqlService) singIn() { } <file_sep>/account-service/internal/infrastructure/datasource/database_config.go package account_service import ( "database/sql" "errors" "fmt" "sync" _ "github.com/lib/pq" ) var once sync.Once var db *sql.DB var errNotInitialized = errors.New("the connection pool has not been initialized") const ( // dns database connection dnsPsql = "postgres://%s:%s@%s:%d/%s?sslmode=disable" // name database postgres = "postgres" ) type Model struct { Engine string Server string port int User string Password string Name string } func (m *Model) NewConn() (*sql.DB, error) { var err error var dns string if m.Engine == "" { return nil, errors.New("databases mandatory") } once.Do(func() { switch m.Engine { case postgres: dns = dnsPsql } db, err = m.initConn(dns) }) return db, err } func (m *Model) initConn(dns string) (*sql.DB, error) { var err error d := fmt.Sprintf(dns, m.User, m.Password, m.Server, m.port, m.Name) db, err := sql.Open(m.Engine, d) if err != nil { return db, err } return db, nil } func InitConn() (*sql.DB, error) { if db == nil { return db, errNotInitialized } if db.Ping() != nil { return db, errNotInitialized } return db, nil } // close connection func CloseConn() error { err := db.Close() if err != nil { return err } return nil } <file_sep>/account-service/internal/application/persistence/postgres_account_repository.go package account_service import "database/sql" type PostgresAccountRepository interface { signUp() singIn() } type PsqlService struct { *sql.DB } <file_sep>/account-service/internal/infrastructure/utils/random/random.go package account_service func RandomUUID() { }
b48c5b9c5a6e355b9d6f266a2ec2f4d0e45dc025
[ "Go Module", "Go" ]
15
Go
ernesto2108/helpnwn-service
498112362ad660f4482d41b26fbd24c6241a7b4e
e6ce2a181bc68627dc720c9a76c9aba0db949d4b
refs/heads/master
<file_sep>const entrepreneurs = [ { first: 'Steve', last: 'Jobs', year: 1955 }, { first: 'Oprah', last: 'Winfrey', year: 1954 }, { first: 'Bill', last: 'Gates', year: 1955 }, { first: 'Sheryl', last: 'Sandberg', year: 1969 }, { first: 'Mark', last: 'Zuckerberg', year: 1984 }, { first: 'Beyonce', last: 'Knowles', year: 1981 }, { first: 'Jeff', last: 'Bezos', year: 1964 }, { first: 'Diane', last: 'Hendricks', year: 1947 }, { first: 'Elon', last: 'Musk', year: 1971 }, { first: 'Marissa', last: 'Mayer', year: 1975 }, { first: 'Walt', last: 'Disney', year: 1901 }, { first: 'Larry', last: 'Page', year: 1973 }, { first: 'Jack', last: 'Dorsey', year: 1976 }, { first: 'Evan', last: 'Spiegel', year: 1990 }, { first: 'Brian', last: 'Chesky', year: 1981 }, { first: 'Travis', last: 'Kalanick', year: 1976 }, { first: 'Marc', last: 'Andreessen', year: 1971 }, { first: 'Peter', last: 'Thiel', year: 1967 } ]; console.log("Filtre dans cette liste les entrepreneurs qui sont nés dans les années 70 :") entrepreneurs.forEach( year => { if (year.year >= 1970 && year.year < 1980) console.log(year.first + " " + year.last); }); console.log("Sors une array qui contient le prénom et le nom des entrepreneurs :") entrepreneurs.forEach(e => { array1 = [e.first + " " + e.last] console.log(array1); }); console.log("Quel âge aurait chaque inventeur aujourd'hui ?") entrepreneurs.forEach (a => { let age =(2019 - a.year) console.log(age); }); console.log("Trie les entrepreneurs par ordre alphabétique du nom de famille : ") function order (){ let alphabetic = entrepreneurs alphabetic.sort(function(a, b){ return a.last.localeCompare(b.last); }) console.log(alphabetic); } order(); // const result = entrepreneurs.filter(year => (1970 < year && year > 1980)); // console.log(result)<file_sep>let nombre = prompt("De quel nombre veut tu calculer la factorielle ?") function factorielle(n){ m = 1 for (i = 1; i <= n; i++){ m = m * i; }; return m; }; console.log(factorielle(nombre));<file_sep>let etages = prompt("Combien d'etages veux tu a ta pryramides?") function createHalfPyramid (etages) { for ( i = 1; i <= etages; i++) { var row = ''; for (e = 1; e <= (etages - i); e++){ row += ' '; } for ( j = 1; j <= i; j++) { row += '*'; } console.log(row); } } createHalfPyramid(etages);
adc5a3837adea2add47a503336760a65ed795396
[ "JavaScript" ]
3
JavaScript
Hgo0123/exo_js
0c84c13d57f4d8ac4547c81e347b3b146f45392b
73c5d56610d7cea8a38cc2921ef6d523e8968fc7
refs/heads/master
<file_sep># Tests module for the diffusion_model.py module from nose.tools import assert_almost_equal, assert_raises from diffusion_model import energy def test_error_on_negative_density(): with assert_raises(ValueError) as exception: energy([1,-2,3]) def test_error_on_non_integer_density(): with assert_raises(TypeError) as exception: energy([1,2.0,3]) def test_error_on_non_1D_array(): densities = [ [1, [2, 3] ], [ [1, 2], [4, 5] ], [1, 2, 3, [4, 5] ] ] for density in densities: with assert_raises(ValueError) as exception: energy(density) def test_zero_energy_on_empty_array(): densities = [ [], [0], [0, 0, 0] ] for density in densities: assert_almost_equal(energy(density),0) def test_known_simple_case(): assert_almost_equal(energy([0,1,4,3,0,2,1],2),20) <file_sep># Calculates the diffusion energy def energy(density, Dcoeff=1): # INPUT PARAMETERS # # density : list of positive integers : number of particles at each site. # Dcoeff : float : scales overall energy result. from numpy import array, any, sum # Check density is an array. density = array(density) # Check array data type is integer if density.dtype.kind != 'i' and len(density) > 0 : raise TypeError("Density must be an array of *integers*.") # Check array is one dimensional. if density.ndim != 1: raise ValueError("Density must be a *one dimensional* array.") # Check all integers are non-negative if any(density < 0) : raise ValueError("Density must be an array of *non-negative* integers.") return Dcoeff * 0.5 * sum(density * (density - 1) )<file_sep>class MonteCarlo(object): "Simple monte carlo class" def __init__( self, temperature=1, itermax=100) : if temperature <= 0.0 : raise ValueError("Temperature must be *positive*.") if not isinstance( itermax, int) : raise TypeError("itermax must be an *integer*.") self.temperature = temperature """ Simulation Temperature """ self.itermax = itermax """ Maximum iterations to run """ def move_particle_randomly( self, density) : """ Randomly move one particle left or right """ from numpy import random, array density = array(density) # Choose random position (weighted by occupation number) particle_positions = [] for i in range(len(density)) : particle_positions += [i] * density[i] pos1 = random.choice(particle_positions) # Randomly choose valid position for particle to move to while True : pos2 = pos1 + random.choice([-1,1]) if 0 <= pos2 < len(density) : break newdensity = array(density) newdensity[pos1] -= 1 newdensity[pos2] += 1 return newdensity def accept_move( self, energy, density0, density1) : """ Accept or reject particle move based on energy function""" from numpy import random, exp E0 = energy(density0) E1 = energy(density1) if E1 < E0 : return True elif exp(-( E1 - E0) / self.temperature ) > random.random() : return True else : return False def __call__( self, initial_density, energy): """ Iterate MonteCarlo object up to itermax """ from numpy import any, array density = array(initial_density) if any(density) < 0 : raise ValueError("Densites must be *non-negative*.") if density.dtype.kind != 'i' : raise TypeError("Densities must be *integers*.") if density.ndim != 1 : raise TypeError("Density must be *1D* array.") if sum(density) == 0 : raise ValueError("Density can't be empty.") if len(density) < 2 : raise ValueError("Density must be more than one site") for i in range(self.itermax) : new_density = self.move_particle_randomly(density) if self.accept_move( energy, density, new_density) : density = new_density return density<file_sep># Tests the monte_carlo_step module from nose.tools import assert_raises, assert_almost_equal, assert_true from monte_carlo_step import MonteCarlo def test_MonteCarlo_initialises_correctly(): # Test negative, 0 temp, and float itermax cases = [[ -1, 100, ValueError], [ 0.0, 100, ValueError], [ 1, 1.5, TypeError]] for case in cases: with assert_raises(case[2]) as exception: mc=MonteCarlo(*case[0:2]) def test_move_particle_randomly() : from numpy import sum density1 = [ 1, 2, 3, 4] mc = MonteCarlo() # Test particle number preserved 100 times over. for i in range(100) : density2 = mc.move_particle_randomly(density1) assert_almost_equal( sum(density1), sum(density2)) def test_accept_move() : from diffusion_model import energy density1 = [ 25, 14, 46, 23] density2 = [ 2, 3, 4, 1] # Use very low temperature to check density based moves mc = MonteCarlo(1e-12) assert mc.accept_move( energy, density1, density2) == True assert mc.accept_move( energy, density2, density1) == False # Then use very high temperature to check random moves mc.temperature = 1e12 n=0 for i in range(100) : if mc.accept_move( energy, density2, density1) == True : n += 1 assert n > 95 def test_MonteCarlo_call_method() : from diffusion_model import energy cases = [[ [ -1, 2, 3], ValueError], [ [ 1.0, 2, 3], TypeError], [ [ [ 1, 2, 3], [ 4, 5, 6]], TypeError], [ [ 0, 0, 0], ValueError], [ [1], ValueError]] mc = MonteCarlo() for case in cases : with assert_raises(case[1]) as exception : mc( case[0], energy) def test_MonteCarlo_known_cases() : from diffusion_model import energy from numpy import array_equal, array # Set v low temperature to allow expected equilibration mc = MonteCarlo(1e-12,100) n = 0 for i in range(100) : density = array([ 15, 0, 0]) density = mc( density, energy) print density if array_equal(density, array([ 5, 5, 5])) : n += 1 assert n > 95
ad94d25892280e41d811863e8d6961a98c69797a
[ "Python" ]
4
Python
jcmgray/Monte-Carlo-Test-Exercise
7aae0dc9610d24085a1fa56021537e84b3cb2204
907373fd4c72c3dc506b9473534540bbd68b10b3
refs/heads/master
<repo_name>Fxy4ever/ExamWeek<file_sep>/module_day/src/main/java/com/fxy/daymatters/ui/widget/AffairWidgetService.kt package com.fxy.daymatters.ui.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.net.Uri import android.support.annotation.IdRes import android.util.Log import android.util.TypedValue import android.widget.RemoteViews import android.widget.RemoteViewsService import com.fxy.daymatters.R import com.fxy.daymatters.bean.Affair import com.fxy.daymatters.debug.TestActivity import com.fxy.daymatters.util.getDayFromNow import com.fxy.daymatters.util.getToday import com.google.gson.Gson import com.google.gson.reflect.TypeToken import org.jetbrains.anko.defaultSharedPreferences /** * create by:Fxymine4ever * time: 2019/3/30 */ class AffairWidgetService : RemoteViewsService() { override fun onGetViewFactory(intent: Intent?): RemoteViewsFactory? { if (intent != null) { return AffairWidgetFactory(this, intent, intent.getStringExtra("classify")) } return null } inner class AffairWidgetFactory(val context: Context, private val intent: Intent, val classify: String) : RemoteViewsService.RemoteViewsFactory { private lateinit var data: MutableList<Affair> private var appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) override fun onCreate() { initData() } private fun initData() { val type = object : TypeToken<MutableList<Affair>>() {}.type data = Gson().fromJson( context.defaultSharedPreferences.getString(AffairSmallWidget.sharedName, "") , type ) } override fun getViewAt(position: Int): RemoteViews { var rv: RemoteViews = RemoteViews(context.packageName, R.layout.day_widget_item_blue) if (data != null && data.size > 0) { val endTime = data[position].endTime ?: "" if (!endTime.isNotEmpty()) {//endDay为空,说明不是计算间隔 val betweenDay = getDayFromNow(getToday(), data[position].startTime!!) if (betweenDay > 0) {//如果时间还没到 rv = RemoteViews(context.packageName, R.layout.day_widget_item_blue) rv.setTextViewText(R.id.day_item_hor_title, "${data[position].title}还有") rv.setTextViewText(R.id.day_item_hor_num, "${Math.abs(betweenDay)}") rv.setTextViewTextSize(R.id.day_item_hor_title, TypedValue.COMPLEX_UNIT_SP,14.0f) setFillIntent(position, R.id.day_item_hor_layout, rv) } else { //如果时间已经过了 rv = RemoteViews(context.packageName, R.layout.day_widget_item_red) rv.setTextViewText(R.id.day_item_red_hor_title, "${data[position].title}已经") rv.setTextViewText(R.id.day_item_red_hor_num, "${Math.abs(betweenDay)}") rv.setTextViewTextSize(R.id.day_item_red_hor_title, TypedValue.COMPLEX_UNIT_SP,14.0f) setFillIntent(position, R.id.day_item_red_hor_layout, rv) } } else { val betweenDay = getDayFromNow(endTime, data[position].startTime!!) rv = RemoteViews(context.packageName, R.layout.day_widget_item_red) rv.setTextViewText(R.id.day_item_red_hor_title, "${data[position].title}共") rv.setTextViewText(R.id.day_item_red_hor_num, "${Math.abs(betweenDay)}") rv.setTextViewTextSize(R.id.day_item_red_hor_title, TypedValue.COMPLEX_UNIT_SP,14.0f) setFillIntent(position, R.id.day_item_red_hor_layout, rv) } } return rv } private fun setFillIntent(position: Int, id: Int, rv: RemoteViews) { val fillIntent = Intent() fillIntent.putExtra(AffairSmallWidget.COLLECTION_VIEW_EXTRA, position) rv.setOnClickFillInIntent(id, fillIntent) } override fun getLoadingView(): RemoteViews? = null override fun getItemId(position: Int): Long = position.toLong() override fun onDataSetChanged() { val type = object : TypeToken<MutableList<Affair>>() {}.type data = Gson().fromJson( context.defaultSharedPreferences.getString(AffairSmallWidget.sharedName, "") , type ) if(AffairSmallWidget.curClassify != "全部"){ data = data.filter { it.classify == AffairSmallWidget.curClassify }.toMutableList() } } override fun hasStableIds(): Boolean = true override fun getCount(): Int = data.size override fun getViewTypeCount(): Int = 2 override fun onDestroy() { data.clear() } } }<file_sep>/module_day/build.gradle apply from: module_config dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') testImplementation 'junit:junit:4.12' // implementation "android.arch.persistence.room:compiler:1.1.1" // implementation "android.arch.persistence.room:rxjava2:1.1.1" kapt deps.room.compiler kapt deps.arouter.compiler implementation 'com.github.clans:fab:1.6.4' implementation project(':lib_common') } repositories { mavenCentral() } <file_sep>/settings.gradle include ':app', ':lib_common', ':module_main', ':module_main', ':module_day', ':module_todo' <file_sep>/module_main/build.gradle apply from: module_config dependencies { implementation project(':lib_common') // implementation 'com.android.support:support-vector-drawable:27.1.1' kapt deps.arouter.compiler } //android { // defaultConfig { // vectorDrawables.useSupportLibrary = true // } //} repositories { mavenCentral() } <file_sep>/module_todo/build/generated/source/dataBinding/trigger/debug/android/databinding/layouts/DataBindingInfo.java package android.databinding.layouts; import android.databinding.BindingBuildInfo; @BindingBuildInfo(buildId="0c214d0f-6fd2-4749-85fc-ee0f38187440") public class DataBindingInfo {} <file_sep>/module_todo/src/main/java/com/fxy/moduletodo/ui/MainFragment.kt package com.fxy.moduletodo.ui import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import com.alibaba.android.arouter.facade.annotation.Route import com.fxy.lib.config.TODO_MAIN import com.fxy.lib.ui.BaseFragment import com.fxy.lib.utils.extensions.observe import com.fxy.moduletodo.R import com.fxy.moduletodo.bean.TodoList import com.fxy.moduletodo.ui.adapter.TodoListAdapter import com.fxy.moduletodo.util.Injection import com.fxy.moduletodo.viewmodel.TodoListViewModel import kotlinx.android.synthetic.main.todo_fragment_main.* import kotlinx.android.synthetic.main.todo_fragment_main.view.* /** * create by:Fxymine4ever * time: 2019/4/9 */ @Route(path = TODO_MAIN) class MainFragment : BaseFragment() { override val isFragmentContainer: Boolean = false private lateinit var parent:View private lateinit var model:TodoListViewModel private val list: MutableList<TodoList> = mutableListOf() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { parent = inflater.inflate(R.layout.todo_fragment_main,container,false) if (context == null) return null val factory = TodoListViewModel.Factory(Injection.provideAffariDataSrouce(context!!)) model = ViewModelProviders.of(this,factory).get(TodoListViewModel::class.java) initData() return parent } private fun initData(){ model.getTodoList() val mAdapter = TodoListAdapter(context!!,list) parent.todo_main_rv.adapter = mAdapter parent.todo_main_rv.layoutManager = LinearLayoutManager(context!!) model.todoList.observe(this) { list-> if(list != null && list.size > 0){ this.list.addAll(list) } } } }<file_sep>/lib_common/src/main/java/com/fxy/lib/utils/extensions/View.kt package com.fxy.lib.utils.extensions import android.view.View /** * create by:Fxymine4ever * time: 2019/1/31 */ fun View.gone() { visibility = View.GONE } fun View.visible() { visibility = View.VISIBLE } fun View.invisible() { visibility = View.INVISIBLE }<file_sep>/module_todo/src/main/java/com/fxy/moduletodo/util/converters/TodoConverter.kt package com.fxy.moduletodo.util.converters import android.arch.persistence.room.TypeConverter import com.fxy.moduletodo.bean.Step import com.fxy.moduletodo.bean.TodoList import com.google.gson.Gson import com.google.gson.reflect.TypeToken class TodoConverter { @TypeConverter fun stringToObject(value: String): List<Step> { val listType = object : TypeToken<List<Step>>() { }.type return Gson().fromJson(value, listType) } @TypeConverter fun objectToString(list: List<Step>): String { val gson = Gson() return gson.toJson(list) } }<file_sep>/module_day/src/main/java/com/fxy/daymatters/event/FinishDetailEvent.kt package com.fxy.daymatters.event /** * create by:Fxymine4ever * time: 2019/3/28 */ class FinishDetailEvent() { }<file_sep>/module_day/src/main/java/com/fxy/daymatters/bean/Affair.kt package com.fxy.daymatters.bean import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import java.io.Serializable /** * create by:Fxymine4ever * time: 2019/3/21 */ @Entity(tableName = "Affair") data class Affair constructor( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var dayMatterId:Long = 0, @ColumnInfo(name = "title") var title: String? = "", @ColumnInfo(name = "startTime") var startTime: String? = null, @ColumnInfo(name = "classify") var classify: String? = null, @ColumnInfo(name = "isNotify") var isNotify: Boolean = false, @ColumnInfo(name = "isChineseDay") var isChineseDay: Boolean = false, @ColumnInfo(name = "endTime") var endTime: String? = null,//结束日期可以为空 @ColumnInfo(name = "background") var background: String? = null, @ColumnInfo(name = "textColor") var textColor: String = "#FFFFFF" ):Serializable<file_sep>/module_todo/build/tmp/kapt3/stubs/debug/com/fxy/moduletodo/util/Injection.java package com.fxy.moduletodo.util; import java.lang.System; /** * create by:Fxymine4ever * time: 2019/3/30 */ @kotlin.Metadata(mv = {1, 1, 15}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000\u001e\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\b\u00c6\u0002\u0018\u00002\u00020\u0001B\u0007\b\u0002\u00a2\u0006\u0002\u0010\u0002J\u000e\u0010\u0003\u001a\u00020\u00042\u0006\u0010\u0005\u001a\u00020\u0006J\u000e\u0010\u0007\u001a\u00020\b2\u0006\u0010\u0005\u001a\u00020\u0006\u00a8\u0006\t"}, d2 = {"Lcom/fxy/moduletodo/util/Injection;", "", "()V", "provideAffariDataSrouce", "Lcom/fxy/moduletodo/dao/TodoListDao;", "context", "Landroid/content/Context;", "provideViewModelFactory", "Landroid/arch/lifecycle/ViewModelProvider$Factory;", "module_todo_debug"}) public final class Injection { public static final com.fxy.moduletodo.util.Injection INSTANCE = null; @org.jetbrains.annotations.NotNull() public final com.fxy.moduletodo.dao.TodoListDao provideAffariDataSrouce(@org.jetbrains.annotations.NotNull() android.content.Context context) { return null; } @org.jetbrains.annotations.NotNull() public final android.arch.lifecycle.ViewModelProvider.Factory provideViewModelFactory(@org.jetbrains.annotations.NotNull() android.content.Context context) { return null; } private Injection() { super(); } }<file_sep>/README.md # ExamWeek 考试周 - Jetpack √ - 组件化 √ - 桌面小部件 √ - ui √ <br> (未完待续... <file_sep>/module_day/src/main/java/com/fxy/daymatters/debug/TestActivity.kt package com.fxy.daymatters.debug import android.os.Bundle import com.fxy.daymatters.ui.DayMatterFragment import com.fxy.daymatters.R import com.fxy.lib.ui.BaseActivity class TestActivity(override val isFragmentActivity: Boolean = true) : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.day_activity_test) common_toolbar.init("倒数日",listener = null) initFragment() } private fun initFragment(){ val transaction = supportFragmentManager.beginTransaction() val fragment = DayMatterFragment() transaction.replace(R.id.daymatters_fragment_container,fragment).commit() } } <file_sep>/module_todo/src/main/java/com/fxy/moduletodo/util/Injection.kt package com.fxy.moduletodo.util import android.arch.lifecycle.ViewModelProvider import android.content.Context import com.fxy.moduletodo.dao.TodoListDao import com.fxy.moduletodo.db.TodoListDatabase import com.fxy.moduletodo.viewmodel.TodoListViewModel /** * create by:Fxymine4ever * time: 2019/3/30 */ object Injection{ fun provideAffariDataSrouce(context: Context):TodoListDao{ return TodoListDatabase.getInstance(context).todoListDao() } fun provideViewModelFactory(context: Context):ViewModelProvider.Factory{ return TodoListViewModel.Factory(provideAffariDataSrouce(context)) } }<file_sep>/module_day/src/main/java/com/fxy/daymatters/viewmodel/CommitAffairViewModel.kt package com.fxy.daymatters.viewmodel import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.util.Log import com.fxy.daymatters.bean.Affair import com.fxy.daymatters.dao.DayMatterDao import com.fxy.daymatters.ui.widget.AffairSmallWidget.Companion.classify import io.reactivex.* import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers /** * create by:Fxymine4ever * time: 2019/3/26 */ class CommitAffairViewModel(private val dataSource: DayMatterDao) : ViewModel() { val isInsertData:MutableLiveData<Long> by lazy(LazyThreadSafetyMode.NONE){ MutableLiveData<Long>().apply { value = -1 } } val isDeleteData:MutableLiveData<Int> by lazy(LazyThreadSafetyMode.NONE){ MutableLiveData<Int>().apply { value = -1 } } val isUpdateData:MutableLiveData<Int> by lazy(LazyThreadSafetyMode.NONE){ MutableLiveData<Int>().apply { value = -1 } } val mAffairs:MutableLiveData<MutableList<Affair>> by lazy(LazyThreadSafetyMode.NONE){ MutableLiveData<MutableList<Affair>>() } val mClassify:MutableLiveData<MutableList<String>> by lazy(LazyThreadSafetyMode.NONE){ MutableLiveData<MutableList<String>>() } fun insertAffair(affair: Affair){ dataSource.let {dao-> Observable.create<Long> { it.onNext(dao.insertDayMatters(affair)) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { isInsertData.value = it } } } fun deleteAffair(affair: Affair){ dataSource.let {dao-> Observable.create<Int> { it.onNext(dao.deleteDayMatters(affair)) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { isDeleteData.value = it } } } fun updateAffair(affair: Affair){ dataSource.let {dao-> Observable.create<Int> { it.onNext(dao.updateDayMatters(affair)) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { isUpdateData.value = it } } } fun getAffairs(){ dataSource.let { dao-> dao.getDayMatters() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { mAffairs.value = it } } } fun getAffairsByClassify(classify:String){ dataSource.let { dao-> dao.getDayMattersByKind(classify) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { mAffairs.value = it } } } fun getClassify(){ dataSource.let {dao-> dao.getClassify() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { if(it!=null&&it.size>0){ it.add(it[0]) it[0] = "全部" mClassify.value = it } } } } }<file_sep>/module_day/src/main/java/com/fxy/daymatters/ui/pop/ClassifyPop.kt package com.fxy.daymatters.ui.pop import android.content.Context import android.view.View import com.fxy.daymatters.R import kotlinx.android.synthetic.main.day_classify_pop.view.* import org.jetbrains.anko.toast import razerdp.basepopup.BasePopupWindow import android.view.animation.Animation import com.fxy.daymatters.util.setFocused /** * create by:Fxymine4ever * time: 2019/3/29 */ class ClassifyPop constructor(context: Context) : BasePopupWindow(context) { private lateinit var view:View private lateinit var onChooseTextListener : (String) -> Unit override fun onCreateContentView(): View { view = createPopupById(R.layout.day_classify_pop) view.day_pop_classify_delete.setOnClickListener { onChooseTextListener("生活") dismiss() } view.day_pop_classify_save.setOnClickListener { val str = view.day_pop_classify_et.text.toString() view.day_pop_classify_et.setFocused() if(str.isNotEmpty()){ onChooseTextListener(str) dismiss() }else{ context.toast("请输入完整的分类") } } return view } override fun onCreateShowAnimation(): Animation { return getDefaultScaleAnimation(true) } override fun onCreateDismissAnimation(): Animation { return getDefaultScaleAnimation(false) } fun setChooseTextListener(listener:(String)->Unit){ this.onChooseTextListener = listener } }<file_sep>/module_todo/src/main/java/com/fxy/moduletodo/debug/TestApplication.kt package com.fxy.moduletodo.debug import android.app.Application /** * create by:Fxymine4ever * time: 2019/7/17 */ class TestApplication : Application() { override fun onCreate() { super.onCreate() } }<file_sep>/module_main/src/main/java/com/fxy/main/MainActivity.kt package com.fxy.main import android.os.Bundle import android.support.design.widget.BottomNavigationView import android.support.v4.app.Fragment import android.support.v4.app.FragmentTransaction import com.alibaba.android.arouter.launcher.ARouter import com.fxy.lib.config.DAY_AFFAIR import com.fxy.lib.config.DAY_MAIN import com.fxy.lib.config.TODO_MAIN import com.fxy.lib.ui.BaseActivity import com.fxy.main.util.disableShiftMode import kotlinx.android.synthetic.main.main_activity_main.* class MainActivity(override val isFragmentActivity: Boolean = true) : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity_main) common_toolbar.init("倒数日",listener = null) initNav() val t = supportFragmentManager.beginTransaction() t.replace(R.id.main_container,getFragment(DAY_MAIN)) t.commit() } override fun onResume() { super.onResume() } private fun getFragment(path :String): Fragment{ return ARouter.getInstance().build(path).navigation() as Fragment } private fun initNav(){ val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.nav_day_matters -> { common_toolbar.init("倒数日",listener = null) val t = supportFragmentManager.beginTransaction() t.replace(R.id.main_container,getFragment(DAY_MAIN)) t.commit() return@OnNavigationItemSelectedListener true } R.id.nav_tomato_alert -> { common_toolbar.init("番茄闹钟",listener = null) return@OnNavigationItemSelectedListener true } R.id.nav_mine_todo -> { common_toolbar.init("我的待办",listener = null) val t = supportFragmentManager.beginTransaction() t.replace(R.id.main_container,getFragment(TODO_MAIN)) t.commit() return@OnNavigationItemSelectedListener true } R.id.nav_setting -> { common_toolbar.init("设置",listener = null) return@OnNavigationItemSelectedListener true } } false } main_navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) disableShiftMode(main_navigation) } } <file_sep>/lib_common/src/main/java/com/fxy/lib/utils/extensions/String.kt package com.fxy.lib.utils.extensions import android.provider.SyncStateContract.Helpers.update import okio.ByteString import java.io.UnsupportedEncodingException import java.math.BigInteger import java.security.MessageDigest import java.security.NoSuchAlgorithmException /** * create by:Fxymine4ever * time: 2019/1/31 */ fun String.toMD5():String{ try { val messageDigest = MessageDigest.getInstance("MD5") val md5bytes = messageDigest.digest(this.toByteArray(charset("UTF-8"))) return ByteString.of(*md5bytes).hex() } catch (e: NoSuchAlgorithmException) { throw AssertionError(e) } catch (e: UnsupportedEncodingException) { throw AssertionError(e) } }<file_sep>/lib_common/src/main/java/com/fxy/lib/config/Config.kt package com.fxy.lib.config /** * create by:Fxymine4ever * time: 2019/1/31 */ const val SP_DEFAULT_NAME = "share_default" //TODO:以后有api再换 const val BASE_URL = "fake"<file_sep>/lib_common/src/main/java/com/fxy/lib/utils/LogUtil.kt package com.fxy.lib.utils import android.util.Log import com.exam.lib_common.BuildConfig /** * create by:Fxymine4ever * time: 2019/1/31 */ /**控制想要打印的日志级别 * 等于VERBOSE,则就会打印所有级别的日志 * 等于WARN,则只会打印警告级别以上的日志 * 等于NOTHING,则会屏蔽掉所有日志 */ object LogUtil { private val isDebug = BuildConfig.DEBUG fun v(msg: String, tag: String = "tag") { if (isDebug) Log.v(tag, msg) } fun d(msg: String, tag: String = "tag") { if (isDebug) Log.d(tag, msg) } fun i(msg: String, tag: String = "tag") { if (isDebug) Log.i(tag, msg) } fun w(msg: String, tag: String = "tag") { if (isDebug) Log.w(tag, msg) } fun e(msg: String, tag: String = "tag") { if (isDebug) Log.e(tag, msg) } }<file_sep>/lib_common/src/main/java/com/fxy/lib/utils/extensions/Rxjava.kt package com.fxy.lib.utils.extensions import com.fxy.lib.network.NetworkRetry import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers /** * create by:Fxymine4ever * time: 2019/1/31 */ fun <T> Observable<T>.setSchedulers( subscribeOn: Scheduler = Schedulers.io(), unsubscribeOn: Scheduler = Schedulers.io(), observeOn: Scheduler = AndroidSchedulers.mainThread() ): Observable<T> = subscribeOn(subscribeOn) .unsubscribeOn(unsubscribeOn) .observeOn(observeOn) fun <T> Observable<T>.safeSubscribeBy( onNext: (T) -> Unit, onError: (Throwable) -> Unit, onComplete: () -> Unit ) = subscribe(onNext, onError, onComplete) fun <T> Observable<T>.networkRetry( maxRetryTimes:Int = 3, retryDelayMillis: Int=1000):Observable<T> = this.retryWhen(NetworkRetry(maxRetryTimes,retryDelayMillis))<file_sep>/module_day/src/main/java/com/fxy/daymatters/ui/CommitAffairActivity.kt package com.fxy.daymatters.ui import android.app.DatePickerDialog import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.util.Log import android.view.Gravity import com.alibaba.android.arouter.facade.annotation.Route import com.fxy.daymatters.bean.Affair import com.fxy.daymatters.event.FinishDetailEvent import com.fxy.daymatters.ui.DayMatterFragment.Companion.cal import com.fxy.daymatters.ui.pop.ClassifyPop import com.fxy.daymatters.util.* import com.fxy.daymatters.viewmodel.CommitAffairViewModel import com.fxy.lib.config.DAY_AFFAIR import com.fxy.lib.ui.BaseActivity import com.fxy.lib.utils.extensions.* import com.google.gson.Gson import kotlinx.android.synthetic.main.day_activity_commit_matter.* import org.greenrobot.eventbus.EventBus import org.jetbrains.anko.toast import java.util.* @Route(path = DAY_AFFAIR) class CommitAffairActivity : BaseActivity() { /* 要设置的参数 */ private var title:String = "" private var isChineseDay:Boolean = false private var startDay:String = "${cal.get(Calendar.YEAR)}-${(cal.get(Calendar.MONTH))+1}-${cal.get(Calendar.DATE)} ${getChineseDayOfWeek("${cal.get(Calendar.YEAR)}-${(cal.get(Calendar.MONTH))+1}-${cal.get(Calendar.DATE)} ")}" private var startChineseDay:String = "" private var classify:String = "生活"//默认为生活 private var isNotify:Boolean = false private var endDay = startDay private var endChineseDay:String = "" private var isEndDay:Boolean = false private var id:Long = -1 private var isChangeActivity:Boolean = false//是否为修改页面,这关系到是否显示DeleteBtn private lateinit var model: CommitAffairViewModel override val isFragmentActivity: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(com.fxy.daymatters.R.layout.day_activity_commit_matter) val affairFromDetail = Gson().fromJson(intent.getStringExtra("affair"),Affair::class.java) jugdePage(affairFromDetail) initSelect() initLiveData() initView() } private fun jugdePage(affair: Affair?){ if(affair == null){//新增页面 common_toolbar.init("新增事件") }else{//修改页面 common_toolbar.init("修改事件") affair.let {//获取传过来的内容 id = it.dayMatterId title = it.title!! day_commit_et_name.setText(title) day_commit_et_name.setSingle() isChineseDay = it.isChineseDay if(isChineseDay){ day_commit_sw_isChineseDay.isChecked = true } startDay = it.startTime!! day_commit_tv_startDay.text = startDay //TODO:农历 classify = it.classify!! day_commit_tv_classify.text = classify isNotify = it.isNotify if(isNotify){ day_commit_sw_notify.isChecked = true } it.endTime?.let {endTime-> endDay = endTime isEndDay = true day_commit_sw_isEnd.isChecked = true day_commit_choose_endDay.visible() } isChangeActivity = true it.background?.let {background-> //TODO: 背景图片 } isChangeActivity = true } } } private fun initLiveData(){ val factory = Injection.provideViewModelFactory(this) model = ViewModelProviders.of(this,factory).get(CommitAffairViewModel::class.java) model.isInsertData.observeNotNull (this){ if(it!! > 0){ toast("插入成功") finish() } } model.isDeleteData.observeNotNull (this){ if(it!! > 0){ toast("删除成功") EventBus.getDefault().post(FinishDetailEvent()) finish() } } model.isUpdateData.observeNotNull (this){ if(it!! > 0){ toast("修改成功") EventBus.getDefault().post(FinishDetailEvent()) finish() } } } /** * 选择结束日期 */ private fun initSelect(){ //开始日期选择 val dateStartPicker = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth -> startDay = "$year-${month+1}-$dayOfMonth ${getChineseDayOfWeek("$year-${month+1}-$dayOfMonth")}" if(isChineseDay){ val startDates = getDateFromString(startDay) startChineseDay = ChinaDate.oneDay(startDates[0],startDates[1],startDates[2]) day_commit_tv_startDay.text = startChineseDay }else{ day_commit_tv_startDay.text = startDay } }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)) day_commit_choose_startDay.setOnClickListener { dateStartPicker.show() } //结束日期选择 val dateEndPicker = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth -> endDay = "$year-${month+1}-$dayOfMonth ${getChineseDayOfWeek("$year-${month+1}-$dayOfMonth")}" if(isChineseDay){ val endDates = getDateFromString(endDay) endChineseDay = ChinaDate.oneDay(endDates[0],endDates[1],endDates[2]) day_commit_tv_endDay.text = endChineseDay }else{ day_commit_tv_endDay.text = endDay } }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)) day_commit_choose_endDay.setOnClickListener { dateEndPicker.show() } day_commit_sw_notify.setOnCheckedChangeListener { _, isChecked -> isNotify = isChecked//是否置顶 } day_commit_sw_isChineseDay.setOnCheckedChangeListener { _, isChecked -> isChineseDay = isChecked if(isChecked){//是否选择农历 //TODO:后期换上农历的日期选择 val startDates = getDateFromString(startDay) startChineseDay = ChinaDate.oneDay(startDates[0],startDates[1],startDates[2]) val endDates = getDateFromString(endDay) endChineseDay = ChinaDate.oneDay(endDates[0],endDates[1],endDates[2]) day_commit_tv_startDay.text = startChineseDay day_commit_tv_endDay.text = endChineseDay }else{ day_commit_tv_startDay.text = startDay day_commit_tv_endDay.text = endDay } } day_commit_sw_isEnd.setOnCheckedChangeListener { _, isChecked -> isEndDay = isChecked if(isChecked) day_commit_choose_endDay.visible() else{ day_commit_choose_endDay.gone() endDay = "" } } } private fun initView(){ day_commit_tv_startDay.text = startDay day_commit_tv_endDay.text = endDay day_commit_tv_classify.text = classify day_commit_btn_save.setOnClickListener { title = day_commit_et_name.text.toString() if(title.isNotEmpty()){ val bean = Affair() bean.startTime = startDay bean.classify = classify bean.title = title bean.isNotify = isNotify bean.isChineseDay = isChineseDay if(isEndDay){ bean.endTime = endDay } if(isChangeActivity){//修改页面 bean.dayMatterId = id//如果是更新,得设置一个id model.updateAffair(bean) }else{//添加页面 model.insertAffair(bean) } }else{ toast("请填写事件名称") } } if(isChangeActivity){ day_commit_btn_delete.visible() day_commit_btn_delete.setOnClickListener { val bean = Affair() bean.dayMatterId = id model.deleteAffair(bean) } } val classifyPop = ClassifyPop(this) classifyPop.popupGravity = Gravity.CENTER classifyPop.setChooseTextListener{ classify = it day_commit_tv_classify.text = it } day_commit_tv_classify.setOnClickListener { classifyPop.showPopupWindow() } } } <file_sep>/module_day/src/main/java/com/fxy/daymatters/viewmodel/AffairViewModelFactory.kt package com.fxy.daymatters.viewmodel import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import com.fxy.daymatters.dao.DayMatterDao import java.lang.IllegalArgumentException /** * create by:Fxymine4ever * time: 2019/3/30 */ class AffairViewModelFactory(private val dataSource: DayMatterDao) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { if(modelClass.isAssignableFrom(CommitAffairViewModel::class.java)) return CommitAffairViewModel(dataSource) as T throw IllegalArgumentException("未知的ViewModel class") } }<file_sep>/module_day/build/tmp/kapt3/stubs/debug/com/fxy/daymatters/viewmodel/AffairViewModelFactory.java package com.fxy.daymatters.viewmodel; import java.lang.System; /** * create by:Fxymine4ever * time: 2019/3/30 */ @kotlin.Metadata(mv = {1, 1, 15}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000 \n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\u0018\u00002\u00020\u0001B\r\u0012\u0006\u0010\u0002\u001a\u00020\u0003\u00a2\u0006\u0002\u0010\u0004J\'\u0010\u0005\u001a\u0002H\u0006\"\n\b\u0000\u0010\u0006*\u0004\u0018\u00010\u00072\f\u0010\b\u001a\b\u0012\u0004\u0012\u0002H\u00060\tH\u0016\u00a2\u0006\u0002\u0010\nR\u000e\u0010\u0002\u001a\u00020\u0003X\u0082\u0004\u00a2\u0006\u0002\n\u0000\u00a8\u0006\u000b"}, d2 = {"Lcom/fxy/daymatters/viewmodel/AffairViewModelFactory;", "Landroid/arch/lifecycle/ViewModelProvider$Factory;", "dataSource", "Lcom/fxy/daymatters/dao/DayMatterDao;", "(Lcom/fxy/daymatters/dao/DayMatterDao;)V", "create", "T", "Landroid/arch/lifecycle/ViewModel;", "modelClass", "Ljava/lang/Class;", "(Ljava/lang/Class;)Landroid/arch/lifecycle/ViewModel;", "module_day_debug"}) public final class AffairViewModelFactory implements android.arch.lifecycle.ViewModelProvider.Factory { private final com.fxy.daymatters.dao.DayMatterDao dataSource = null; @java.lang.Override() public <T extends android.arch.lifecycle.ViewModel>T create(@org.jetbrains.annotations.NotNull() java.lang.Class<T> modelClass) { return null; } public AffairViewModelFactory(@org.jetbrains.annotations.NotNull() com.fxy.daymatters.dao.DayMatterDao dataSource) { super(); } }<file_sep>/module_day/src/main/java/com/fxy/daymatters/ui/adapter/MyFragPagerAdapter.kt package com.fxy.daymatters.ui.adapter import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.PagerAdapter import com.fxy.daymatters.bean.Affair import com.fxy.daymatters.ui.AffairDetailFragment /** * create by:Fxymine4ever * time: 2019/3/27 */ class MyFragPagerAdapter(private val list: MutableList<Affair>,fm: FragmentManager) : FragmentPagerAdapter(fm) { override fun getItem(position: Int): Fragment{ val fragment = AffairDetailFragment() fragment.affair = list[position] return fragment } override fun getCount(): Int = list.size }<file_sep>/module_todo/src/main/java/com/fxy/moduletodo/db/TodoListDatabase.kt package com.fxy.moduletodo.db import android.arch.persistence.room.Database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.content.Context import com.fxy.moduletodo.bean.TodoList import com.fxy.moduletodo.dao.TodoListDao /** * create by:Fxymine4ever * time: 2019/7/17 */ @Database(entities = [TodoList::class],version = 1,exportSchema = false) abstract class TodoListDatabase: RoomDatabase() { abstract fun todoListDao():TodoListDao companion object { @Volatile private var INSTANCE:TodoListDatabase? = null fun getInstance(context: Context):TodoListDatabase = INSTANCE ?: synchronized(this){ INSTANCE ?: buildDB(context) } private fun buildDB(context: Context) = Room.databaseBuilder(context,TodoListDatabase::class.java, "TodoList.db").build() } }<file_sep>/module_day/src/main/java/com/fxy/daymatters/workmanager/NotifyWork.kt package com.fxy.daymatters.workmanager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.util.Log import android.util.TypedValue import android.widget.RemoteViews import androidx.work.Worker import androidx.work.WorkerParameters import com.fxy.daymatters.R import com.fxy.daymatters.bean.Affair import com.fxy.daymatters.debug.TestActivity import com.fxy.daymatters.ui.widget.AffairSmallWidget import com.fxy.daymatters.util.getDayFromNow import com.fxy.daymatters.util.getToday import com.fxy.lib.utils.NotificationUtils import com.fxy.lib.utils.extensions.editor import com.google.gson.Gson import com.google.gson.reflect.TypeToken import org.jetbrains.anko.defaultSharedPreferences import java.util.* import kotlin.math.abs /** * create by:Fxymine4ever * time: 2019/3/31 */ class NotifyWork(val context: Context,workerParams:WorkerParameters) : Worker(context,workerParams) { private val PUSHTAG = "NotifyWork" private lateinit var data: MutableList<Affair> override fun doWork(): Result { val isPush = applicationContext.defaultSharedPreferences.getBoolean(PUSHTAG,false) applicationContext.defaultSharedPreferences.editor { putBoolean(PUSHTAG,false) } if(compareTime(7)){//如果在当前时间 if(isPush){//已经推送则不推送了 return Result.RETRY }else{ applicationContext.defaultSharedPreferences.editor { putBoolean(PUSHTAG,true) } } }else{//不在当前时间Flag重置 applicationContext.defaultSharedPreferences.editor { putBoolean(PUSHTAG,false) } return Result.RETRY } //TODO:合代码的时候换成主界面 val type = object : TypeToken<MutableList<Affair>>() {}.type data = Gson().fromJson( context.defaultSharedPreferences.getString(AffairSmallWidget.sharedName, "") , type) data = data.filter { it.isNotify }.toMutableList() data.forEach { val endTime = it.endTime ?: "" val title = "倒数提醒" val content:String if (endTime.isEmpty()) {//endDay为空,说明不是计算间隔 val betweenDay = getDayFromNow(getToday(), it.startTime!!) if (betweenDay > 0) {//如果时间还没到 content = "距离${it.title}还有${abs(betweenDay)}天了" } else { //如果时间已经过了 content = "距离${it.title}已经${abs(betweenDay)}天了" } } else { val betweenDay = getDayFromNow(endTime, it.startTime!!) content = "距离${it.title}共${abs(betweenDay)}天了" } val intent = Intent(applicationContext,TestActivity::class.java) val pi = PendingIntent.getActivity(applicationContext,0,intent,PendingIntent.FLAG_UPDATE_CURRENT) NotificationUtils(applicationContext).sendNotification( title, content, pi ) } return Result.SUCCESS } private fun compareTime(targetHour:Int):Boolean{ val curHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) return targetHour == curHour } }<file_sep>/lib_common/src/main/java/com/fxy/lib/ui/BaseActivity.kt package com.fxy.lib.ui import android.app.Activity import android.graphics.Color import android.os.Build import android.os.Bundle import android.os.PersistableBundle import android.support.annotation.DrawableRes import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.View import android.view.WindowManager import com.fxy.lib.event.EmptyEvent import com.exam.lib_common.R import com.umeng.analytics.MobclickAgent import kotlinx.android.synthetic.main.common_toolbar.* import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import org.jetbrains.anko.startActivity /** * create by:Fxymine4ever * time: 2019/1/31 */ abstract class BaseActivity : AppCompatActivity() { protected abstract val isFragmentActivity:Boolean//辅助umeng统计fragment override fun onStart() { super.onStart() EventBus.getDefault().register(this) } override fun onResume() { super.onResume() MobclickAgent.onResume(this) if(!isFragmentActivity) MobclickAgent.onPageStart(javaClass.name) } @Subscribe(threadMode = ThreadMode.MAIN) open fun onEmptyEvent(event: EmptyEvent){ //...以后有什么需要添加再改 } override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { super.onCreate(savedInstanceState, persistentState) //沉浸式 if (Build.VERSION.SDK_INT >= 21) { val decorView = window.decorView val option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE decorView.systemUiVisibility = option window.statusBarColor = Color.TRANSPARENT } else if (Build.VERSION.SDK_INT >= 19) { window.setFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS ) } } protected val BaseActivity.common_toolbar get() = toolbar fun Toolbar.init(title: String, @DrawableRes icon: Int = R.drawable.common_ic_back, listener: View.OnClickListener? = View.OnClickListener { finish() }) { this.title = title setSupportActionBar(this) if (listener == null) { navigationIcon = null } else { setNavigationIcon(icon) setNavigationOnClickListener(listener) } } override fun onPostCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { super.onPostCreate(savedInstanceState, persistentState) } //利用内联跳转Activity inline fun <reified T : Activity> startActivity(finish: Boolean = false, vararg params: Pair<String, Any?>) { if (finish) finish() startActivity<T>(*params) } override fun onPause() { super.onPause() MobclickAgent.onPause(this) if(!isFragmentActivity) MobclickAgent.onPageEnd(javaClass.name) } override fun onStop() { super.onStop() EventBus.getDefault().unregister(this) } override fun onDestroy() { super.onDestroy() } }<file_sep>/lib_common/src/main/java/com/fxy/lib/utils/extensions/Sp.kt package com.fxy.lib.utils.extensions import android.content.Context import android.content.SharedPreferences import com.fxy.lib.config.SP_DEFAULT_NAME /** * create by:Fxymine4ever * time: 2019/1/31 */ fun Context.getSp(name: String = SP_DEFAULT_NAME): SharedPreferences = getSharedPreferences(name, Context.MODE_PRIVATE) fun SharedPreferences.editor(editBuilder: SharedPreferences.Editor.() -> Unit) { edit().apply(editBuilder).apply() } <file_sep>/lib_common/src/main/java/com/fxy/lib/event/EmptyEvent.kt package com.fxy.lib.event /** * create by:Fxymine4ever * time: 2019/1/31 */ class EmptyEvent { }<file_sep>/module_day/src/main/java/com/fxy/daymatters/ui/AffairDetailActivity.kt package com.fxy.daymatters.ui import android.arch.lifecycle.ViewModelProviders import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v4.view.ViewPager import android.util.Log import android.view.MotionEvent import android.view.View import android.widget.SeekBar import com.fxy.daymatters.R import com.fxy.daymatters.bean.Affair import com.fxy.daymatters.event.FinishDetailEvent import com.fxy.daymatters.ui.adapter.MyFragPagerAdapter import com.fxy.daymatters.util.CardTransformer import com.fxy.daymatters.util.Injection import com.fxy.daymatters.viewmodel.CommitAffairViewModel import com.fxy.lib.ui.BaseActivity import com.fxy.lib.utils.extensions.observeNotNull import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.android.synthetic.main.day_activity_affair_detail.* import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode class AffairDetailActivity : BaseActivity() { private lateinit var affairs: MutableList<Affair> private var curPosition:Int = 0 private lateinit var mAdapter: MyFragPagerAdapter override val isFragmentActivity: Boolean = false private lateinit var model:CommitAffairViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.day_activity_affair_detail) common_toolbar.init("倒数日") initLiveData() initVp() } override fun onResume() { super.onResume() model.getAffairs() } private fun initLiveData(){ val factory = Injection.provideViewModelFactory(this) model = ViewModelProviders.of(this,factory).get(CommitAffairViewModel::class.java) model.getAffairs() model.mAffairs.observeNotNull(this) { it?.let {data-> affairs.clear() affairs.addAll(data) mAdapter.notifyDataSetChanged() day_detail_vp.currentItem = curPosition } } } private fun initVp(){ affairs = mutableListOf() curPosition = intent.getIntExtra("curPosition",0) mAdapter = MyFragPagerAdapter(affairs,supportFragmentManager) day_detail_vp.adapter = mAdapter day_detail_vp.offscreenPageLimit = 3 day_detail_vp.setPageTransformer(true,CardTransformer()) //解决clipChildren的滑动冲突 day_detail_container.setOnTouchListener(object: View.OnTouchListener{ override fun onTouch(v: View?, event: MotionEvent?): Boolean { day_detail_container.requestDisallowInterceptTouchEvent(true) return day_detail_vp.dispatchTouchEvent(event) } }) day_detail_vp.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{ override fun onPageScrollStateChanged(state: Int) {} override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { curPosition = position } }) day_detail_edit.setOnClickListener { val intent = Intent(this@AffairDetailActivity,CommitAffairActivity::class.java) intent.putExtra("affair",Gson().toJson(affairs[curPosition])) startActivity(intent) } } @Subscribe(threadMode = ThreadMode.MAIN) fun finishCurActivity(event: FinishDetailEvent){ finish() } } <file_sep>/module_day/src/main/java/com/fxy/daymatters/ui/AffairDetailFragment.kt package com.fxy.daymatters.ui import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.fxy.daymatters.R import com.fxy.daymatters.bean.Affair import com.fxy.daymatters.util.getDayFromNow import com.fxy.daymatters.util.getToday import kotlinx.android.synthetic.main.day_fragment_detail.view.* import org.jetbrains.anko.backgroundColor /** * create by:Fxymine4ever * time: 2019/3/27 */ class AffairDetailFragment : Fragment() { lateinit var affair: Affair private lateinit var parent:View override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { parent = inflater.inflate(R.layout.day_fragment_detail,container,false) initView() return parent } private fun initView(){ context?.let {context-> if(!affair.isChineseDay&&affair!=null){//如果不是农历 val endTime = affair.endTime ?: "" if(!endTime.isNotEmpty()){//endDay为空,说明不是计算间隔 val betweenDay = getDayFromNow(getToday(),affair.startTime!! ) if(betweenDay > 0){//如果时间还没到 parent.day_detail_title.text = "${affair.title}还有" parent.day_detail_title.backgroundColor = context.resources.getColor(R.color.day_blue) }else{ //如果时间已经过了 parent.day_detail_title.text = "${affair.title}已经" parent.day_detail_title.backgroundColor = context.resources.getColor(R.color.day_origin) } parent.day_detail_num.text = "${Math.abs(betweenDay)}" }else{ val betweenDay = getDayFromNow(endTime,affair.startTime!!) parent.day_detail_num.text = "${Math.abs(betweenDay)}" parent.day_detail_title.text = "${affair.title}共" parent.day_detail_title.backgroundColor = context.resources.getColor(R.color.day_origin) } }else{//TODO:农历还没想好怎么做Orz } parent.day_detail_time.text = affair.startTime } } }<file_sep>/module_day/src/main/java/com/fxy/daymatters/util/DateUtil.kt package com.fxy.daymatters.util import android.annotation.SuppressLint import com.fxy.daymatters.ui.DayMatterFragment.Companion.cal import java.text.ParseException import java.text.SimpleDateFormat import java.util.* /** * create by:Fxymine4ever * time: 2019/3/27 */ @SuppressLint("SimpleDateFormat") fun getChineseDayOfWeek(time:String):String{ val arr = arrayOf("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六") var date = Date() val sdf = SimpleDateFormat("yyyy-MM-dd") try{ date = sdf.parse(time) }catch (e: ParseException){ e.printStackTrace() } cal.time = date var cur = cal.get(Calendar.DAY_OF_WEEK) - 1 if(cur < 0) cur = 0 return arr[cur] } fun getToday():String{ val df = SimpleDateFormat("yyyy-MM-dd")//设置日期格式 return df.format(Date()) } /** * 2019-03-27 星期三,先通过空格分日期和星期,然后通过-拿到年月日 */ fun getDateFromString(date:String): IntArray { val temp = date.split(" ") val dates = temp[0].split("-") return intArrayOf(dates[0].toInt(),dates[1].toInt(),dates[2].toInt()) } fun getDayFromNow(startDay:String,nowDay:String):Int{ val firstString = startDay.split(" ")[0] val secondString = nowDay.split(" ")[0] return getDaysBetweenTwoDate(firstString,secondString) } fun getDaysBetweenTwoDate(firstString: String, secondString: String): Int { val df = SimpleDateFormat("yyyy-MM-dd") var firstDate: Date? = null var secondDate: Date? = null try { firstDate = df.parse(firstString) secondDate = df.parse(secondString) } catch (e: Exception) { // 日期型字符串格式错误 println("日期型字符串格式错误") } return ((secondDate!!.time - firstDate!!.time) / (24 * 3600 * 1000)).toInt() } <file_sep>/lib_common/src/main/java/com/fxy/lib/utils/extensions/LiveData.kt package com.fxy.lib.utils.extensions import android.arch.lifecycle.LifecycleOwner import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.Observer /** * create by:Fxymine4ever * time: 2019/3/27 */ inline fun <T> MutableLiveData<T>.observe(owner: LifecycleOwner, crossinline onChange:(T?)->Unit) = observe(owner, Observer { onChange(it) }) inline fun <T> LiveData<T>.observeNotNull(owner: LifecycleOwner,crossinline onChange:(T?)->Unit) = observe(owner, Observer { it?:return@Observer onChange(it) })<file_sep>/module_day/src/main/java/com/fxy/daymatters/util/CardTransformer.kt package com.fxy.daymatters.util /** * create by:Fxymine4ever * time: 2019/3/27 */ import android.support.v4.view.ViewPager import android.view.View class CardTransformer : ViewPager.PageTransformer { companion object { private val MAX_SCALE = 1.2f private val MIN_SCALE = 0.75f//0.85f } override fun transformPage(page: View, position: Float) { if (position <= 1) { val scaleFactor = MIN_SCALE + (1 - Math.abs(position)) * (MAX_SCALE - MIN_SCALE) page.scaleX = scaleFactor //缩放效果 if (position > 0) { page.translationX = -scaleFactor * 2 } else if (position < 0) { page.translationX = scaleFactor * 2 } page.scaleY = scaleFactor } else { page.scaleX = MIN_SCALE page.scaleY = MIN_SCALE } } }<file_sep>/module_todo/src/main/java/com/fxy/moduletodo/ui/adapter/TodoListAdapter.kt package com.fxy.moduletodo.ui.adapter import android.content.Context import android.media.Image 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.fxy.moduletodo.R import com.fxy.moduletodo.bean.TodoList /** * create by:Fxymine4ever * time: 2019/7/17 */ class TodoListAdapter(val context:Context,var list: MutableList<TodoList>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.todo_item_rv_todolist,parent) return ViewHolder(view) } override fun getItemCount(): Int = list.size override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val itemView = holder.itemView val finish:ImageView = itemView.findViewById(R.id.todo_rv_finish) val important:ImageView = itemView.findViewById(R.id.todo_rv_important) val content:TextView = itemView.findViewById(R.id.todo_rv_content) //TODO:数据处理 } inner class ViewHolder(itemView:View): RecyclerView.ViewHolder(itemView) { } }<file_sep>/module_day/src/main/java/com/fxy/daymatters/bean/Classify.kt package com.fxy.daymatters.bean import java.io.Serializable /** * create by:Fxymine4ever * time: 2019/3/31 */ data class Classify( val name:String ):Serializable<file_sep>/module_todo/src/main/java/com/fxy/moduletodo/viewmodel/TodoListViewModel.kt package com.fxy.moduletodo.viewmodel import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import com.fxy.moduletodo.bean.TodoList import com.fxy.moduletodo.dao.TodoListDao import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.lang.IllegalArgumentException /** * create by:Fxymine4ever * time: 2019/7/17 */ class TodoListViewModel(private val dataSource: TodoListDao?) : ViewModel() { val todoList:MutableLiveData<MutableList<TodoList>> by lazy(LazyThreadSafetyMode.NONE){ MutableLiveData<MutableList<TodoList>>() } fun getTodoList(){ dataSource?.let {dao-> dao.getTodoList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { todoList.value = it } } } class Factory (private val dataSource: TodoListDao) : ViewModelProvider.Factory{ override fun <T : ViewModel?> create(modelClass: Class<T>): T { if(modelClass.isAssignableFrom(TodoListViewModel::class.java)) return TodoListViewModel(dataSource) as T throw IllegalArgumentException("未知的ViewModel class") } } }<file_sep>/module_day/src/main/java/com/fxy/daymatters/ui/widget/AffairSmallWidget.kt package com.fxy.daymatters.ui.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.ComponentName import android.content.Context import android.content.Intent import android.net.Uri import android.support.annotation.IdRes import android.util.Log import android.view.SoundEffectConstants.CLICK import android.view.View import android.widget.RemoteViews import com.fxy.daymatters.R import com.fxy.daymatters.bean.Classify import com.fxy.daymatters.debug.TestActivity import com.google.gson.Gson import com.google.gson.reflect.TypeToken import org.jetbrains.anko.defaultSharedPreferences import org.jetbrains.anko.startActivity import org.jetbrains.anko.toast class AffairSmallWidget : AppWidgetProvider() { companion object { const val sharedName = "com.fxy.exam.widget" const val sharedClassify = "com.fxy.exam.classify" const val BTN_CLICK = "com.fxy.exam.widget.click" const val COLLECTION_VIEW_EXTRA = "com.fxy.exam.widget.view.extra" const val COLLECTION_VIEW_ACTION = "com.fxy.exam.widget.view.action" var curPosition = 0 lateinit var classify:MutableList<Classify> var widgetId:Int = -1 lateinit var curClassify:String } override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { super.onUpdate(context, appWidgetManager, appWidgetIds) widgetId = appWidgetIds[0] refresh(context) } private fun setListView(context: Context,rv:RemoteViews,classify:String){ //serviceIntent绑定适配器 val serviceIntent = Intent(context,AffairWidgetService::class.java) serviceIntent.putExtra("classify",classify) rv.setRemoteAdapter(R.id.day_widget_list,serviceIntent) } private fun refresh(context: Context ){ val rv = getRemotesView(context) //前后点击事件 rv.setOnClickPendingIntent(getLeftButtonId(), getClickPendingIntent(context,getLeftButtonId(), BTN_CLICK,javaClass)) rv.setOnClickPendingIntent(getRightButtonId(), getClickPendingIntent(context,getRightButtonId(), BTN_CLICK,javaClass)) rv.setOnClickPendingIntent(getTitleTextViewId(), getClickPendingIntent(context,getTitleTextViewId(), BTN_CLICK,javaClass)) val typeToken = object : TypeToken<MutableList<Classify>>(){}.type classify = Gson().fromJson(context.defaultSharedPreferences.getString(sharedClassify,mutableListOf<Classify>().toString()),typeToken) curClassify = classify[curPosition].name rv.setViewVisibility(getRightButtonId(), View.VISIBLE) rv.setViewVisibility(getLeftButtonId(), View.VISIBLE) if(curPosition == 0){ rv.setViewVisibility(getLeftButtonId(), View.GONE) } if(curPosition == classify.size-1){ rv.setViewVisibility(getRightButtonId(), View.GONE) } setListView(context,rv,classify[curPosition].name) rv.setTextViewText(getTitleTextViewId(),"考试周 - ${classify[curPosition].name}") val componentName = ComponentName(context, javaClass) /* 集合不能直接设置点击事件 需要1、设置intent模版 2、通过RemoteViewFactory的getViewAt接口中,设置setOnClickFillIntent设置集合某一数据 */ val listIntent = Intent() listIntent.action = COLLECTION_VIEW_ACTION listIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,componentName) val pi = PendingIntent.getBroadcast(context,0,listIntent,PendingIntent.FLAG_UPDATE_CURRENT) rv.setPendingIntentTemplate(R.id.day_widget_list,pi) show(rv,context) } private fun show(remoteViews: RemoteViews, context: Context) { val manager = AppWidgetManager.getInstance(context) val componentName = ComponentName(context, javaClass) manager.updateAppWidget(componentName, remoteViews) manager.notifyAppWidgetViewDataChanged(widgetId,R.id.day_widget_list) } private fun getClickPendingIntent(context: Context, @IdRes resId: Int, action: String, clazz: Class<AppWidgetProvider>): PendingIntent { val intent = Intent() intent.setClass(context, clazz) intent.action = action intent.data = Uri.parse("id:$resId") return PendingIntent.getBroadcast(context, 0, intent, 0) } override fun onReceive(context: Context?, intent: Intent?) { intent?.let { i-> val action = i.action if(action == COLLECTION_VIEW_ACTION){ val appWidgetId = i.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) val viewIndex = i.getIntExtra(COLLECTION_VIEW_EXTRA,0) }else if(action == BTN_CLICK){ val data = i.data var rId = -1 if(data!=null) rId = data.schemeSpecificPart.toInt() when(rId){ getLeftButtonId()->{ if(curPosition>0){ curPosition-- refresh(context!!) } } getRightButtonId()->{ if(curPosition < classify.size-1){ curPosition++ refresh(context!!) } } getTitleTextViewId()->{ //TODO:合代码更换跳转 val mIntent = Intent(context,TestActivity::class.java) context!!.startActivity(mIntent) } } } } super.onReceive(context, intent) } private fun getLeftButtonId():Int = R.id.day_widget_left private fun getRightButtonId():Int = R.id.day_widget_right private fun getTitleTextViewId():Int = R.id.day_widget_text private fun getRemotesView(context: Context):RemoteViews = RemoteViews(context.packageName,R.layout.day_widget_small_affair) } <file_sep>/module_todo/src/main/java/com/fxy/moduletodo/bean/TodoList.kt package com.fxy.moduletodo.bean import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import android.arch.persistence.room.TypeConverters import com.fxy.moduletodo.util.converters.TodoConverter import java.io.Serializable /** * create by:Fxymine4ever * time: 2019/7/17 */ @Entity(tableName = "TodoList") @TypeConverters(TodoConverter::class) data class TodoList constructor( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id")//id var id:Long, @ColumnInfo(name = "content")//内容 var content:String? = null, @ColumnInfo(name = "deadLine")//截止时间 var deadLine:String? = null, @ColumnInfo(name = "isAddMyDay")//是否添加进我的一天 var isAddMyDay:Boolean = false, @ColumnInfo(name = "isFinish")//是否完成 var isFinish:Boolean = false, @ColumnInfo(name = "isImportant")//是否重要 var isImportant:Boolean = false, @ColumnInfo(name = "steps")//步骤 var steps:MutableList<Step>? = null, @ColumnInfo(name = "notes") var notes:String? = null ):Serializable data class Step( val content: String )<file_sep>/module_day/src/main/java/com/fxy/daymatters/ui/pop/ClassifyListPop.java package com.fxy.daymatters.ui.pop; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Color; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.widget.LinearLayout; import android.widget.TextView; import com.fxy.daymatters.R; import com.fxy.daymatters.bean.Classify; import java.util.List; import razerdp.basepopup.BasePopupWindow; /** * create by:Fxymine4ever * time: 2019/3/30 */ public class ClassifyListPop extends BasePopupWindow { private OnGetChooseListener listener; public void setListener(OnGetChooseListener listener) { this.listener = listener; } public ClassifyListPop(Context context, List<Classify> data){ super(context); System.out.println("classify"); if(data!=null && data.size()>0){ ViewGroup container = findViewById(R.id.day_pop_classify_list_layout); for (Classify s : data) { TextView textView = new TextView(context); textView.setPadding(0,20,0,20); textView.setText(s.getName()); textView.setGravity(Gravity.CENTER); textView.setTextSize(18.0f); textView.setTextColor(Color.parseColor("#000000")); textView.setOnClickListener(v->{ listener.OnGetChoose(s.getName()); dismiss(); }); container.addView(textView); } } setPopupGravity(Gravity.CENTER); } @Override public View onCreateContentView() { return createPopupById(R.layout.day_classify_list_pop); } @Override protected Animation onCreateShowAnimation() { return getDefaultScaleAnimation(true); } @Override protected Animation onCreateDismissAnimation() { return getDefaultScaleAnimation(false); } public interface OnGetChooseListener{ void OnGetChoose(String choose); } } <file_sep>/lib_common/src/main/java/com/fxy/lib/network/ApiGenerator.kt package com.fxy.lib.network import com.fxy.lib.config.BASE_URL import com.exam.lib_common.BuildConfig import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit /** * create by:Fxymine4ever * time: 2019/1/31 */ object ApiGenerator { private const val TIME_OUT = 30 private var retrofit: Retrofit private var okHttpClient: OkHttpClient private var builder: OkHttpClient.Builder = OkHttpClient.Builder() init { builder.writeTimeout((TIME_OUT*5).toLong(), TimeUnit.MILLISECONDS) builder.readTimeout((TIME_OUT*5).toLong(), TimeUnit.MILLISECONDS) builder.connectTimeout((TIME_OUT*5).toLong(), TimeUnit.MILLISECONDS) if (BuildConfig.DEBUG) { val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY builder.addInterceptor(logging) } okHttpClient = builder.build() retrofit = buildRetrofit(BASE_URL) } fun buildRetrofit(baseUrl: String) = Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() fun <T> getApiService(clazz: Class<T>) = retrofit.create(clazz) fun <T> getApiService(retrofit: Retrofit, clazz: Class<T>) = retrofit.create(clazz) }<file_sep>/module_todo/src/main/java/com/fxy/moduletodo/debug/TestActivity2.kt package com.fxy.moduletodo.debug import android.support.v7.app.AppCompatActivity import android.os.Bundle import com.fxy.moduletodo.R import kotlinx.android.synthetic.main.todo_activity_test2.* class TestActivity2 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.todo_activity_test2) } } <file_sep>/module_day/src/main/java/com/fxy/daymatters/dao/DayMatterDao.kt package com.fxy.daymatters.dao import android.arch.lifecycle.LiveData import android.arch.lifecycle.Observer import android.arch.persistence.room.* import com.fxy.daymatters.bean.Affair import io.reactivex.Flowable import io.reactivex.Observable /** * create by:Fxymine4ever * time: 2019/3/21 */ @Dao interface DayMatterDao { @Query("select * from Affair") fun getDayMatters():Flowable<MutableList<Affair>> @Query("select * from Affair where classify = :classify") fun getDayMattersByKind(classify:String):Flowable<MutableList<Affair>> @Insert fun insertDayMatters(bean:Affair):Long @Update fun updateDayMatters(bean:Affair):Int//根据primaryKey更新 @Delete fun deleteDayMatters(bean:Affair):Int @Query("select distinct classify from Affair") fun getClassify():Flowable<MutableList<String>> }<file_sep>/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { compileSdkVersion build_versions.target_sdk buildToolsVersion build_versions.build_tools defaultConfig { applicationId "com.fxy" minSdkVersion build_versions.min_sdk targetSdkVersion build_versions.target_sdk versionCode 1 versionName "第一版" multiDexEnabled true manifestPlaceholders = [UMENG_CHANNEL_VALUE: "official"] kapt { //ARouter arguments { arg("AROUTER_MODULE_NAME", project.getName()) } } } dataBinding { enabled = true } // signingConfigs { // config { // File signingConfigFile = file("../local.properties") // Properties configs = new Properties() // configs.load(new FileInputStream(signingConfigFile)) // // keyAlias configs['RELEASE_KEY_ALIAS'] // keyPassword configs['RELEASE_KEY_PASSWORD'] // storeFile file("../key-exam") // storePassword configs['RELEASE_STORE_PASSWORD'] // } // } buildTypes { debug { minifyEnabled false zipAlignEnabled false shrinkResources false signingConfig signingConfigs.debug manifestPlaceholders = [UMENG_CHANNEL_VALUE: "official"] buildConfigField("String", "BUGLY_APP_ID", "\"dc6a6e9225\"") //signingConfig signingConfigs.config } release { minifyEnabled true zipAlignEnabled true shrinkResources true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' buildConfigField("String", "BUGLY_APP_ID", "\"dc6a6e9225\"") //signingConfig signingConfigs.config productFlavors.all { flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name] } ndk { abiFilters 'armeabi', 'armeabi-v7a' } } } android.applicationVariants.all { variant -> variant.outputs.each { out -> if (out.outputFile != null && out.outputFile.name.endsWith('.apk')) { if ('release' == variant.buildType.name) { def flavorName = variant.flavorName.startsWith("_") ? variant.flavorName.substring(1) : variant.flavorName out.outputFileName = "考试周_${flavorName}_${variant.versionName}.apk" } else if ('com.fxy.daymatters.debug' == variant.buildType.name) { out.outputFileName = "考试周_${variant.versionName}_debug.apk" } } } } lintOptions { abortOnError false disable 'InvalidPackage' checkReleaseBuilds false } productFlavors { kuan {} } flavorDimensions "default" compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } packagingOptions { exclude 'LICENSE.txt' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/ASL2.0' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/services/javax.annotation.processing.Processor' exclude 'META-INF/MANIFEST.MF' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/rxjava.properties' doNotStrip '*/mips/*.so' doNotStrip '*/mips64/*.so' } } dependencies { testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' if (!isModule.toBoolean()) { implementation project(':module_main') implementation project(':module_day') implementation project(':module_todo') } kapt deps.arouter.compiler implementation project(path: ':lib_common') } repositories { mavenCentral() } <file_sep>/lib_common/src/main/java/com/fxy/lib/BaseApp.kt package com.fxy.lib import android.annotation.SuppressLint import android.content.Context import android.support.multidex.BuildConfig import android.support.multidex.MultiDex import android.support.multidex.MultiDexApplication import com.alibaba.android.arouter.launcher.ARouter import com.fxy.lib.network.ApiGenerator import com.umeng.analytics.MobclickAgent import com.umeng.commonsdk.UMConfigure /** * create by:Fxymine4ever * time: 2019/1/31 */ open class BaseApp : MultiDexApplication() { companion object { @SuppressLint("StaticFieldLeak") lateinit var context: Context private set } override fun attachBaseContext(base: Context) { super.attachBaseContext(base) context = base MultiDex.install(this) } override fun onCreate() { super.onCreate() initARouter() initUM() } private fun initARouter(){ //if(BuildConfig.DEBUG){ ARouter.openDebug() ARouter.openLog() //} ARouter.init(this) } private fun initUM(){ UMConfigure.init(applicationContext,UMConfigure.DEVICE_TYPE_PHONE,"5c52d1d0b465f508fe00026d") MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL) MobclickAgent.openActivityDurationTrack(false) //调试模式(推荐到umeng注册测试机,避免数据污染) //UMConfigure.setLogEnabled(BuildConfig.DEBUG) } }<file_sep>/module_day/src/main/java/com/fxy/daymatters/util/Injection.kt package com.fxy.daymatters.util import android.arch.lifecycle.ViewModelProvider import android.content.Context import com.fxy.daymatters.dao.DayMatterDao import com.fxy.daymatters.db.DayMatterDatabase import com.fxy.daymatters.viewmodel.AffairViewModelFactory /** * create by:Fxymine4ever * time: 2019/3/30 */ object Injection{ fun provideAffariDataSrouce(context: Context):DayMatterDao{ return DayMatterDatabase.getInstance(context).dayMattersDao() } fun provideViewModelFactory(context: Context):ViewModelProvider.Factory{ return AffairViewModelFactory(provideAffariDataSrouce(context)) } }<file_sep>/lib_common/src/main/java/com/fxy/lib/ui/BaseFragment.kt package com.fxy.lib.ui import android.os.Bundle import android.support.v4.app.Fragment import android.view.View import com.fxy.lib.event.EmptyEvent import com.umeng.analytics.MobclickAgent import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode /** * create by:Fxymine4ever * time: 2019/1/31 */ abstract class BaseFragment:Fragment() { //若fragment为容器,设置此为false protected abstract val isFragmentContainer:Boolean override fun onResume() { super.onResume() if (!isFragmentContainer) { MobclickAgent.onPageStart(javaClass.name) } } override fun onPause() { super.onPause() if (!isFragmentContainer) { MobclickAgent.onPageEnd(javaClass.name) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) EventBus.getDefault().register(this) } override fun onDestroyView() { super.onDestroyView() EventBus.getDefault().unregister(this) } @Subscribe(threadMode = ThreadMode.MAIN) open fun onEmptyEvent(event: EmptyEvent){ //...以后有什么需要添加再改 } }<file_sep>/lib_common/src/main/java/com/fxy/lib/utils/extensions/File.kt package com.fxy.lib.utils.extensions import android.net.Uri import android.os.Build import android.support.v4.content.FileProvider import com.fxy.lib.BaseApp import java.io.File /** * create by:Fxymine4ever * time: 2019/1/31 */ val File.getUri :Uri get() = if(Build.VERSION.SDK_INT >= 24) FileProvider.getUriForFile(BaseApp.context,"com.exam.FileProvider",this) else Uri.fromFile(this) <file_sep>/module_todo/src/main/java/com/fxy/moduletodo/dao/TodoListDao.kt package com.fxy.moduletodo.dao import android.arch.persistence.room.* import com.fxy.moduletodo.bean.TodoList import io.reactivex.Flowable /** * create by:Fxymine4ever * time: 2019/7/17 */ @Dao interface TodoListDao { @Insert fun insertTodo(todo: TodoList):Long @Update fun updateTodo(todo: TodoList):Int @Delete fun deleteTodo(todo: TodoList):Int @Query("SELECT * FROM TodoList") fun getTodoList():Flowable<MutableList<TodoList>> }<file_sep>/module_todo/src/main/java/com/fxy/moduletodo/debug/TestActivity.kt package com.fxy.moduletodo.debug import android.os.Bundle import com.fxy.lib.ui.BaseActivity import com.fxy.moduletodo.R import com.fxy.moduletodo.ui.MainFragment class TestActivity : BaseActivity() { override val isFragmentActivity: Boolean = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.todo_activity_main) common_toolbar.init("todo",listener = null) initFragment() } private fun initFragment(){ val transaction = supportFragmentManager.beginTransaction() val fragment = MainFragment() transaction.replace(R.id.todo_main_fragment,fragment).commit() } } <file_sep>/lib_common/src/main/java/com/fxy/lib/network/NetworkRetry.kt package com.fxy.lib.network import android.util.Log import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.functions.Function import org.reactivestreams.Publisher import java.lang.Exception import java.util.concurrent.TimeUnit /** * create by:Fxymine4ever * 用于网络失败后重试 * time: 2019/3/20 */ class NetworkRetry(private val maxRetryTimes:Int,private val retryDelayMillis: Int) :Function<Observable<out Throwable>, Observable<*>>{ private var retryTime = 0 init { this.retryTime = 0 } @Throws(Exception::class) override fun apply(t: Observable<out Throwable>): Observable<Any>? { return t.flatMap { throwable -> if(++retryTime <= maxRetryTimes){ Log.i("RetryWithDelay", "网络连接失败..重试中:次数$retryTime") Observable.timer(retryDelayMillis.toLong(),TimeUnit.MILLISECONDS) }else{ Observable.error<Any>(throwable) } } } }<file_sep>/lib_common/src/main/java/com/fxy/lib/config/RouteTable.kt package com.fxy.lib.config /** * create by:Fxymine4ever * time: 2019/3/21 */ const val DAY_MAIN = "/day/Main" const val DAY_AFFAIR = "/day/Affair" const val TODO_MAIN = "/todo/Main"<file_sep>/module_day/src/main/java/com/fxy/daymatters/debug/TestApplication.kt package com.fxy.daymatters.debug import android.annotation.SuppressLint import android.app.Application import android.content.Context import android.support.multidex.MultiDex /** * create by:Fxymine4ever * time: 2019/3/21 */ class TestApplication : Application() { companion object { @SuppressLint("StaticFieldLeak") lateinit var context: Context private set } override fun attachBaseContext(base: Context) { super.attachBaseContext(base) context = base MultiDex.install(this) } }<file_sep>/module_day/src/main/java/com/fxy/daymatters/ui/DayMatterFragment.kt package com.fxy.daymatters.ui import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.PeriodicWorkRequest import androidx.work.WorkManager import com.alibaba.android.arouter.facade.annotation.Route import com.fxy.daymatters.R import com.fxy.daymatters.bean.Affair import com.fxy.daymatters.bean.Classify import com.fxy.daymatters.ui.adapter.DayMattersAdapter import com.fxy.daymatters.ui.pop.ClassifyListPop import com.fxy.daymatters.ui.widget.AffairSmallWidget import com.fxy.daymatters.util.Injection import com.fxy.daymatters.viewmodel.AffairViewModelFactory import com.fxy.daymatters.viewmodel.CommitAffairViewModel import com.fxy.daymatters.workmanager.NotifyWork import com.fxy.lib.config.DAY_MAIN import com.fxy.lib.ui.BaseFragment import com.fxy.lib.utils.extensions.editor import com.fxy.lib.utils.extensions.gone import com.fxy.lib.utils.extensions.observeNotNull import com.fxy.lib.utils.extensions.visible import com.google.gson.Gson import kotlinx.android.synthetic.main.day_day_fragment.view.* import org.jetbrains.anko.defaultSharedPreferences import org.jetbrains.anko.support.v4.startActivity import org.jetbrains.anko.support.v4.toast import java.util.* import java.util.concurrent.TimeUnit /** * create by:Fxymine4ever * time: 2019/3/21 */ @Route(path = DAY_MAIN) class DayMatterFragment : BaseFragment() { lateinit var parent:View private lateinit var mAdapter:DayMattersAdapter private lateinit var list: MutableList<Affair> private lateinit var model: CommitAffairViewModel private var isGrid = true private lateinit var listPop: ClassifyListPop override val isFragmentContainer: Boolean = false private val classlist = mutableListOf<Classify>() companion object { val cal: Calendar = Calendar.getInstance(Locale.CHINA) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { parent = inflater.inflate(R.layout.day_day_fragment,container,false) context?.let { val factory = AffairViewModelFactory(Injection.provideAffariDataSrouce(it)) model = ViewModelProviders.of(this,factory).get(CommitAffairViewModel::class.java) initLiveData(it) initRv(it) initView(it) initWorkManager() } return parent } override fun onResume() { super.onResume() model.getAffairs() model.getClassify() } private fun initLiveData(context: Context){ model.getAffairs() model.mAffairs.observeNotNull(this) {affairs-> affairs?.let { if(affairs.size == 0){ parent.day_main_sr.gone() }else{ parent.day_main_sr.visible() } context.defaultSharedPreferences.editor { putString(AffairSmallWidget.sharedName, Gson().toJson(affairs)) } refreshClassify(context) parent.day_main_sr.isRefreshing = false mAdapter.changeAffairs(affairs) } } model.mClassify.observeNotNull(this){classifies-> context.defaultSharedPreferences.editor { val mutableList = mutableListOf<Classify>() classifies?.forEach { mutableList.add(Classify(it)) } putString(AffairSmallWidget.sharedClassify, Gson().toJson(mutableList)) if(classifies != null && classifies.size>0){ classlist.clear() classlist.addAll(mutableList) } } } } private fun initRv(context: Context){ list = mutableListOf() mAdapter = DayMattersAdapter(list,context,DayMattersAdapter.ItemType.GRID) parent.day_main_rv.adapter = mAdapter parent.day_main_rv.layoutManager = StaggeredGridLayoutManager(2, RecyclerView.VERTICAL) model.getAffairs() } private fun initView(context: Context){ val fabMenu = parent.day_main_fab_menu fabMenu.setClosedOnTouchOutside(false) //添加fab parent.day_main_fab_add.setOnClickListener { startActivity<CommitAffairActivity>() fabMenu.close(true) } //分类fab parent.day_main_fab_classify.setOnClickListener { toast("切换分类") model.getClassify() listPop = ClassifyListPop(context,classlist) listPop.showPopupWindow() listPop.setListener { if(it == "全部"){ model.getAffairs() }else{ model.getAffairsByClassify(it) } } fabMenu.close(true) } //更换布局fab parent.day_main_fab_layout.setOnClickListener { refreshRv(context) fabMenu.close(true) } parent.day_main_sr.setOnRefreshListener { parent.day_main_sr.isRefreshing = true model.getAffairs() } } fun refreshRv(context: Context){ if(!isGrid){ parent.day_main_rv.layoutManager = StaggeredGridLayoutManager(2, RecyclerView.VERTICAL) val newAdapter = DayMattersAdapter(list,context,DayMattersAdapter.ItemType.GRID) parent.day_main_rv.adapter = newAdapter parent.day_main_rv.requestLayout() }else{ parent.day_main_rv.layoutManager = LinearLayoutManager(context) val newAdapter = DayMattersAdapter(list,context,DayMattersAdapter.ItemType.HORIZONTAL) parent.day_main_rv.adapter = newAdapter parent.day_main_rv.requestLayout() } isGrid = !isGrid } private fun refreshClassify(context: Context){ if(isGrid){ parent.day_main_rv.layoutManager = StaggeredGridLayoutManager(2, RecyclerView.VERTICAL) val newAdapter = DayMattersAdapter(list,context,DayMattersAdapter.ItemType.GRID) parent.day_main_rv.adapter = newAdapter parent.day_main_rv.requestLayout() }else{ parent.day_main_rv.layoutManager = LinearLayoutManager(context) val newAdapter = DayMattersAdapter(list,context,DayMattersAdapter.ItemType.HORIZONTAL) parent.day_main_rv.adapter = newAdapter parent.day_main_rv.requestLayout() } } private fun initWorkManager(){ val request = PeriodicWorkRequest .Builder(NotifyWork::class.java,15,TimeUnit.MINUTES) .build() WorkManager.getInstance().enqueueUniquePeriodicWork( "notifyAffair", ExistingPeriodicWorkPolicy.KEEP, request ) } }<file_sep>/module_day/src/main/java/com/fxy/daymatters/ui/adapter/DayMattersAdapter.kt package com.fxy.daymatters.ui.adapter import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.fxy.daymatters.R import com.fxy.daymatters.bean.Affair import com.fxy.daymatters.ui.AffairDetailActivity import com.fxy.daymatters.util.clickWithTrigger import com.fxy.daymatters.util.getDayFromNow import com.fxy.daymatters.util.getToday import com.fxy.daymatters.util.withTrigger import com.google.gson.Gson import kotlinx.android.synthetic.main.day_rv_item_grid.view.* import kotlinx.android.synthetic.main.day_rv_item_horizontal.view.* import org.jetbrains.anko.backgroundColor /** * create by:Fxymine4ever * time: 2019/3/21 */ class DayMattersAdapter(private var list:MutableList<Affair>, private val context:Context, private var itemType:ItemType) : RecyclerView.Adapter<DayMattersAdapter.DayMattersViewHolder>() { var data:MutableList<Affair> = list override fun getItemCount(): Int = data.size override fun onBindViewHolder(holder: DayMattersViewHolder, position: Int) { holder.itemView?.let { if(itemType == ItemType.GRID){//流布局 if(!list[position].isChineseDay){//如果不是农历 val endTime = list[position].endTime ?: "" if(!endTime.isNotEmpty()){//endDay为空,说明不是计算间隔 val betweenDay = getDayFromNow(getToday(),list[position].startTime!! ) if(betweenDay > 0){//如果时间还没到 it.day_item_title.text = "${list[position].title}还有" it.day_item_title.backgroundColor = context.resources.getColor(R.color.day_blue) }else{ //如果时间已经过了 it.day_item_title.text = "${list[position].title}已经" it.day_item_title.backgroundColor = context.resources.getColor(R.color.day_origin) } it.day_item_num.text = "${Math.abs(betweenDay)}" }else{ val betweenDay = getDayFromNow(endTime,list[position].startTime!!) it.day_item_num.text = "${Math.abs(betweenDay)}" it.day_item_title.text = "${list[position].title}共" it.day_item_title.backgroundColor = context.resources.getColor(R.color.day_origin) } }else{//TODO:农历还没想好怎么做Orz } it.day_item_time.text = list[position].startTime }else{//垂直布局 if(!list[position].isChineseDay){ val endTime = list[position].endTime ?: "" if(!endTime.isNotEmpty()){ val betweenDay = getDayFromNow(getToday(),list[position].startTime!! ) if(betweenDay > 0){ it.day_item_hor_title.text = "${list[position].title}还有" it.day_item_hor_num.backgroundColor = context.resources.getColor(R.color.day_blue) it.day_item_hor_day.backgroundColor = context.resources.getColor(R.color.day_blue2) }else{ it.day_item_hor_title.text = "${list[position].title}已经" it.day_item_hor_num.backgroundColor = context.resources.getColor(R.color.day_origin) it.day_item_hor_day.backgroundColor = context.resources.getColor(R.color.day_origin2) } it.day_item_hor_num.text = "${Math.abs(betweenDay)}" }else{ val betweenDay = getDayFromNow(endTime,list[position].startTime!!) it.day_item_hor_num.text = "${Math.abs(betweenDay)}" it.day_item_hor_title.text = "${list[position].title}共" it.day_item_hor_num.backgroundColor = context.resources.getColor(R.color.day_origin) it.day_item_hor_day.backgroundColor = context.resources.getColor(R.color.day_origin2) } }else{//TODO:农历还没想好怎么做Orz } } it.clickWithTrigger{ val intent = Intent(context,AffairDetailActivity::class.java) intent.putExtra("data",Gson().toJson(list)) intent.putExtra("curPosition",position) context.startActivity(intent) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DayMattersViewHolder{ return if (itemType == ItemType.GRID) DayMattersViewHolder(LayoutInflater.from(context).inflate(R.layout.day_rv_item_grid,parent,false)) else DayMattersViewHolder(LayoutInflater.from(context).inflate(R.layout.day_rv_item_horizontal,parent,false)) } enum class ItemType{ GRID,HORIZONTAL } fun addAffairs(list:MutableList<Affair>){ data.addAll(list) notifyDataSetChanged() } fun changeAffairs(list:MutableList<Affair>){ data.clear() data.addAll(list) notifyDataSetChanged() } class DayMattersViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) }<file_sep>/module_day/src/main/java/com/fxy/daymatters/db/DayMatterDatabase.kt package com.fxy.daymatters.db import android.arch.persistence.room.Database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.content.Context import com.fxy.daymatters.bean.Affair import com.fxy.daymatters.dao.DayMatterDao /** * create by:Fxymine4ever * time: 2019/3/21 */ @Database(entities = [Affair::class],version = 1,exportSchema = false) abstract class DayMatterDatabase : RoomDatabase() { abstract fun dayMattersDao():DayMatterDao companion object { @Volatile private var Instance:DayMatterDatabase ?= null fun getInstance(context: Context):DayMatterDatabase = Instance ?: synchronized(this){ Instance ?: buildDatabase(context) } fun buildDatabase(context: Context)= Room.databaseBuilder(context.applicationContext, DayMatterDatabase::class.java,"DayMatter.db").build() } }<file_sep>/module_todo/build/generated/source/kapt/debug/com/fxy/moduletodo/db/TodoListDatabase_Impl.java package com.fxy.moduletodo.db; import android.arch.persistence.db.SupportSQLiteDatabase; import android.arch.persistence.db.SupportSQLiteOpenHelper; import android.arch.persistence.db.SupportSQLiteOpenHelper.Callback; import android.arch.persistence.db.SupportSQLiteOpenHelper.Configuration; import android.arch.persistence.room.DatabaseConfiguration; import android.arch.persistence.room.InvalidationTracker; import android.arch.persistence.room.RoomOpenHelper; import android.arch.persistence.room.RoomOpenHelper.Delegate; import android.arch.persistence.room.util.TableInfo; import android.arch.persistence.room.util.TableInfo.Column; import android.arch.persistence.room.util.TableInfo.ForeignKey; import android.arch.persistence.room.util.TableInfo.Index; import com.fxy.moduletodo.dao.TodoListDao; import com.fxy.moduletodo.dao.TodoListDao_Impl; import java.lang.IllegalStateException; import java.lang.Override; import java.lang.String; import java.lang.SuppressWarnings; import java.util.HashMap; import java.util.HashSet; @SuppressWarnings("unchecked") public class TodoListDatabase_Impl extends TodoListDatabase { private volatile TodoListDao _todoListDao; @Override protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration configuration) { final SupportSQLiteOpenHelper.Callback _openCallback = new RoomOpenHelper(configuration, new RoomOpenHelper.Delegate(1) { @Override public void createAllTables(SupportSQLiteDatabase _db) { _db.execSQL("CREATE TABLE IF NOT EXISTS `TodoList` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content` TEXT, `deadLine` TEXT, `isAddMyDay` INTEGER NOT NULL, `isFinish` INTEGER NOT NULL, `isImportant` INTEGER NOT NULL, `steps` TEXT, `notes` TEXT)"); _db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)"); _db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"d18b0dfc9a08ebc6e20b29982e397b78\")"); } @Override public void dropAllTables(SupportSQLiteDatabase _db) { _db.execSQL("DROP TABLE IF EXISTS `TodoList`"); } @Override protected void onCreate(SupportSQLiteDatabase _db) { if (mCallbacks != null) { for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) { mCallbacks.get(_i).onCreate(_db); } } } @Override public void onOpen(SupportSQLiteDatabase _db) { mDatabase = _db; internalInitInvalidationTracker(_db); if (mCallbacks != null) { for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) { mCallbacks.get(_i).onOpen(_db); } } } @Override protected void validateMigration(SupportSQLiteDatabase _db) { final HashMap<String, TableInfo.Column> _columnsTodoList = new HashMap<String, TableInfo.Column>(8); _columnsTodoList.put("id", new TableInfo.Column("id", "INTEGER", true, 1)); _columnsTodoList.put("content", new TableInfo.Column("content", "TEXT", false, 0)); _columnsTodoList.put("deadLine", new TableInfo.Column("deadLine", "TEXT", false, 0)); _columnsTodoList.put("isAddMyDay", new TableInfo.Column("isAddMyDay", "INTEGER", true, 0)); _columnsTodoList.put("isFinish", new TableInfo.Column("isFinish", "INTEGER", true, 0)); _columnsTodoList.put("isImportant", new TableInfo.Column("isImportant", "INTEGER", true, 0)); _columnsTodoList.put("steps", new TableInfo.Column("steps", "TEXT", false, 0)); _columnsTodoList.put("notes", new TableInfo.Column("notes", "TEXT", false, 0)); final HashSet<TableInfo.ForeignKey> _foreignKeysTodoList = new HashSet<TableInfo.ForeignKey>(0); final HashSet<TableInfo.Index> _indicesTodoList = new HashSet<TableInfo.Index>(0); final TableInfo _infoTodoList = new TableInfo("TodoList", _columnsTodoList, _foreignKeysTodoList, _indicesTodoList); final TableInfo _existingTodoList = TableInfo.read(_db, "TodoList"); if (! _infoTodoList.equals(_existingTodoList)) { throw new IllegalStateException("Migration didn't properly handle TodoList(com.fxy.moduletodo.bean.TodoList).\n" + " Expected:\n" + _infoTodoList + "\n" + " Found:\n" + _existingTodoList); } } }, "d18b0dfc9a08ebc6e20b29982e397b78", "dd60808d8efdce2e1977666fb365a100"); final SupportSQLiteOpenHelper.Configuration _sqliteConfig = SupportSQLiteOpenHelper.Configuration.builder(configuration.context) .name(configuration.name) .callback(_openCallback) .build(); final SupportSQLiteOpenHelper _helper = configuration.sqliteOpenHelperFactory.create(_sqliteConfig); return _helper; } @Override protected InvalidationTracker createInvalidationTracker() { return new InvalidationTracker(this, "TodoList"); } @Override public void clearAllTables() { super.assertNotMainThread(); final SupportSQLiteDatabase _db = super.getOpenHelper().getWritableDatabase(); try { super.beginTransaction(); _db.execSQL("DELETE FROM `TodoList`"); super.setTransactionSuccessful(); } finally { super.endTransaction(); _db.query("PRAGMA wal_checkpoint(FULL)").close(); if (!_db.inTransaction()) { _db.execSQL("VACUUM"); } } } @Override public TodoListDao todoListDao() { if (_todoListDao != null) { return _todoListDao; } else { synchronized(this) { if(_todoListDao == null) { _todoListDao = new TodoListDao_Impl(this); } return _todoListDao; } } } } <file_sep>/app/src/main/java/com/fxy/app/App.kt package com.fxy.app import android.content.Context import android.os.Process import android.support.multidex.MultiDex import com.alibaba.android.arouter.launcher.ARouter import com.exam.app.BuildConfig import com.fxy.lib.BaseApp import com.fxy.lib.utils.getAppVersionName import com.fxy.lib.utils.getProcessName import com.tencent.bugly.crashreport.CrashReport /** * create by:Fxymine4ever * time: 2019/1/31 */ class App : BaseApp() { override fun onCreate() { super.onCreate() initBugly() if(BuildConfig.DEBUG){ ARouter.openDebug() ARouter.openLog() } ARouter.init(this) } override fun attachBaseContext(base: Context) { super.attachBaseContext(base) MultiDex.install(context) } private fun initBugly(){ //bugly文档配置 val packageName = applicationContext.packageName val processName = getProcessName(Process.myPid()) val strategy = CrashReport.UserStrategy(applicationContext) strategy.appVersion = getAppVersionName(applicationContext) strategy.isUploadProcess = processName == null || processName == packageName CrashReport.initCrashReport(applicationContext, BuildConfig.BUGLY_APP_ID, BuildConfig.DEBUG,strategy) if(BuildConfig.DEBUG) CrashReport.setUserSceneTag(applicationContext,10000)//自定义标签 } }<file_sep>/lib_common/src/main/java/com/fxy/lib/utils/ViewModelDelegate.kt package com.fxy.lib.utils import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProviders import com.fxy.lib.ui.BaseActivity import com.fxy.lib.ui.BaseFragment import kotlin.reflect.KClass import kotlin.reflect.KProperty /** * create by:Fxymine4ever * time: 2019/3/20 */ class ViewModelDelegate<out T: ViewModel>( private val clazz: KClass<T>, private val fromActivity:Boolean ){ private var viewModel: T? = null operator fun getValue(reference:BaseActivity,property:KProperty<*>) = buildViewModel(activity = reference) operator fun getValue(reference: BaseFragment, property: KProperty<*>) = if (fromActivity) buildViewModel(activity = reference.activity as? BaseActivity ?: throw IllegalStateException("Activity must be as BaseActivity")) else buildViewModel(fragment = reference) private fun buildViewModel(activity: BaseActivity? = null, fragment: BaseFragment? = null): T{ if(viewModel != null) return viewModel!! activity?.let { viewModel = ViewModelProviders.of(it).get(clazz.java) } ?: fragment?.let { viewModel = ViewModelProviders.of(it).get(clazz.java) } ?: throw IllegalStateException("Activity or Fragment is null! ") return viewModel!! } fun <T : ViewModel> BaseActivity.viewModelDelegate(clazz: KClass<T>) = ViewModelDelegate(clazz, true) // fromActivity默认为true,viewModel生命周期默认跟activity相同 fun <T : ViewModel> BaseFragment.viewModelDelegate(clazz: KClass<T>, fromActivity: Boolean = true) = ViewModelDelegate(clazz, fromActivity) }<file_sep>/lib_common/src/main/java/com/fxy/lib/utils/NotificationUtils.kt package com.fxy.lib.utils import android.annotation.TargetApi import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.ContextWrapper import android.os.Build import android.support.v4.app.NotificationCompat.VISIBILITY_SECRET import android.R import android.support.v4.app.NotificationCompat import android.support.v4.app.NotificationCompat.PRIORITY_DEFAULT import android.graphics.BitmapFactory import android.app.PendingIntent /** * create by:Fxymine4ever * time: 2019/3/31 */ class NotificationUtils(base: Context?) : ContextWrapper(base) { companion object { const val CHANNEL_ID = "com.fxy.exam" const val CHANNEL_NAME = "com.fxy.exam.notify" } private val manager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager init { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ createNotificationChannel() } } @TargetApi(Build.VERSION_CODES.O) private fun createNotificationChannel(){ val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT) channel.canBypassDnd() channel.lockscreenVisibility = VISIBILITY_SECRET channel.canShowBadge() channel.enableVibration(true) channel.setBypassDnd(true) channel.vibrationPattern = longArrayOf(100, 100, 200) getManager().createNotificationChannel(channel) } private fun getManager():NotificationManager{ return manager } fun sendNotification(title: String, content: String,pendingIntent: PendingIntent) { val builder = getNotification(title, content,pendingIntent) getManager().notify((Math.random()*1000).toInt(), builder!!.build())//notify的id设置为不同,显示多个notification } private fun getNotification(title: String, content: String,pendingIntent: PendingIntent): NotificationCompat.Builder? { val builder: NotificationCompat.Builder? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID) } else { builder = NotificationCompat.Builder(applicationContext) builder.priority = PRIORITY_DEFAULT } //标题 builder.setContentTitle(title) //文本内容 builder.setContentText(content) //小图标 builder.setSmallIcon(R.drawable.ic_dialog_email)////TODO:通知的icon //设置点击信息后自动清除通知 builder.setAutoCancel(true) builder.setContentIntent(pendingIntent) return builder } fun sendNotificationProgress(title: String, content: String, progress: Int, intent: PendingIntent) { val builder = getNotificationProgress(title, content, progress, intent) getManager().notify(0, builder.build()) } private fun getNotificationProgress(title: String, content: String, progress: Int, intent: PendingIntent): NotificationCompat.Builder { var builder: NotificationCompat.Builder? = null if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID) } else { builder = NotificationCompat.Builder(applicationContext) builder.priority = PRIORITY_DEFAULT } builder.setContentTitle(title) builder.setContentText(content) builder.setSmallIcon(R.drawable.ic_dialog_email) builder.setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.ic_dialog_email)) if (progress > 0 && progress < 100) { builder.setProgress(100, progress, false) } else { builder.setProgress(0, 0, false) builder.setContentText("下载完成") } builder.setAutoCancel(true) builder.setWhen(System.currentTimeMillis()) builder.setContentIntent(intent) return builder } }<file_sep>/lib_common/src/main/java/com/fxy/lib/utils/extensions/Context.kt package com.fxy.lib.utils.extensions import android.content.Context import android.graphics.Point import android.support.annotation.DrawableRes import android.view.WindowManager import android.widget.ImageView import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.request.RequestOptions import com.exam.lib_common.R /** * create by:Fxymine4ever * time: 2019/1/31 */ var screenHeight: Int = 0 var screenWidth: Int = 0 fun Context.getScreenHeight(): Int { if (screenHeight == 0) { val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager val display = windowManager.defaultDisplay val size = Point() display.getSize(size) screenHeight = size.y } return screenHeight } fun Context.getScreenWidth(): Int { if (screenHeight == 0) { val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager val display = windowManager.defaultDisplay val size = Point() display.getSize(size) screenWidth = size.x } return screenWidth } fun Context.loadImage(url: String?, imageView: ImageView, @DrawableRes placeholder: Int = R.drawable.holder, @DrawableRes error: Int = R.drawable.error) { url?.let { Glide.with(this) .load(it) .transition(DrawableTransitionOptions().crossFade()) .apply(RequestOptions().placeholder(placeholder).error(error)) .into(imageView) } }<file_sep>/module_main/src/main/java/com/fxy/main/util/BottomNaVUtil.kt package com.fxy.main.util import android.annotation.SuppressLint import android.support.design.internal.BottomNavigationItemView import android.support.design.internal.BottomNavigationMenuView import android.support.design.widget.BottomNavigationView /** * create by:Fxymine4ever * time: 2019/3/21 */ @SuppressLint("RestrictedApi") fun disableShiftMode(view : BottomNavigationView){ val menu = view.getChildAt(0) as BottomNavigationMenuView try { val shiftingMode = menu::class.java.getDeclaredField("mShiftingMode") shiftingMode.isAccessible = true shiftingMode.setBoolean(menu, false) shiftingMode.isAccessible = false for (i in 0..menu.childCount) { if(menu.getChildAt(i)!=null){ val item = menu.getChildAt(i) as BottomNavigationItemView //noinspection RestrictedApi item.setShiftingMode(false) // set once again checked value, so view will be updated //noinspection RestrictedApi item.setChecked(item.itemData.isChecked) } } }catch (e:NoSuchFieldException){ }catch (e:IllegalAccessException){ } }
f82da26bea77de84a404cda868fb9e4c99b7cce9
[ "Markdown", "Java", "Kotlin", "Gradle" ]
64
Kotlin
Fxy4ever/ExamWeek
93d95df6c252a180ae283fae85f534304f2d7954
5748fc51dfcecedca379fd26723deea4dfc58af2
refs/heads/master
<repo_name>edwardianec/hystogram_equalization<file_sep>/eq.py import matplotlib import matplotlib.pyplot as plt import numpy as np import cv2 import gc import glob img0 = cv2.imread('images/src/0.tif',0) img1 = cv2.imread('images/src/1.tif',0) img2 = cv2.imread('images/src/2.tif',0) img3 = cv2.imread('images/src/3.tif',0) img4 = cv2.imread('images/src/4.tif',0) def filters(img): #kernel = np.ones((5,5),np.float32)/25 kernel_edges = [ [0, -2, 0], [-2, 0, 2], [0, 2, 0] ] kernel_clarity = [ [-1, -1, -1], [-1, 9, -1], [-1, -1, -1] ] kernel_clarity_0 = [ [0, -1, 0], [-1, 5, -1], [0, -1, 0] ] kernel_gausian = [ [1/16, 2/16, 1/16], [2/16, 4/16, 2/16], [1/16, 2/16, 1/16] ] kernel_edges_mat = np.array(kernel_edges, dtype=float); kernel_clarity_mat = np.array(kernel_clarity, dtype=float); kernel_clarity_0_mat = np.array(kernel_clarity_0, dtype=float); kernel_gausian_mat = np.array(kernel_gausian, dtype=float); edges_image = cv2.filter2D(img,-1,kernel_edges_mat) clarity_image = cv2.filter2D(img,-1,kernel_clarity_mat) clarity_0_image = cv2.filter2D(img,-1,kernel_clarity_0_mat) gausian_image = cv2.filter2D(img,-1,kernel_gausian_mat) bilateral_image = cv2.bilateralFilter(img,9,5,5) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) clahe_image = clahe.apply(gausian_image) # # #bioinspired # # # def get_retina(cv_img): #bm3d = cv2.imread('images/src/coffeebm3dsharp.tif',0) retina = cv2.bioinspired.Retina_create((cv_img.shape[1], cv_img.shape[0])) # the retina object is created with default parameters. If you want to read # the parameters from an external XML file, uncomment the next line retina.setup('setup.xml') # feed the retina with several frames, in order to reach 'steady' state retina.run(cv_img) # get our processed image :) return retina.getParvo() def modify_image_core(val): new_val = 0 if (val >= 127): new_val = val*2 else: new_val = val new_val = 255 if new_val>255 else new_val return new_val def cumm_sum(): pass def modify_image(img): height, width = img.shape resolution = height*width histogram = build_hyst(img) mult = 255/resolution new_greys = {} for i in range(0,256): new_greys[i] = cumm_sum(i)*mult #img_new = np.zeros((height,width)) img_new = 255 * np.ones(shape=[height, width, 1], dtype=np.uint8) for j in range(0,height): for i in range(0, width): pixel_val = img[j,i] new_val = modify_image_core(pixel_val) img_new[j,i] = new_val return img_new def my_resize(img, percent): width = int(img.shape[1] * percent / 100) height = int(img.shape[0] * percent / 100) dim = (width, height) # resize image return cv2.resize(img, dim, interpolation = cv2.INTER_AREA) def my_subplots(img1, img2): hist, edges = np.histogram(img1,bins=range(255)) hist2, edges2 = np.histogram(img2,bins=range(255)) hystogram = build_hist(img3) lag = 0.1 x = list(range(1,256)) y = [(hystogram[out]+hystogram[out-1]) for out in x if out>0 ] ax = plt.subplot(2, 2, 1) # Draw the plot ax.bar(edges[:-1], hist, width = 0.5, color='#0504aa') # Title and labels ax.set_title('Histogram of image 1', size = 10) ax.set_xlabel('grey level', size = 10) ax.set_ylabel('amount', size= 10) ax = plt.subplot(2, 2, 2) # Draw the plot ax.bar(edges2[:-1], hist2, width = 0.5, color='#0504aa') # Title and labels ax.set_title('Histogram of image 2', size = 10) ax.set_xlabel('grey level', size = 10) ax.set_ylabel('amount', size= 10) ax = plt.subplot(2, 2, 3) ax.plot(x,y) plt.tight_layout() plt.show() #modified_image = modify_image(img4) #--------------------------------------------------------- MAX_GREY_LEVEL = 256 def build_hist(img): height, width = img.shape hist = dict(enumerate([0]*256)) for j in range(0,height): for i in range(0, width): pixel_val = int(img[j,i]) #print("pix_val:",pixel_val) hist[pixel_val] = hist[pixel_val]+1 return hist def normilize_image(img, histogram): height, width = img.shape hist_minimum = 0 hist_maximum = 0 for grey in range(0,256): if histogram[grey]: if (hist_minimum == 0): hist_minimum = grey hist_maximum = grey stretch_coefficient = 255/(hist_maximum) normilized_image = np.zeros(shape=[height, width], dtype=np.uint8) for i in range(0,width): for j in range(0, height): pixel_val = img[j,i] new_val = int((pixel_val-hist_minimum)*stretch_coefficient) normilized_image[j,i] = new_val #if new_val <=255 else 255 min_percent = (hist_minimum / (width*height))*100 max_percent = (hist_maximum / (width*height))*100 #print("HIST_MINIMUM:{0}, HIST_MAXIMUM:{1} ;".format(hist_minimum, hist_maximum)) #print("HIST_MINIMUM %:{0}, HIST_MAXIMUM %:{1} ;".format(min_percent, max_percent)) return normilized_image def cumul_hist_val(histogram, grey): #print(histogram) cum = 0 for i in range(0, grey): cum = cum + histogram[i] return cum def cdf_trashold(histogram, grey, trashold): cum = 0 for i in range(0, grey): hist_val = histogram[i] if histogram[i] < trashold else trashold cum = cum + hist_val return cum def cumulative_function(histogram): cum_dict = {} for i in range(0,256): cum_dict[i] = cumul_hist_val(histogram,i) return (cum_dict.keys(), cum_dict.values()) def equalization_image(img, histogram): height, width = img.shape eq_image = np.zeros(shape=[height, width], dtype=np.uint8) eq_image.fill(0) for i in range(0,width): for j in range(0, height): pixel_val = img[j,i] new_val = (255/(width*height))*cumul_hist_val(histogram, pixel_val) eq_image[j,i] = int(new_val) return eq_image # adaptive trashold def equalization_image_2(img, histogram, trashold): height, width = img.shape eq_image = np.zeros(shape=[height, width], dtype=np.uint8) multiplyer = (MAX_GREY_LEVEL-1)/cdf_trashold(histogram, MAX_GREY_LEVEL-1, trashold) for i in range(0,width): for j in range(0, height): pixel_val = img[j,i] new_val = multiplyer*cdf_trashold(histogram, pixel_val, trashold) eq_image[j,i] = int(new_val) return eq_image def show_graphs(graphs, width, height, image_filename_path=""): figure, axs = plt.subplots(height, width, gridspec_kw={'hspace': 0.5, 'wspace': 0.5}) image_filename = image_filename_path.split("\\")[-1] image_path = "\\".join(image_filename_path.split("\\")[:-1]) i,j = 0,0 for graph in graphs: axs[j,i].bar(graph[0], graph[1]) axs[j,i].set_title("graph {0}, {1}".format(j,i)) i = i+1 if (i>width-1): i = 0 j = j+1 if (image_filename_path): plt.savefig(image_path+"\\processed\\figures\\"+image_filename+"_figure.png") else: plt.show() figure.clf() plt.close() def show_graphs_simple(graph1, graph2, width): figure, (axs1, axs2 ) = plt.subplots( width, gridspec_kw={'hspace': 0.5, 'wspace': 0.5}) axs1.bar(graph1[0], graph1[1]) axs1.set_title("hist 0") axs2.bar(graph2[0], graph2[1]) axs2.set_title("hist 1") plt.show() def hist_peaks(h): last_val_item = 0 peaks = {} peaks[0] = 0 for i in range(1, MAX_GREY_LEVEL-1): if (h[i]): last_val_item = i if ((h[i] > h[i-1]) and (h[i] > h[i+1])): peaks[i] = h[i] else: peaks[i] = 0 else: peaks[i] = 0 return peaks def find_peaks_avarage(h): counter = 0 sum = 0 for i in range(1, MAX_GREY_LEVEL): if (h[i]): counter = counter + 1 sum = sum + h[i] avarage = int(sum/counter) return avarage def process_image(image_filename_path): #print("image_filename_path:", image_filename_path) image_filename = image_filename_path.split("\\")[-1] image_path = "\\".join(image_filename_path.split("\\")[:-1]) img = cv2.imread(image_filename_path, cv2.IMREAD_GRAYSCALE) height, width = img.shape src_hyst = build_hist(img) normilized_image = normilize_image(img, src_hyst) norm_hyst = build_hist(normilized_image) #simple equalization eq_image = equalization_image(img, src_hyst) eq_hyst = build_hist(eq_image) #peaks of image peaks_src_hist = hist_peaks(src_hyst) peak_trashold = find_peaks_avarage(src_hyst) #print("trashold:",peak_trashold) #equalization with trashold eq_trashold_img = equalization_image_2(img, src_hyst, peak_trashold/5) eq_trashold_hyst = build_hist(eq_trashold_img) graph_src_hyst = [src_hyst.keys(), src_hyst.values()] graph_eq_hyst = [eq_hyst.keys(), eq_hyst.values()] graph_norm_hyst = [norm_hyst.keys(), norm_hyst.values()] graph_eq_trashold_hyst = [eq_trashold_hyst.keys(), eq_trashold_hyst.values()] graph_peaks_hyst = [peaks_src_hist.keys(), peaks_src_hist.values()] show_graphs( [ graph_src_hyst, graph_norm_hyst , graph_eq_hyst, graph_eq_trashold_hyst #graph_peaks_hyst, #cumulative_function(src_hyst), #cumulative_function(norm_hyst), #cumulative_function(eq_hyst), #cumulative_function(eq_trashold_hyst), #cumulative_function(peaks_src_hist) ], width=2, height=2, image_filename_path=image_filename_path) row0 = np.concatenate( (my_resize(img,80), my_resize(eq_image, 80)), axis=0) row1 = np.concatenate( (my_resize(normilized_image,80), my_resize(eq_trashold_img, 80)), axis=0) full_image = np.concatenate( (row0, row1), axis=1) #cv2.imshow('modified_image', full_image) #print("write_path:", image_writepath+"\\"+image_filename) cv2.imwrite(image_path+"\\processed\\images\\"+image_filename, full_image) #del a, b #gc.collect() #cv2.imshow('modified_image',eq_image) #------------------------------MAIN----------------------------------------- src_path = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\video\M11-2231\\tiff\\*.tif" images = glob.glob(src_path) img_amount = len(images) img_counter = 0 for image in images: img_counter = img_counter + 1 print("{0} of {1}".format(img_counter, img_amount)) process_image(image) #concat_images = np.concatenate( (my_resize(img4,50), my_resize(img4, 50)), axis=1) #cv2.imshow('modified_image',concat_images ) #my_subplots(img4, img4) gc.collect() cv2.waitKey(0) cv2.destroyAllWindows() <file_sep>/fuzzy.py import matplotlib import matplotlib.pyplot as plt import numpy as np import cv2 import gc def dark_func(z,a,b): if (z<= a): y = 1 elif (z>a and z<= a+b): y = 1 - (z-a) / b else: y = 0 return y def grey_func(z, a,b,c): if (z < a and z >= a-b): y = 1 - (a-z)/b elif (a<=z and z<= a+c): y = 1 - (z-a)/c else: y = 0 return y def highlight_func(z,a,b): if (a-b <=z and z <= a): y = 1 - (a-z)/b elif (z>= a): y = 1 else: y = 0 return y def show_fuzz_func(): print("############ dark func ##############") for i in range(0, 20): y = dark_func(z=i,a=7,b=3) print("x:{0}, y:{1}".format(i,y)) print("############ grey func ##############") for i in range(0, 20): y = grey_func(z=i,a=10,b=7,c=6) print("x:{0}, y:{1}".format(i,y)) print("############ highlight func ##############") for i in range(0, 20): y = highlight_func(z=i,a=13,b=3) print("x:{0}, y:{1}".format(i,y)) def defuzification(z,vd,vg,vb): ud = dark_func(z=z,a=3,b=7) ug = grey_func(z=z,a=10,b=7,c=6) ub = highlight_func(z=z,a=16,b=6) #print("x:{0},ud:{1},ug:{2},ub:{3}".format(z,ud,ug,ub)) a = ud*vd+ug*vg+ub*vb b = ud+ug+ub v = a/b print("x:{0}, | a:{1},b:{2} | v:{3};".format(z, a,b,v)) return v #----------------------------------------- for i in [4,5,6,10,12,14,15,16,17]: defuzification(i,0,10,20)<file_sep>/fuzzyfication.py import numpy as np import matplotlib import matplotlib.pyplot as plt #------------------------------------------------------------------------------------------------------------- # Функции принадлежности к множествам # и функция вывода множест в виде графиков def sigma_left_func(z,params, max_top=1): a,b = params[0], params[1] if (z > a and z < b): y = (1 - (z-a)/(b-a) )*max_top elif (z<= a): y = 1*max_top else: y = 0 return y def trianglural_func(z, params, max_top=1): a,b,c = params[0], params[1], params[2] if (z < b and z >= a): y = (1 - (b-z)/(b-a) )*max_top elif (z >= b and z < c): y = (1 - (z-b)/(c-b) )*max_top else: y = 0 return y def sigma_right_func(z,params, max_top=1): a,b = params[0], params[1] if (z > a and z <= b): y = (1 - (b-z)/(b-a) )*max_top elif (z>= b): y = 1*max_top else: y = 0 return y def plt_member_functions(params, member_vds, max_top=1): max_grade = 256 y = [] #member_params = [0,30,60,80,100,150,229,255] y.append( [sigma_left_func(x, params[0:2], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[0:3], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[1:4], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[2:5], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[3:6], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[4:7], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[5:8], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[6:9], max_top=max_top) for x in range(0,max_grade)] ) y.append( [sigma_right_func(x,params[7:10], max_top=max_top) for x in range(0,max_grade)] ) y_vds = [x*15 for x in range(0,(max_grade-1))] x_vds = [] x_vds.append( [member_vds[0]]*(max_grade-1)) x_vds.append( [member_vds[1]]*(max_grade-1)) x_vds.append( [member_vds[2]]*(max_grade-1)) x_vds.append( [member_vds[3]]*(max_grade-1)) x_vds.append( [member_vds[4]]*(max_grade-1)) x_vds.append( [member_vds[5]]*(max_grade-1)) x_vds.append( [member_vds[6]]*(max_grade-1)) x_vds.append( [member_vds[7]]*(max_grade-1)) x_vds.append( [member_vds[8]]*(max_grade-1)) x = range(0,max_grade) return plt.plot( #x, y[0], x, y[1], x, y[2], x, y[3], x, y[4], x, y[5], x, y[6], x, y[7], x_vds[0], y_vds, x_vds[1], y_vds, x_vds[2], y_vds, x_vds[3], y_vds, x_vds[4], y_vds, x_vds[5], y_vds, x_vds[6], y_vds, x_vds[7], y_vds, x_vds[8], y_vds ) #------------------------------------------------------------------------------------------------------------- # описание формулы на странице 233, Мир цифровой обработки def defuzification(ums, vds ): (a, b) = 0, 0 for i in range(0,len(ums)): a = a + ums[i]*vds[i] b = b + ums[i] v = a/b #print("x:{0}, | a:{1},b:{2} | v:{3};".format(z, a,b,v)) return int(v) def get_defuzzification_list(params, vds): max_grade = 256 defuzz_list = [] for z in range(0, max_grade): ums = [] ums.append(sigma_left_func(z, params[0:2])) ums.append(trianglural_func(z, params[0:3])) ums.append(trianglural_func(z, params[1:4])) ums.append(trianglural_func(z, params[2:5])) ums.append(trianglural_func(z, params[3:6])) ums.append(trianglural_func(z, params[4:7])) ums.append(trianglural_func(z, params[5:8])) ums.append(trianglural_func(z, params[6:9])) ums.append(sigma_right_func(z, params[7:10])) defuzz_list.append(defuzification(ums,vds)) return defuzz_list def get_fuzzy_image(img, params, vds): height, width, = img.shape[0:2] fuzzy_image = np.zeros(shape=[height, width], dtype=np.uint8) fuzzy_list = get_defuzzification_list(params, vds) for i in range(0,width): for j in range(0, height): pixel_val = int(img[j,i] ) new_val = fuzzy_list[pixel_val] fuzzy_image[j,i] = new_val return fuzzy_image<file_sep>/raw/code.c public static UInt16[] ToUint16(byte[] pixelData, PixelFormat pixelFormat) { if (pixelData == null) throw new ArgumentNullException(); int pixelOccupy = pixelFormat.PixelOccupy; UInt16[] result = new UInt16[8 * pixelData.Length / pixelOccupy]; int bitCount = 0; UInt32 accumulataor = 0; UInt32 mask = (UInt32)((1 << pixelOccupy) - 1); for (int i = 0, ix = 0; i < pixelData.Length; i++) { if (bitCount > pixelOccupy) { result[ix++] = (UInt16)(accumulataor & mask); accumulataor >>= pixelOccupy; bitCount -= pixelOccupy; } accumulataor |= ((UInt32)pixelData[i] << bitCount); bitCount += 8; } return result; }<file_sep>/test_pattern/test_pattern_gen.py import matplotlib import matplotlib.pyplot as plt import numpy as np import cv2 import gc #------------------------------MAIN----------------------------------------- def get_value(i,m,k): value = 255 for j in range(0, (640//m)): if (i > j*m and i <= (j+1)*m): value = value-(k*j) return value def create_test_pattern(): height = 480 width = 640 first_grade = 255 img_new = 255 * np.ones(shape=[height, width, 1], dtype=np.uint8) for j in range(0,height): for i in range(0, width): img_new[j,i] = get_value(i,5,2) return img_new cv2.imwrite("test_pattern.png",create_test_pattern()) <file_sep>/convolution.py import matplotlib import matplotlib.pyplot as plt import numpy as np import cv2 import gc import glob #modified_image = modify_image(img4) #--------------------------------------------------------- MAX_GREY_LEVEL = 256 def kernel_tree(a, comb, position, variants): for i in comb: a[position] = i if (position-1 >= 0): next_position = position -1 kernel_tree(a, comb, next_position,variants ) else: variants.append(a[:]) def build_kernels(comb, kernel_size): combinations = [] a = [0]*(kernel_size*kernel_size) list_variants = [] kernel_tree(a, comb, kernel_size*kernel_size-1, list_variants) nparray = [] for variant in list_variants: new_arr = np.array( [np.array(variant[i*kernel_size:(i*kernel_size)+kernel_size], dtype="int8") for i in range(0,kernel_size)], dtype="int8") nparray.append(new_arr) return nparray def process_image(img_sum_t0, img_sum_t1, image_filename_path, write_path, kernel, kernel_position): image_filename = image_filename_path.split("\\")[-1] img = cv2.imread(image_filename_path, cv2.IMREAD_GRAYSCALE) conv_image = cv2.filter2D(img,-1,kernel) height, width = conv_image.shape img_sum = 0 img_sum = cv2.sumElems(conv_image) #print("conv_sum ", img_sum[0] ) #print("{0}:{1}".format(kernel_position, [str(i) for i in kernel])) if (img_sum[0] == img_sum_t1[0]): print("{0}:{1}".format(kernel_position, [str(i) for i in kernel])) cv2.imwrite(write_path+str(kernel_position)+".tif", conv_image) #------------------------------MAIN----------------------------------------- #images = glob.glob("D:\\resilio\\ip_lib_ed\\src_images\\dslr\\tif\\*.tif") def main(): image_filename_path = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\tif\\_MG_9778.TIF" target_image_0 = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\tif\\_MG_9778_t0.TIF" target_image_1 = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\tif\\_MG_9778_t1.TIF" t_img0 = cv2.imread(target_image_0, cv2.IMREAD_GRAYSCALE) t_img1 = cv2.imread(target_image_1, cv2.IMREAD_GRAYSCALE) img_sum_t0 = cv2.sumElems(t_img0) img_sum_t1 = cv2.sumElems(t_img1) print(img_sum_t0[0], "or ", img_sum_t1[0] ) write_path = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\tif\\processed\\" kernel_position = 0 kernels = build_kernels(comb=[-1,-3, 0,1,2,5],kernel_size=3) print("total variants: ", len(kernels)) for kernel in kernels: process_image(img_sum_t0, img_sum_t1, image_filename_path=image_filename_path, write_path=write_path, kernel=kernel, kernel_position=kernel_position) kernel_position = kernel_position + 1 #concat_images = np.concatenate( (my_resize(img4,50), my_resize(img4, 50)), axis=1) #cv2.imshow('modified_image',concat_images ) #my_subplots(img4, img4) main() cv2.waitKey(0) cv2.destroyAllWindows() gc.collect() plt.close() <file_sep>/test.py def yep(x): if(x >= 80): y = 5 elif(x >= 60): y = 3 elif(x >= 30):y=2 else: y=1 return y print(yep(100))<file_sep>/convolution_processing.py import matplotlib import matplotlib.pyplot as plt import numpy as np import cv2 import gc import glob import statistics #------------------------------------------------------------------------------------------------------------- # Операции с гистограммой def build_hist(img): height, width = img.shape hist = dict(enumerate([0]*256)) for j in range(0,height): for i in range(0, width): pixel_val = int(img[j,i]) #print("pix_val:",pixel_val) hist[pixel_val] = hist[pixel_val]+1 return hist def build_first_derivative(hist): max = 255 derivative = dict(enumerate([0]*(max+1))) j = 0 for i in range(0, max+1): hist_val = hist[i] if (i > 0 and i <max): derivative[j] = (hist[i+1] - hist[i-1])/2 j = j +1 return derivative def build_second_derivative(hist): max = 255 derivative = dict(enumerate([0]*(max+1))) j = 0 for i in range(0, max+1): hist_val = hist[i] if (i > 0 and i <max): derivative[j] = hist[i+1] - 2*hist[i] + hist[i-1] j = j +1 return derivative def filtered_hist(h): max = 255 filtered = dict(enumerate([0]*(max+1))) for i in range(0, max+1): if (i==0 or i==max): filtered[i] == 0 else: filtered[i] = statistics.median([h[i-1],h[i], h[i+1]]) return filtered def find_local_max(h): max = 255 local_max = dict(enumerate([0]*(max+1))) j = 0 for i in range(0, max+1): if (i > 0 and i < max): if (h[i+1]==0 and h[i-1]==0): local_max[j] = 0 elif ((h[i-1] == h[i+1] and h[i] >= h[i+1] ) or (h[i-1] < h[i] and h[i+1] < h[i])): local_max[j] = h[i] else: local_max[j] = 0 j = j +1 return local_max def find_regions(h): max = 255 right_index = 0 left_index = 0 for i in range(max,-1,-1): if (h[i]>0): right_index = i; break for i in range(0,(max+1)): if (h[i]>0): left_index = i; break step = int((right_index-left_index)/2) #med1 = statistics.median([h[i] for i in range(left_index+1, left_index+step)]) med1 = statistics.median([h[i] for i in range(left_index, left_index+step) if (h[i] > 0)]) med2 = statistics.median([h[i] for i in range(left_index+step, right_index) if (h[i] > 0)]) medpos1 = [i for i in range(left_index+1, left_index+step) if (h[i] == med1)] medpos2 = [i for i in range(left_index+step, right_index) if (h[i] == med2)] return (left_index, right_index, (med1, medpos1), (med2, medpos2)) def cumul_hist_val(histogram, grey): #print(histogram) cum = 0 for i in range(0, grey): cum = cum + histogram[i] return cum def cumulative_function(histogram): cum_dict = {} for i in range(0,256): cum_dict[i] = cumul_hist_val(histogram,i) return (cum_dict.keys(), cum_dict.values()) def find_equal_regions(h): sum_pix = cumul_hist_val(h, 255) region = sum_pix//7 print("pixel_counter: {0}; region: {1}".format(sum_pix, region)) cum = 0 j = 0 region_grade = [] for i in range(0, 256): cum = cum + h[i] if (cum > region): cum = 0 region_grade.append((i+1)) if (j == 5): break j = j+1 for i in range(0, len(region_grade)): if (i+1==len(region_grade)): avarage = get_region_avarage(region_grade[i], 255) else: avarage = get_region_avarage(region_grade[i], region_grade[i+1]) return region_grade #------------------------------------------------------------------------------------------------------------- # Функции принадлежности к множествам # и функция вывода множест в виде графиков def sigma_left_func(z,params, max_top=1): a,b = params[0], params[1] if (z > a and z < b): y = (1 - (z-a)/(b-a) )*max_top elif (z<= a): y = 1*max_top else: y = 0 return y def trianglural_func(z, params, max_top=1): a,b,c = params[0], params[1], params[2] if (z < b and z >= a): y = (1 - (b-z)/(b-a) )*max_top elif (z >= b and z < c): y = (1 - (z-b)/(c-b) )*max_top else: y = 0 return y def sigma_right_func(z,params, max_top=1): a,b = params[0], params[1] if (z > a and z <= b): y = (1 - (b-z)/(b-a) )*max_top elif (z>= b): y = 1*max_top else: y = 0 return y def plt_member_functions(params, member_vds, max_top=1): max_grade = 256 y = [] #member_params = [0,30,60,80,100,150,229,255] y.append( [sigma_left_func(x, params[0:2], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[0:3], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[1:4], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[2:5], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[3:6], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[4:7], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[5:8], max_top=max_top) for x in range(0,max_grade)] ) y.append( [sigma_right_func(x,params[6:8], max_top=max_top) for x in range(0,max_grade)] ) y_vds = [x*15 for x in range(0,(max_grade-1))] x_vds = [] x_vds.append( [member_vds[0]]*(max_grade-1)) x_vds.append( [member_vds[1]]*(max_grade-1)) x_vds.append( [member_vds[2]]*(max_grade-1)) x_vds.append( [member_vds[3]]*(max_grade-1)) x_vds.append( [member_vds[4]]*(max_grade-1)) x_vds.append( [member_vds[5]]*(max_grade-1)) x_vds.append( [member_vds[6]]*(max_grade-1)) x_vds.append( [member_vds[7]]*(max_grade-1)) x = range(0,max_grade) return plt.plot( x, y[0], x, y[1], x, y[2], x, y[3], x, y[4], x, y[5], x, y[6], x, y[7], x_vds[0], y_vds, x_vds[1], y_vds, x_vds[2], y_vds, x_vds[3], y_vds, x_vds[4], y_vds, x_vds[5], y_vds, x_vds[6], y_vds, x_vds[7], y_vds ) #------------------------------------------------------------------------------------------------------------- # описание формулы на странице 233, Мир цифровой обработки def defuzification(ums, vds ): (a, b) = 0, 0 for i in range(0,len(ums)): a = a + ums[i]*vds[i] b = b + ums[i] v = a/b #print("x:{0}, | a:{1},b:{2} | v:{3};".format(z, a,b,v)) return int(v) def get_defuzzification_list(params, vds): max_grade = 256 defuzz_list = [] for z in range(0, max_grade): ums = [] ums.append(sigma_left_func(z, params[0:2])) ums.append(trianglural_func(z, params[0:3])) ums.append(trianglural_func(z, params[1:4])) ums.append(trianglural_func(z, params[2:5])) ums.append(trianglural_func(z, params[3:6])) ums.append(trianglural_func(z, params[4:7])) ums.append(trianglural_func(z, params[5:8])) ums.append(sigma_right_func(z, params[6:8])) defuzz_list.append(defuzification(ums,vds)) return defuzz_list #------------------------------------------------------------------------------------------------------------- # графики # def show_cdf_func(h): graph = cumulative_function(h) plt.plot(list(graph[0]),list(graph[1]) ) plt.show() def show_cdf_derivative(h): cdf_graph = cumulative_function(h) cdf_dict = dict(zip(cdf_graph[0], cdf_graph[1])) deriv_graph = build_first_derivative(cdf_dict) plt.plot(list(deriv_graph.keys()),list(deriv_graph.values()) ) plt.show() def show_transformation_func(member_params, member_vds ): plt.plot(list(range(0,256)), get_defuzzification_list(member_params, member_vds), list(range(0,256)), list(range(0,256))) plt.show() def show_graphs(graphs, width, height, image_filename_path=""): figure, axs = plt.subplots(height, width, gridspec_kw={'hspace': 0.5, 'wspace': 0.5}, figsize=(30,20)) image_filename = image_filename_path.split("\\")[-1] image_path = "\\".join(image_filename_path.split("\\")[:-1]) i,j = 0,0 for graph in graphs: axs[j,i].bar(graph[0], graph[1]) axs[j,i].set_title("graph {0}, {1}".format(j,i)) i = i+1 if (i>width-1): i = 0 j = j+1 if (image_filename_path): plt.savefig(image_path+"\\processed\\"+image_filename+"_figure.png") else: plt.show() plt.close() def show_graph(graph, member_params, member_vds, image_filename_path=""): max = 255 #plt.figure(figsize=(30, 20)) #plt.cla() #plt.clf() plt.tick_params(axis='both', which='major', labelsize=5) plt.tick_params(axis='both', which='minor', labelsize=8) bar_tiks = [] for i in range(0,max+1): val = list(graph[1])[i] if (val > 0): bar_tiks.append(i) else: bar_tiks.append("") plt.bar(graph[0], graph[1], tick_label=bar_tiks, ) #plt.plot(graph[0], graph[1]) plt_member_functions(member_params, member_vds, max_top=35000) image_filename = image_filename_path.split("\\")[-1] image_path = "\\".join(image_filename_path.split("\\")[:-1]) #plt.xticks(range(0, 256), range(0,256), rotation=90) for i in range(0,max+1): val = list(graph[1])[i] if (val > 0): plt.text(x = i , y = val, s = val, ha='center', va='bottom', size = 5) if (image_filename_path): plt.savefig(image_path+"\\processed\\"+image_filename+"_figure.png") else: plt.show() def show_plot_graph(graph, member_params, member_vds, image_filename_path=""): max = 255 plt.bar(list(graph[0]), list(graph[1]), color=(0.6, 0.4, 0.6, 0.3)) #plt.plot(graph[0], graph[1]) plt_member_functions(member_params, member_vds, max_top=35000) image_filename = image_filename_path.split("\\")[-1] image_path = "\\".join(image_filename_path.split("\\")[:-1]) if (image_filename_path): plt.savefig(image_path+"\\processed\\"+image_filename+"_figure.png") else: plt.show() #----------------------------------------- def get_fuzzy_image(img, params, vds): height, width = img.shape fuzzy_image = np.zeros(shape=[height, width], dtype=np.uint8) fuzzy_list = get_defuzzification_list(params, vds) for i in range(0,width): for j in range(0, height): pixel_val = img[j,i] new_val = fuzzy_list[pixel_val] fuzzy_image[j,i] = new_val return fuzzy_image def fuzzy_process(path, wrt_path): image_filename = path.split("\\")[-1] image_path = "\\".join(path.split("\\")[:-1]) img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) height, width = img.shape # photo 9737 # member_params = [0,10,25,45,75,140,252,255] member_params = [0,5,8,15,56,66,76,255] member_vds = [0,35,70,105,140,175,210,255] fuzzy_image = get_fuzzy_image(img, member_params, member_vds) src_hyst = build_hist(img) fuzz_hyst = build_hist(fuzzy_image) filtered_h = filtered_hist(src_hyst) filtered_fuzzy = filtered_hist(fuzz_hyst) graph_src_hyst = [src_hyst.keys(), src_hyst.values()] graph_fuzz_hyst = [fuzz_hyst.keys(), fuzz_hyst.values()] graph_filtered_hyst = [filtered_h.keys(), filtered_h.values()] graph_fuzz_filtered_hyst = [filtered_fuzzy.keys(), filtered_fuzzy.values()] src_scnd_deriv = build_second_derivative(src_hyst) local_max = find_local_max(src_hyst) local_filt_max = find_local_max(filtered_h) graph_src_maxs = [local_max.keys(), local_max.values()] graph_filt_maxs = [local_filt_max.keys(), local_filt_max.values()] graph_sec_der = [src_scnd_deriv.keys(), src_scnd_deriv.values()] """ show_graphs( [ graph_src_hyst, graph_filtered_hyst, graph_src_maxs, graph_filt_maxs ], width=2, height=2, image_filename_path=path) """ print(find_regions(local_max)) #show_graph(graph_sec_der) cv2.imwrite(wrt_path+image_filename, fuzzy_image) print(find_equal_regions(src_hyst)) #show_cdf_derivative(src_hyst) plt.plot(member_params, [0,0,0,0,0,0,0,0], 'ro') show_cdf_func(src_hyst) show_transformation_func(member_params, member_vds) plt.bar(list(fuzz_hyst.keys()), list(fuzz_hyst.values()),color=(0.2, 0.4, 0.6, 0.3)) plt.bar(list(local_max.keys()), list(local_max.values()),color=(0.6, 0.4, 0.6, 0.7)) show_plot_graph(graph_src_hyst, member_params, member_vds) #show_graph(graph_src_hyst, member_params, member_vds) #show_graph(graph_fuzz_hyst, member_params, member_vds) # def convolution(image_path): img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) height, width = img.shape #------------------------------MAIN----------------------------------------- src_path = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\tif\\fuzzy\\src\\*.tif" wrt_path = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\tif\\fuzzy\\processed\\" images = glob.glob(src_path) img_amount = len(images) img_counter = 0 for image in images: img_counter = img_counter + 1 #print("{0} of {1}".format(img_counter, img_amount)) convolution(image, wrt_path) #concat_images = np.concatenate( (my_resize(img4,50), my_resize(img4, 50)), axis=1) #cv2.imshow('modified_image',concat_images ) #my_subplots(img4, img4) gc.collect() cv2.waitKey(0) cv2.destroyAllWindows() <file_sep>/combine_images.py import matplotlib import matplotlib.pyplot as plt import numpy as np import PIL import glob def combine_images(image_path, figures_path, write_path): image_filename = image_path.split("\\")[-1] imgs = [] imgs.append(PIL.Image.open(image_path).convert('LA')) imgs.append(PIL.Image.open(figures_path+image_filename+"_figure.png").convert('LA')) # pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here) min_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1] imgs_comb = np.hstack( [np.asarray( i.resize(min_shape) ) for i in imgs ] ) # save that beautiful picture imgs_comb = PIL.Image.fromarray( imgs_comb) imgs_comb.save( write_path+image_filename+"_combined.png" ) # for a vertical stacking it is simple: use vstack #imgs_comb = np.vstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) ) #imgs_comb = PIL.Image.fromarray( imgs_comb) #imgs_comb.save( 'Trifecta_vertical.jpg' ) #------------------------------MAIN----------------------------------------- images = glob.glob("D:\\resilio\\ip_lib_ed\\src_images\\dslr\\video\\M11-2231\\tiff\\processed\\images\\*.tif") figures = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\video\\M11-2231\\tiff\\processed\\figures\\" write_path = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\video\\M11-2231\\tiff\\processed\\combined\\" img_amount = len(images) img_counter = 0 for image_path in images: img_counter = img_counter + 1 print("{0} of {1}".format(img_counter, img_amount)) combine_images(image_path=image_path, figures_path=figures, write_path=write_path) print("DONE!") #concat_images = np.concatenate( (my_resize(img4,50), my_resize(img4, 50)), axis=1) #cv2.imshow('modified_image',concat_images ) #my_subplots(img4, img4) <file_sep>/fuzzy_processing_v3.py import matplotlib import matplotlib.pyplot as plt import numpy as np import cv2, itertools import gc import glob import statistics import random import collections #------------------------------------------------------------------------------------------------------------- # Операции с гистограммой BIT_DEPTH = 8 BIT_DEPTH_MAX_VALUE = 2**BIT_DEPTH def build_hist(img): height, width = img.shape hist = dict(enumerate([0]*256)) for j in range(0,height): for i in range(0, width): pixel_val = int(img[j,i]) #print("pix_val:",pixel_val) hist[pixel_val] = hist[pixel_val]+1 return hist def cumul_hist_val(histogram, grey): #print(histogram) cum = 0 for i in range(0, grey): cum = cum + histogram[i] return cum def cumulative_function(histogram): cum_dict = {} for i in range(0,256): cum_dict[i] = cumul_hist_val(histogram,i) return (cum_dict.keys(), cum_dict.values()) def analyze_histogram(h, member_vds): total_pixels = cumul_hist_val(h, BIT_DEPTH_MAX_VALUE-1 ) # я не считаю крайние правила слева и справа по одному rights = len(member_vds)-2 pixels_per_right = total_pixels//rights h_values = list(h.values()) pixels_per_region = {} for i in range(0, len(member_vds)-1): start = member_vds[i] end = member_vds[i+1] region_pixels = 0 for el in h_values[start:end]: region_pixels = region_pixels + el #pixels_per_region.append({i:region_pixels, round(region_pixels/pixels_per_right, 2)]}) pixels_per_region[(i, start,end, round(region_pixels/pixels_per_right, 2))] = region_pixels pixels_per_region = {k: v for k, v in sorted(pixels_per_region.items(), key=lambda item: item[1], reverse=True)} print("pixels_per_region: \t",pixels_per_region) dots = 0 result = {} for key in pixels_per_region: points = pixels_per_region[key]//pixels_per_right #points = round(pixels_per_region[key]/pixels_per_right) if (points == 0 ): points = 1 if (dots+points <= 6): dots = dots + points result[key] = [pixels_per_region[key], points] return result def get_member_params(h, region_stat, member_vds): h_values = list(h.values()) borders = histogram_borders(h, member_vds) result = [borders[0]] for key in region_stat: keys = list(region_stat.keys()) start = key[1] end = key[2] region_points = region_stat[key][1] if (key==keys[0] and start==0): start = borders[0] if (key==keys[-1] and end==255): end = borders[1] #result = result + random.choices(range(start,end), k=region_stat[key][1]) # maxs = list(maximums(h, maximums_count=region_stat[key][1], start=start, end=end).values()) maxs = [] dist = (end-start)//(region_points+1) for i in range(1, region_points+1 ): maxs.append(start+dist*i) print("maxs: \t",maxs) result = result + maxs result.append(borders[1]) return sorted(result) def build_first_derivative(hist): bit_depth = len(list(hist.keys())) #256 к примеру derivative = dict(enumerate([0]*(bit_depth))) j = 0 for i in range(0, bit_depth): hist_val = hist[i] if (i > 0 and i < (bit_depth-1) ): derivative[j] = (hist[i+1] - hist[i-1])/2 j = j +1 return derivative def get_derivative_maxs(derivative_histogram): h = derivative_histogram bit_depth = len(list(h.keys())) #256 к примеру derivative = dict(enumerate([0]*(bit_depth))) maxs = [] for i in range(1, bit_depth): if (h[i] < 0 and h[i-1] >= 0): maxs.append(i-1) return maxs def get_median_histogram(h): bit_depth = len(list(h.keys())) #256 к примеру filtered = dict(enumerate([0]*(bit_depth))) for i in range(0, bit_depth): if (i < 3): if (i==0): filtered[i] = h[0] elif (i==1): filtered[i] = h[1] elif (i==2): filtered[i] = statistics.median([ h[i-2], h[i-1], h[i] ]) else: filtered[i] = statistics.median([ h[i-3], h[i-2], h[i-1], h[i] ]) return filtered def maximums(graph, maximums_count=0, start=0, end=255): # данный метод позволяет найти максимумы на графике # и выбрать из него только необходимое количество из # всех максимумов. При этом максимумы выбираются начиная # с самых больших значений. maximums = {} previous = 0 #print("start, end: ", start, end) for i in range(start+1, end): current = graph[i] - graph[i-1] #print("graph[",i,"]:", graph[i]) #print(current) if (current < 0 and previous > 0): maximums[i-1] = graph[i-1] previous = current # После того, как мы нашли максимумы, мы должны упорядичить эти # максимумы в порядке убывания, после чего выбрать только необходимое нам количество, # определенное в переменной maximums_count maximums = {k: v for k, v in sorted(maximums.items(), key=lambda item: item[1], reverse=True)} if (maximums_count): maximums = dict(itertools.islice(maximums.items(),maximums_count)) maximums = dict(sorted(maximums.items())) return maximums def region_max_value(h, start, end): h_values = list(h.values())[start:end] max_value = max(h_values) max_index = start + h_values.index(max_value) return max_index def find_local_max(h): max = 255 local_max = dict(enumerate([0]*(max+1))) j = 0 for i in range(0, max+1): if (i > 0 and i < max): if (h[i+1]==0 and h[i-1]==0): local_max[j] = 0 elif ((h[i-1] == h[i+1] and h[i] >= h[i+1] ) or (h[i-1] < h[i] and h[i+1] < h[i])): local_max[j] = h[i] else: local_max[j] = 0 j = j +1 return local_max def histogram_borders(h, member_vds): keys = list(h.keys()) for el in h: if (h[el]>20): left = el break for el in reversed(keys): if (h[el]>20): right = el break if (right < member_vds[1]): right = member_vds[1] if (left > member_vds[-2]): left = member_vds[-2] return (left, right) def calculate_median(l): l = sorted(l) l_len = len(l) return l[(l_len)//2] def find_equal_regions(h): # данная штука делит количество всех пикселей на 7. # и находит те области гистограммы, где содержится 1/7 часть # все пикселей. Цель - разрядить гистограмму таким образом, # посредством смещения в ту или иную сторону. sum_pix = cumul_hist_val(h, BIT_DEPTH_MAX_VALUE-1 ) region = sum_pix//6 print("pixel_counter: {0} pixels in image; 1/6 part of pixels: {1}".format(sum_pix, region)) cum = 0 j = 0 region_grade = [] previos_val = 0 for i in range(0, BIT_DEPTH_MAX_VALUE): cum = cum + h[i] #print("cum=",cum) if (cum >= region): cum = 0 region_grade.append([previos_val, i-1]) previos_val = i-1 if (j == 4): region_grade.append([previos_val, 255]) j = j+1 return region_grade #------------------------------------------------------------------------------------------------------------- # Функции принадлежности к множествам # и функция вывода множест в виде графиков def sigma_left_func(z,params, max_top=1): a,b = params[0], params[1] if (z > a and z < b): y = (1 - (z-a)/(b-a) )*max_top elif (z<= a): y = 1*max_top else: y = 0 return y def trianglural_func(z, params, max_top=1): a,b,c = params[0], params[1], params[2] if (z < b and z >= a): y = (1 - (b-z)/(b-a) )*max_top elif (z >= b and z < c): y = (1 - (z-b)/(c-b) )*max_top else: y = 0 return y def sigma_right_func(z,params, max_top=1): a,b = params[0], params[1] if (z > a and z <= b): y = (1 - (b-z)/(b-a) )*max_top elif (z>= b): y = 1*max_top else: y = 0 return y def plt_member_functions(params, member_vds, max_top=1): max_grade = 256 y = [] #member_params = [0,30,60,80,100,150,229,255] y.append( [sigma_left_func(x, params[0:2], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[0:3], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[1:4], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[2:5], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[3:6], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[4:7], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[5:8], max_top=max_top) for x in range(0,max_grade)] ) y.append( [sigma_right_func(x,params[6:8], max_top=max_top) for x in range(0,max_grade)] ) y_vds = [x*15 for x in range(0,(max_grade-1))] x_vds = [] x_vds.append( [member_vds[0]]*(max_grade-1)) x_vds.append( [member_vds[1]]*(max_grade-1)) x_vds.append( [member_vds[2]]*(max_grade-1)) x_vds.append( [member_vds[3]]*(max_grade-1)) x_vds.append( [member_vds[4]]*(max_grade-1)) x_vds.append( [member_vds[5]]*(max_grade-1)) x_vds.append( [member_vds[6]]*(max_grade-1)) x_vds.append( [member_vds[7]]*(max_grade-1)) x = range(0,max_grade) return plt.plot( #x, y[0], x, y[1], x, y[2], x, y[3], x, y[4], x, y[5], x, y[6], x, y[7], x_vds[0], y_vds, x_vds[1], y_vds, x_vds[2], y_vds, x_vds[3], y_vds, x_vds[4], y_vds, x_vds[5], y_vds, x_vds[6], y_vds, x_vds[7], y_vds ) #------------------------------------------------------------------------------------------------------------- # описание формулы на странице 233, Мир цифровой обработки def defuzification(ums, vds ): (a, b) = 0, 0 for i in range(0,len(ums)): a = a + ums[i]*vds[i] b = b + ums[i] v = a/b #print("x:{0}, | a:{1},b:{2} | v:{3};".format(z, a,b,v)) return int(v) def get_defuzzification_list(params, vds): max_grade = 256 defuzz_list = [] for z in range(0, max_grade): ums = [] ums.append(sigma_left_func(z, params[0:2])) ums.append(trianglural_func(z, params[0:3])) ums.append(trianglural_func(z, params[1:4])) ums.append(trianglural_func(z, params[2:5])) ums.append(trianglural_func(z, params[3:6])) ums.append(trianglural_func(z, params[4:7])) ums.append(trianglural_func(z, params[5:8])) ums.append(sigma_right_func(z, params[6:8])) defuzz_list.append(defuzification(ums,vds)) return defuzz_list #------------------------------------------------------------------------------------------------------------- # графики # def show_cdf_func(h): graph = cumulative_function(h) plt.plot(list(graph[0]),list(graph[1]) ) plt.show() def show_cdf_derivative(h): cdf_graph = cumulative_function(h) cdf_dict = dict(zip(cdf_graph[0], cdf_graph[1])) deriv_graph = build_first_derivative(cdf_dict) plt.plot(list(deriv_graph.keys()),list(deriv_graph.values()) ) plt.show() def show_transformation_func(member_params, member_vds ): plt.plot(list(range(0,256)), get_defuzzification_list(member_params, member_vds), list(range(0,256)), list(range(0,256))) plt.show() def show_first_derivative(h): plt.bar(list(h.keys()), list(h.values())) #plt.show() def show_graphs(graphs, width, height, image_filename_path=""): figure, axs = plt.subplots(height, width, gridspec_kw={'hspace': 0.5, 'wspace': 0.5}, figsize=(30,20)) image_filename = image_filename_path.split("\\")[-1] image_path = "\\".join(image_filename_path.split("\\")[:-1]) i,j = 0,0 for graph in graphs: axs[j,i].bar(graph[0], graph[1]) axs[j,i].set_title("graph {0}, {1}".format(j,i)) i = i+1 if (i>width-1): i = 0 j = j+1 if (image_filename_path): plt.savefig(image_path+"\\processed\\"+image_filename+"_figure.png") else: plt.show() plt.close() def show_graph(graph, member_params, member_vds, image_filename_path=""): max = 255 #plt.figure(figsize=(30, 20)) #plt.cla() #plt.clf() plt.tick_params(axis='both', which='major', labelsize=5) plt.tick_params(axis='both', which='minor', labelsize=8) bar_tiks = [] for i in range(0,max+1): val = list(graph[1])[i] if (val > 0): bar_tiks.append(i) else: bar_tiks.append("") plt.bar(graph[0], graph[1], tick_label=bar_tiks, ) #plt.plot(graph[0], graph[1]) plt_member_functions(member_params, member_vds, max_top=35000) image_filename = image_filename_path.split("\\")[-1] image_path = "\\".join(image_filename_path.split("\\")[:-1]) #plt.xticks(range(0, 256), range(0,256), rotation=90) for i in range(0,max+1): val = list(graph[1])[i] if (val > 0): plt.text(x = i , y = val, s = val, ha='center', va='bottom', size = 5) if (image_filename_path): plt.savefig(image_path+"\\processed\\"+image_filename+"_figure.png") else: plt.show() def show_plot_graph(graph, member_params, member_vds, equal_regions, image_filename_path=""): max = 255 #equal_regions = [0] + equal_regions + [255] colors = [ (1, 0, 0, 0.4), (0, 0, 1, 0.4), (0, 1, 0, 0.4) , (0, 1, 1, 0.4), (1, 1, 0, 0.4), (1, 0, 1, 0.4), (0, 1, 0.5, 0.4), (1, 0, 0.5, 0.4) ] # каждый кусок 1/6 части гистограммы нам нужно расскрасить for region in equal_regions: position = equal_regions.index(region) start = region[0] end = region[1] x = list(graph[0])[start:end] y = list(graph[1])[start:end] plt.bar(x, y, color=colors[position]) #plt.bar(list(graph[0]), list(graph[1]),color=colors[7] ) plt_member_functions(member_params, member_vds, max_top=35000) image_filename = image_filename_path.split("\\")[-1] image_path = "\\".join(image_filename_path.split("\\")[:-1]) if (image_filename_path): plt.savefig(image_path+"\\processed\\"+image_filename+"_figure.png") else: plt.show() #----------------------------------------- def get_fuzzy_image(img, params, vds): height, width = img.shape fuzzy_image = np.zeros(shape=[height, width], dtype=np.uint8) fuzzy_list = get_defuzzification_list(params, vds) for i in range(0,width): for j in range(0, height): pixel_val = img[j,i] new_val = fuzzy_list[pixel_val] fuzzy_image[j,i] = new_val return fuzzy_image def apply_lut(img,): height, width = img.shape colored_image = np.zeros(shape=[height, width, 3], dtype=np.uint8) for i in range(0,width): for j in range(0, height): pixel_val = img[j,i] if (pixel_val < 200): new_val = [0,0, pixel_val] else: new_val = [pixel_val,pixel_val, pixel_val] colored_image[j,i] = new_val return colored_image def image_statisctic(h): # делим картинку на 8 частей # в каждой из частей определяем - какое количество # пикселей там присутсвует. Если в левой части гистограммы большое скопление - # картинка темная, иначе - светлая. # Если в каждой части примерно равное количество - картинка выровненная. # Если большая часть в середине - то картинка не контрастная - необходимо немного # переместить пиксели влево и вправо, чтобы добиться небольшого контраста. sum_pix = cumul_hist_val(h, BIT_DEPTH_MAX_VALUE-1 ) region = BIT_DEPTH_MAX_VALUE//8 regions = [[j*region, region*j+region] for j in range(0,8)] pixels = [] h_values = list(h.values()) for region in regions: start = region[0] end = region[1] pix_region = sum(h_values[start:end]) perc_region = int((pix_region/sum_pix)*100) pixels.append([pix_region, perc_region]) left_part = pixels[0][1]+pixels[1][1]+pixels[2][1]+pixels[3][1] dark_part = pixels[0][1]+pixels[1][1] darkest_part = pixels[0][1] right_part = pixels[4][1]+pixels[5][1]+pixels[6][1]+pixels[7][1] light_part = pixels[6][1]+pixels[7][1] lightest_part = pixels[7][1] print("left_part: ",left_part) print("dark_part: ",dark_part) print("darkest_part: ",darkest_part) if (left_part > 70 ): answer = "картинка темная" if (dark_part > left_part//2): answer = "картинка темноватая" if (darkest_part > dark_part//2): answer = "картинка оч темная" elif (right_part > 70 ): answer = "картинка светлая" if (light_part > right_part//2): answer = "картинка светловатая" if (lightest_part > light_part//2): answer = "картинка оч светлая" else: answer = "картинка нормас" print("********************** STATISTICS **********************") print("pixels in regions: {0} \t".format(pixels)) print("quality: {0} \t".format(answer)) def fuzzy_process(path, wrt_path): image_filename = path.split("\\")[-1] image_path = "\\".join(path.split("\\")[:-1]) img = cv2.imread(path, 0) height, width = img.shape src_hyst = build_hist(img) median_histogram = get_median_histogram(src_hyst) median_first_derivative = build_first_derivative(median_histogram) derivative_maxs = get_derivative_maxs(median_first_derivative) target_histogram = median_histogram equal_regions = find_equal_regions(src_hyst) all_maxs = maximums(src_hyst) choosen_maxs = list(all_maxs.keys())[0:4] #print("src_hyst: \t", src_hyst) # # print("median_histogram: \t", median_histogram) #print("all_maxs: \t", all_maxs) print("derivative_maxs: \t", derivative_maxs) print("equal_regions: \t", equal_regions) print("choosen maxs: \t", choosen_maxs) #member_vds = [0,25,50,85,120,155,190,235] #member_vds = [0,35,70,105,140,175,210,255] #left member_vds = [0,35,70,105,140,175,210,255] # right #member_vds = [0,55,105,135,170,210,235,255] region_stat = analyze_histogram(src_hyst, member_vds) member_params = get_member_params(src_hyst,region_stat, member_vds) #member_params = [borders[0]] + [5,7, 13, 22,36,80]+ [borders[1]] print("memeber params: \t", member_params) print("region_stat: \t", region_stat) member_params = [24, 50,80,115,140,175,205,255] fuzzy_image = get_fuzzy_image(img, member_params, member_vds) fuzz_hyst = build_hist(fuzzy_image) graph_target_hist = [target_histogram.keys(), target_histogram.values()] #local_max = find_local_max(src_hyst) cv2.imwrite(wrt_path+image_filename, fuzzy_image) """ colored_image = apply_lut(img) cv2.imwrite(wrt_path+"lut_"+image_filename, colored_image) """ #статистика image_statisctic(src_hyst) #графики plt.bar(list(src_hyst.keys()), list(src_hyst.values()), color=(0, 0, 1, 0.6)) plt.bar(list(fuzz_hyst.keys()), list(fuzz_hyst.values()), color=(1, 0, 0, 0.6)) plt.show() plt.plot(member_params, [0,0,0,0,0,0,0,0], 'ro') #show_cdf_func(src_hyst) #show_transformation_func(member_params, member_vds) #show_first_derivative(median_first_derivative) plt.bar(list(fuzz_hyst.keys()), list(fuzz_hyst.values()),color=(0.2, 0.4, 0.6, 0.3)) show_plot_graph(graph_target_hist, member_params, member_vds, equal_regions) # #------------------------------MAIN----------------------------------------- src_path = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\tif\\fuzzy\\src\\*.*" wrt_path = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\tif\\fuzzy\\processed\\" images = glob.glob(src_path) img_amount = len(images) img_counter = 0 for image in images: img_counter = img_counter + 1 #print("{0} of {1}".format(img_counter, img_amount)) fuzzy_process(image, wrt_path) #concat_images = np.concatenate( (my_resize(img4,50), my_resize(img4, 50)), axis=1) #cv2.imshow('modified_image',concat_images ) #my_subplots(img4, img4) gc.collect() cv2.waitKey(0) cv2.destroyAllWindows() <file_sep>/fuzzy_processing_v2.py import matplotlib import matplotlib.pyplot as plt import numpy as np import cv2, itertools import gc import glob import statistics #------------------------------------------------------------------------------------------------------------- # Операции с гистограммой def build_hist(img): height, width = img.shape hist = dict(enumerate([0]*256)) for j in range(0,height): for i in range(0, width): pixel_val = int(img[j,i]) #print("pix_val:",pixel_val) hist[pixel_val] = hist[pixel_val]+1 return hist def build_first_derivative(hist): max = 255 derivative = dict(enumerate([0]*(max+1))) j = 0 for i in range(0, max+1): hist_val = hist[i] if (i > 0 and i <max): derivative[j] = (hist[i+1] - hist[i-1])/2 j = j +1 return derivative def build_second_derivative(hist): max = 255 derivative = dict(enumerate([0]*(max+1))) j = 0 for i in range(0, max+1): hist_val = hist[i] if (i > 0 and i <max): derivative[j] = hist[i+1] - 2*hist[i] + hist[i-1] j = j +1 return derivative def filtered_hist(h): max = 255 filtered = dict(enumerate([0]*(max+1))) for i in range(0, max+1): if (i==0 or i==max): filtered[i] == 0 else: filtered[i] = statistics.median([h[i-1],h[i], h[i+1]]) return filtered def find_local_max(h): max = 255 local_max = dict(enumerate([0]*(max+1))) j = 0 for i in range(0, max+1): if (i > 0 and i < max): if (h[i+1]==0 and h[i-1]==0): local_max[j] = 0 elif ((h[i-1] == h[i+1] and h[i] >= h[i+1] ) or (h[i-1] < h[i] and h[i+1] < h[i])): local_max[j] = h[i] else: local_max[j] = 0 j = j +1 return local_max def find_regions(h): max = 255 right_index = 0 left_index = 0 for i in range(max,-1,-1): if (h[i]>0): right_index = i; break for i in range(0,(max+1)): if (h[i]>0): left_index = i; break step = int((right_index-left_index)/2) #med1 = statistics.median([h[i] for i in range(left_index+1, left_index+step)]) med1 = statistics.median([h[i] for i in range(left_index, left_index+step) if (h[i] > 0)]) med2 = statistics.median([h[i] for i in range(left_index+step, right_index) if (h[i] > 0)]) medpos1 = [i for i in range(left_index+1, left_index+step) if (h[i] == med1)] medpos2 = [i for i in range(left_index+step, right_index) if (h[i] == med2)] return (left_index, right_index, (med1, medpos1), (med2, medpos2)) def cumul_hist_val(histogram, grey): #print(histogram) cum = 0 for i in range(0, grey): cum = cum + histogram[i] return cum def cumulative_function(histogram): cum_dict = {} for i in range(0,256): cum_dict[i] = cumul_hist_val(histogram,i) return (cum_dict.keys(), cum_dict.values()) def find_equal_regions(h): # данная штука делит количество всех пикселей на 7. # и находит те области гистограммы, где содержится 1/7 часть # все пикселей. Цель - разрядить гистограмму таким образом, # посредством смещения в ту или иную сторону. sum_pix = cumul_hist_val(h, 255) region = sum_pix//7 print("pixel_counter: {0} pixels in image; 1/7 part of pixels: {1}".format(sum_pix, region)) cum = 0 j = 0 region_grade = [] for i in range(0, 256): cum = cum + h[i] print("cum=",cum) if (cum >= region): cum = 0 region_grade.append((i+1)) print("i+1=",i+1, "j=", j) if (j == 5): break j = j+1 return region_grade def histogram_rois(equal_regions): l = equal_regions new = [0] # Цель этой функции определить - на какой из областей гистограммы # нам необходимо искать скопления пикселей, чтобы переместить их # в другую часть изображения, если это необходимо for i in range(0, len(l)-1): new.append(l[i] + (l[i+1] - l[i])//2 ) new.append(255) return new def maximums(graph, maximums_count, start=0, end=255): # данный метод позволяет найти максимумы на графике # и выбрать из него только необходимое количество из # всех максимумов. При этом максимумы выбираются начиная # с самых больших значений. maximums = {} previous = 0 #print("start, end: ", start, end) for i in range(start+1, end): current = graph[i] - graph[i-1] #print("graph[",i,"]:", graph[i]) #print(current) if (current < 0 and previous > 0): maximums[i-1] = graph[i-1] previous = current # После того, как мы нашли максимумы, мы должны упорядичить эти # максимумы в порядке убывания, после чего выбрать только необходимое нам количество, # определенное в переменной maximums_count maximums = {k: v for k, v in sorted(maximums.items(), key=lambda item: item[1], reverse=True)} maximums = dict(itertools.islice(maximums.items(),maximums_count)) maximums = dict(sorted(maximums.items())) return maximums def region_max_value(h, start, end): h_values = list(h.values())[start:end] max_value = max(h_values) max_index = start + h_values.index(max_value) return max_index def histogram_borders(h): keys = list(h.keys()) for el in h: if (h[el]>5): left = el break for el in reversed(keys): if (h[el]>5): right = el break return (left, right) def maximums_in_rois(histogram, histogram_rois, equal_regions): # находит максимумы в тех областях гистограммы, которые # определены как регионы интереса # это необходимо для того, чтобы определить пики в этих регионах # для их перемещения в нужную нам область l = histogram_rois result = [] for i in range(1, len(l)): start = l[i-1] end = l[i] max_list = maximums(histogram, 1, start, end) region_max = region_max_value(histogram, start, end) if (len(max_list)==0): max_list = equal_regions[i-1] else: max_list = list(max_list.keys())[0] result.append([start, end, region_max]) return result def calculate_median(l): l = sorted(l) l_len = len(l) return l[(l_len)//2] def avarage_in_rois(histogram, rois_maxs): # цель - найти среднее значение в регионе интереса # и двигать его в нужное значение. h = list(histogram.values()) rois_av = [] for roi in rois_maxs: start = roi[0] end = roi[1] filtered = [el for el in h[start:end] if el > 200] if (len(filtered)==0): result = max(h[start:end]) else: result = calculate_median(filtered) #print(h[start:end], median) indx = h.index(result) rois_av.append([start, end, indx]) return rois_av #------------------------------------------------------------------------------------------------------------- # Функции принадлежности к множествам # и функция вывода множест в виде графиков def sigma_left_func(z,params, max_top=1): a,b = params[0], params[1] if (z > a and z < b): y = (1 - (z-a)/(b-a) )*max_top elif (z<= a): y = 1*max_top else: y = 0 return y def trianglural_func(z, params, max_top=1): a,b,c = params[0], params[1], params[2] if (z < b and z >= a): y = (1 - (b-z)/(b-a) )*max_top elif (z >= b and z < c): y = (1 - (z-b)/(c-b) )*max_top else: y = 0 return y def sigma_right_func(z,params, max_top=1): a,b = params[0], params[1] if (z > a and z <= b): y = (1 - (b-z)/(b-a) )*max_top elif (z>= b): y = 1*max_top else: y = 0 return y def plt_member_functions(params, member_vds, max_top=1): max_grade = 256 y = [] #member_params = [0,30,60,80,100,150,229,255] y.append( [sigma_left_func(x, params[0:2], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[0:3], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[1:4], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[2:5], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[3:6], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[4:7], max_top=max_top) for x in range(0,max_grade)] ) y.append( [trianglural_func(x,params[5:8], max_top=max_top) for x in range(0,max_grade)] ) y.append( [sigma_right_func(x,params[6:8], max_top=max_top) for x in range(0,max_grade)] ) y_vds = [x*15 for x in range(0,(max_grade-1))] x_vds = [] x_vds.append( [member_vds[0]]*(max_grade-1)) x_vds.append( [member_vds[1]]*(max_grade-1)) x_vds.append( [member_vds[2]]*(max_grade-1)) x_vds.append( [member_vds[3]]*(max_grade-1)) x_vds.append( [member_vds[4]]*(max_grade-1)) x_vds.append( [member_vds[5]]*(max_grade-1)) x_vds.append( [member_vds[6]]*(max_grade-1)) x_vds.append( [member_vds[7]]*(max_grade-1)) x = range(0,max_grade) return plt.plot( x, y[0], x, y[1], x, y[2], x, y[3], x, y[4], x, y[5], x, y[6], x, y[7], x_vds[0], y_vds, x_vds[1], y_vds, x_vds[2], y_vds, x_vds[3], y_vds, x_vds[4], y_vds, x_vds[5], y_vds, x_vds[6], y_vds, x_vds[7], y_vds ) #------------------------------------------------------------------------------------------------------------- # описание формулы на странице 233, Мир цифровой обработки def defuzification(ums, vds ): (a, b) = 0, 0 for i in range(0,len(ums)): a = a + ums[i]*vds[i] b = b + ums[i] v = a/b #print("x:{0}, | a:{1},b:{2} | v:{3};".format(z, a,b,v)) return int(v) def get_defuzzification_list(params, vds): max_grade = 256 defuzz_list = [] for z in range(0, max_grade): ums = [] ums.append(sigma_left_func(z, params[0:2])) ums.append(trianglural_func(z, params[0:3])) ums.append(trianglural_func(z, params[1:4])) ums.append(trianglural_func(z, params[2:5])) ums.append(trianglural_func(z, params[3:6])) ums.append(trianglural_func(z, params[4:7])) ums.append(trianglural_func(z, params[5:8])) ums.append(sigma_right_func(z, params[6:8])) defuzz_list.append(defuzification(ums,vds)) return defuzz_list #------------------------------------------------------------------------------------------------------------- # графики # def show_cdf_func(h): graph = cumulative_function(h) plt.plot(list(graph[0]),list(graph[1]) ) plt.show() def show_cdf_derivative(h): cdf_graph = cumulative_function(h) cdf_dict = dict(zip(cdf_graph[0], cdf_graph[1])) deriv_graph = build_first_derivative(cdf_dict) plt.plot(list(deriv_graph.keys()),list(deriv_graph.values()) ) plt.show() def show_transformation_func(member_params, member_vds ): plt.plot(list(range(0,256)), get_defuzzification_list(member_params, member_vds), list(range(0,256)), list(range(0,256))) plt.show() def show_graphs(graphs, width, height, image_filename_path=""): figure, axs = plt.subplots(height, width, gridspec_kw={'hspace': 0.5, 'wspace': 0.5}, figsize=(30,20)) image_filename = image_filename_path.split("\\")[-1] image_path = "\\".join(image_filename_path.split("\\")[:-1]) i,j = 0,0 for graph in graphs: axs[j,i].bar(graph[0], graph[1]) axs[j,i].set_title("graph {0}, {1}".format(j,i)) i = i+1 if (i>width-1): i = 0 j = j+1 if (image_filename_path): plt.savefig(image_path+"\\processed\\"+image_filename+"_figure.png") else: plt.show() plt.close() def show_graph(graph, member_params, member_vds, image_filename_path=""): max = 255 #plt.figure(figsize=(30, 20)) #plt.cla() #plt.clf() plt.tick_params(axis='both', which='major', labelsize=5) plt.tick_params(axis='both', which='minor', labelsize=8) bar_tiks = [] for i in range(0,max+1): val = list(graph[1])[i] if (val > 0): bar_tiks.append(i) else: bar_tiks.append("") plt.bar(graph[0], graph[1], tick_label=bar_tiks, ) #plt.plot(graph[0], graph[1]) plt_member_functions(member_params, member_vds, max_top=35000) image_filename = image_filename_path.split("\\")[-1] image_path = "\\".join(image_filename_path.split("\\")[:-1]) #plt.xticks(range(0, 256), range(0,256), rotation=90) for i in range(0,max+1): val = list(graph[1])[i] if (val > 0): plt.text(x = i , y = val, s = val, ha='center', va='bottom', size = 5) if (image_filename_path): plt.savefig(image_path+"\\processed\\"+image_filename+"_figure.png") else: plt.show() def show_plot_graph(graph, member_params, member_vds, equal_regions, image_filename_path=""): max = 255 equal_regions = [0] + equal_regions + [255] colors = [ (1, 0, 0, 0.4), (0, 0, 1, 0.4), (0, 1, 0, 0.4) , (0, 1, 1, 0.4), (1, 1, 0, 0.4), (1, 0, 1, 0.4), (0, 1, 0.5, 0.4), (1, 0, 0.5, 0.4) ] # каждый кусок 1/7 части гистограммы нам нужно расскрасить for i in range(0, len(equal_regions)): start = equal_regions[i-1] end = equal_regions[i] x = list(graph[0])[start:end] y = list(graph[1])[start:end] plt.bar(x, y, color=colors[i-1]) #plt.plot(graph[0], graph[1]) plt_member_functions(member_params, member_vds, max_top=35000) image_filename = image_filename_path.split("\\")[-1] image_path = "\\".join(image_filename_path.split("\\")[:-1]) if (image_filename_path): plt.savefig(image_path+"\\processed\\"+image_filename+"_figure.png") else: plt.show() plt.clf() #----------------------------------------- def get_fuzzy_image(img, params, vds): height, width = img.shape fuzzy_image = np.zeros(shape=[height, width], dtype=np.uint8) fuzzy_list = get_defuzzification_list(params, vds) for i in range(0,width): for j in range(0, height): pixel_val = img[j,i] new_val = fuzzy_list[pixel_val] fuzzy_image[j,i] = new_val return fuzzy_image def fuzzy_process(path, wrt_path): image_filename = path.split("\\")[-1] image_path = "\\".join(path.split("\\")[:-1]) img = cv2.imread(path, 0) height, width = img.shape src_hyst = build_hist(img) filtered_h = filtered_hist(src_hyst) target_histogram = src_hyst #fuzzzyyyyyyyyy borders = histogram_borders(target_histogram) print("BORDERS: ", borders) maxs = maximums(target_histogram,6) print("Local max list: \t",maxs) equal_regions = find_equal_regions(target_histogram) print("Equal regions is: \t",equal_regions) h_rois = histogram_rois(equal_regions) print("histogram_rois: \t", h_rois) rois_maxs = maximums_in_rois(target_histogram, h_rois, equal_regions) print("rois_maxs: \t", rois_maxs) rois_av = avarage_in_rois(target_histogram, rois_maxs) print("rois_av: \t", rois_av) # photo 9737 # member_params = [0,10,25,45,75,140,252,255] # member_params = [0,5,8,15,56,66,76,255] member_params = [i[2] for i in rois_av] member_params.insert(0, borders[0]) member_params.append(borders[1]) #member_params = [0, 7, 13, 33, 47, 60, 90, 255] print("memeber params: \t", member_params) #member_params = [7, 17, 70, 86, 99, 115, 140, 255] #member_params = [0,6,14,20,56,65,84,255] # this number's list is working properly on 9752 image # member_params = [0,5,8,15,56,66,76,255] # member_vds = [0,35,70,105,140,175,210,255] member_vds = [0,35,70,105,140,175,210,255] print("member_vds: \t", member_vds) fuzzy_image = get_fuzzy_image(img, member_params, member_vds) fuzz_hyst = build_hist(fuzzy_image) #filtered_h = filtered_hist(src_hyst) #filtered_fuzzy = filtered_hist(fuzz_hyst) graph_src_hyst = [src_hyst.keys(), src_hyst.values()] graph_fuzz_hyst = [fuzz_hyst.keys(), fuzz_hyst.values()] graph_filtered_hyst = [filtered_h.keys(), filtered_h.values()] graph_target_hist = [target_histogram.keys(), target_histogram.values()] #graph_fuzz_filtered_hyst = [filtered_fuzzy.keys(), filtered_fuzzy.values()] #src_scnd_deriv = build_second_derivative(src_hyst) local_max = find_local_max(src_hyst) #local_filt_max = find_local_max(filtered_h) graph_src_maxs = [local_max.keys(), local_max.values()] #graph_filt_maxs = [local_filt_max.keys(), local_filt_max.values()] #graph_sec_der = [src_scnd_deriv.keys(), src_scnd_deriv.values()] """ show_graphs( [ graph_src_hyst, graph_filtered_hyst, graph_src_maxs, graph_filt_maxs ], width=2, height=2, image_filename_path=path) """ cv2.imwrite(wrt_path+image_filename, fuzzy_image) #графики # plt.plot(member_params, [0,0,0,0,0,0,0,0], 'ro') # show_cdf_func(src_hyst) # show_transformation_func(member_params, member_vds) # plt.bar(list(fuzz_hyst.keys()), list(fuzz_hyst.values()),color=(0.2, 0.4, 0.6, 0.3)) # plt.bar(list(local_max.keys()), list(local_max.values()),color=(0.6, 0.4, 0.6, 0.7)) # show_plot_graph(graph_target_hist, member_params, member_vds, equal_regions) # #------------------------------MAIN----------------------------------------- src_path = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\tif\\fuzzy\\src\\*.tif" wrt_path = "D:\\resilio\\ip_lib_ed\\src_images\\dslr\\tif\\fuzzy\\processed\\" images = glob.glob(src_path) img_amount = len(images) img_counter = 0 for image in images: img_counter = img_counter + 1 #print("{0} of {1}".format(img_counter, img_amount)) fuzzy_process(image, wrt_path) #concat_images = np.concatenate( (my_resize(img4,50), my_resize(img4, 50)), axis=1) #cv2.imshow('modified_image',concat_images ) #my_subplots(img4, img4) gc.collect() cv2.waitKey(0) cv2.destroyAllWindows() <file_sep>/fuzzy_processing_v6.py import matplotlib import matplotlib.pyplot as plt import numpy as np import cv2, itertools import gc import glob import statistics import random import collections from pathlib import Path import fuzzyfication #------------------------------------------------------------------------------------------------------------- # Операции с гистограммой BIT_DEPTH = 8 BIT_DEPTH_MAX_VALUE = 2**BIT_DEPTH """ def build_hist(img): height, width, colors = img.shape hist = dict(enumerate([0]*256)) for j in range(0,height): for i in range(0, width): pixel_val = int(img[j,i]) #print("pix_val:",pixel_val) hist[pixel_val] = hist[pixel_val]+1 return hist """ def get_histogram(img): hist = cv2.calcHist([img],[0], None, [256], [0,256]) hist = hist.astype(int) return hist def find_histogram_borders(h): for index, el in enumerate(h): if (el>0): left = index break for index, el in enumerate(h): if (el>40): right = index return (left, right) def gaus_filter(img): """ kernel_gausian = [ [1/16, 2/16, 1/16], [2/16, 4/16, 2/16], [1/16, 2/16, 1/16] ] """ kernel_gausian = [ [1/273, 4/273, 7/273, 4/273, 1/273], [4/273, 16/273, 26/273, 16/273, 4/273], [7/273, 26/273, 41/273, 26/273, 7/273], [4/273, 16/273, 26/273, 16/273, 4/273], [1/273, 4/273, 7/273, 4/273, 1/273] ] kernel_gausian_mat = np.array(kernel_gausian, dtype=float); gausian_image = cv2.filter2D(img,-1,kernel_gausian_mat) return gausian_image def get_median_histogram(h): bit_depth = len(list(h.keys())) #256 к примеру filtered = dict(enumerate([0]*(bit_depth))) for i in range(0, bit_depth): if (i < 3): if (i==0): filtered[i] = h[0] elif (i==1): filtered[i] = h[1] elif (i==2): filtered[i] = statistics.median([ h[i-2], h[i-1], h[i] ]) else: filtered[i] = statistics.median([ h[i-3], h[i-2], h[i-1], h[i] ]) return filtered def normalize_image(img, h): h_min_indx, h_max_indx = find_histogram_borders(h) height, width = img.shape image_res = np.zeros(shape=[height, width, 1], dtype=np.uint8) for i in range(0,width): for j in range(0, height): image_res[j,i] = ((img[j,i] - h_min_indx)/(h_max_indx-h_min_indx))*(len(h)-1) #cv2.imshow("normilized",image_res) return image_res def trashold_calculation(img): h1 = get_histogram(img) h2 = np.sort(h1, axis=0, order=None)[::-1] # по убыванию tau1 = h2[0] tau2 = h2[255] i = 1 while (tau1 > tau2): tau = tau1 tau1 = (tau1+h1[i])/2 tau2 = (tau2+h2[255-i])/2 i = i+1 return tau def merge_insignificant_bins(h, img): tau = trashold_calculation(img) print("TAU IS :",tau) h2 = np.zeros(shape=[256,1], dtype=np.uint32) for i in range(0, len(h)-1): if (h[i]< tau): h2[i] = 0 h2[i+1] = h[i] + h[i+1] else: h2[i] = h[i] return h2 """ def cumul_hist_val(histogram, grey): #print(histogram) cum = 0 for i in range(0, grey): cum = cum + histogram[i] return cum """ """ def cumulative_function(histogram): cum_dict = {} for i in range(0,256): cum_dict[i] = cumul_hist_val(histogram,i) return (cum_dict.keys(), cum_dict.values()) """ """ def analyze_histogram(h, member_vds): total_pixels = cumul_hist_val(h, BIT_DEPTH_MAX_VALUE-1 ) # я не считаю крайние правила слева и справа по одному rights = len(member_vds)-2 pixels_per_right = total_pixels//rights h_values = list(h.values()) pixels_per_region = {} for i in range(0, len(member_vds)-1): start = member_vds[i] end = member_vds[i+1] region_pixels = 0 for el in h_values[start:end]: region_pixels = region_pixels + el #pixels_per_region.append({i:region_pixels, round(region_pixels/pixels_per_right, 2)]}) pixels_per_region[(i, start,end, round(region_pixels/pixels_per_right, 2))] = region_pixels pixels_per_region = {k: v for k, v in sorted(pixels_per_region.items(), key=lambda item: item[1], reverse=True)} print("pixels_per_region: \t",pixels_per_region) dots = 0 result = {} for key in pixels_per_region: points = pixels_per_region[key]//pixels_per_right #points = round(pixels_per_region[key]/pixels_per_right) if (points == 0 ): points = 1 if (dots+points <= 6): dots = dots + points result[key] = [pixels_per_region[key], points] return result """ """ def get_member_params(h, region_stat, member_vds): h_values = list(h.values()) borders = histogram_borders(h, member_vds) result = [borders[0]] for key in region_stat: keys = list(region_stat.keys()) start = key[1] end = key[2] region_points = region_stat[key][1] if (key==keys[0] and start==0): start = borders[0] if (key==keys[-1] and end==255): end = borders[1] #result = result + random.choices(range(start,end), k=region_stat[key][1]) # maxs = list(maximums(h, maximums_count=region_stat[key][1], start=start, end=end).values()) maxs = [] dist = (end-start)//(region_points+1) for i in range(1, region_points+1 ): maxs.append(start+dist*i) print("maxs: \t",maxs) result = result + maxs result.append(borders[1]) return sorted(result) """ """ def build_first_derivative(hist): bit_depth = len(list(hist.keys())) #256 к примеру derivative = dict(enumerate([0]*(bit_depth))) j = 0 for i in range(0, bit_depth): hist_val = hist[i] if (i > 0 and i < (bit_depth-1) ): derivative[j] = (hist[i+1] - hist[i-1])/2 j = j +1 return derivative """ """ def get_derivative_maxs(derivative_histogram): h = derivative_histogram bit_depth = len(list(h.keys())) #256 к примеру derivative = dict(enumerate([0]*(bit_depth))) maxs = [] for i in range(1, bit_depth): if (h[i] < 0 and h[i-1] >= 0): maxs.append(i-1) return maxs """ """ def maximums(graph, maximums_count=0, start=0, end=255): # данный метод позволяет найти максимумы на графике # и выбрать из него только необходимое количество из # всех максимумов. При этом максимумы выбираются начиная # с самых больших значений. maximums = {} previous = 0 #print("start, end: ", start, end) for i in range(start+1, end): current = graph[i] - graph[i-1] #print("graph[",i,"]:", graph[i]) #print(current) if (current < 0 and previous > 0): maximums[i-1] = graph[i-1] previous = current # После того, как мы нашли максимумы, мы должны упорядичить эти # максимумы в порядке убывания, после чего выбрать только необходимое нам количество, # определенное в переменной maximums_count maximums = {k: v for k, v in sorted(maximums.items(), key=lambda item: item[1], reverse=True)} if (maximums_count): maximums = dict(itertools.islice(maximums.items(),maximums_count)) maximums = dict(sorted(maximums.items())) return maximums """ """ def region_max_value(h, start, end): h_values = list(h.values())[start:end] max_value = max(h_values) max_index = start + h_values.index(max_value) return max_index """ """ def find_local_max(h): max = 255 local_max = dict(enumerate([0]*(max+1))) j = 0 for i in range(0, max+1): if (i > 0 and i < max): if (h[i+1]==0 and h[i-1]==0): local_max[j] = 0 elif ((h[i-1] == h[i+1] and h[i] >= h[i+1] ) or (h[i-1] < h[i] and h[i+1] < h[i])): local_max[j] = h[i] else: local_max[j] = 0 j = j +1 return local_max """ """ def histogram_borders(h, member_vds): keys = list(h.keys()) for el in h: if (h[el]>20): left = el break for el in reversed(keys): if (h[el]>20): right = el break if (right < member_vds[1]): right = member_vds[1] if (left > member_vds[-2]): left = member_vds[-2] return (left, right) """ """ def calculate_median(l): l = sorted(l) l_len = len(l) return l[(l_len)//2] """ #------------------------------------------------------------------------------------------------------------- # графики # """ def show_cdf_func(h): graph = cumulative_function(h) plt.plot(list(graph[0]),list(graph[1]) ) plt.show() """ """ def show_cdf_derivative(h): cdf_graph = cumulative_function(h) cdf_dict = dict(zip(cdf_graph[0], cdf_graph[1])) deriv_graph = build_first_derivative(cdf_dict) plt.plot(list(deriv_graph.keys()),list(deriv_graph.values()) ) plt.show() """ """ def show_transformation_func(member_params, member_vds ): plt.plot(list(range(0,256)), get_defuzzification_list(member_params, member_vds), list(range(0,256)), list(range(0,256))) plt.show() """ """ def show_first_derivative(h): plt.bar(list(h.keys()), list(h.values())) #plt.show() """ """ def quality(region_percent): left_part = region_percent[0]+region_percent[1]+region_percent[2]+region_percent[3] dark_part = region_percent[0]+region_percent[1] darkest_part = region_percent[0] right_part = region_percent[4]+region_percent[5]+region_percent[6]+region_percent[7] light_part = region_percent[6]+region_percent[7] lightest_part = region_percent[7] print("regions: \t", regions) print("left_part: \t",left_part) print("dark_part: \t",dark_part) print("darkest_part: \t",darkest_part) print("----------------- \t") print("right_part:\t", right_part) print("light_part:\t", light_part) print("lightest_part:\t", lightest_part) if (left_part > 70 ): answer = "картинка темная" if (dark_part > left_part//2): answer = "картинка темноватая" if (darkest_part > dark_part//2): answer = "картинка оч темная" elif (right_part > 70 ): answer = "картинка светлая" if (light_part > right_part//2): answer = "картинка светловатая" if (lightest_part > light_part//2): answer = "картинка оч светлая" else: answer = "картинка нормас" print("quality: {0} \t".format(answer)) """ #----------------------------------------- """ def apply_lut(img,): height, width = img.shape colored_image = np.zeros(shape=[height, width, 3], dtype=np.uint8) for i in range(0,width): for j in range(0, height): pixel_val = img[j,i] if (pixel_val < 200): new_val = [0,0, pixel_val] else: new_val = [pixel_val,pixel_val, pixel_val] colored_image[j,i] = new_val return colored_image """ def region_devider(h, borders, region_total, needed_dots, right, this_index): start = borders[0] end = borders[1] if (needed_dots == 1): divider = 2 else: divider = needed_dots print("region_total :",region_total) one_part = region_total/divider print("one_part :",one_part) temp_sum = 0 dots = [] for index, count in list(enumerate(h))[start:end]: temp_sum = temp_sum + count if (temp_sum >= one_part): if (temp_sum > one_part*1.5): temp_sum = temp_sum - one_part else: temp_sum = 0 dots.append(index) if (needed_dots == 1): break print("len(dots) :",len(dots)) print("needed_dots-1 :",needed_dots-1) if (len(dots) == (needed_dots-1)): if (right): dots.append(end) else: dots.append(start) break return dots def calculate_points(h, sum_pix, region_pixels, regions, member_vds): borders = find_histogram_borders(h) left_border = member_vds[1] if borders[0] > member_vds[1] else borders[0] right_border = member_vds[-2] if borders[1] < member_vds[-2] else borders[1] sorted_regions = sorted(region_pixels, reverse=True) total_dots = [] for region in sorted_regions: this_index = region_pixels.index(region) percentage = int((region/sum_pix)*100) if (this_index < 4): right = True else: right = False dots_count = 1 if (percentage >= 60): dots_count = 4 elif (percentage >= 50): dots_count = 3 elif (percentage >= 40): dots_count = 2 elif (percentage >= 30): dots_count = 1 print("--------------") print("number: ", this_index) print("percent: ", percentage, " %") print("dots_count: ", dots_count) print("right: ", right) dots = region_devider(h, regions[this_index], region, dots_count, right, this_index) print("dots: ", dots) total_dots = total_dots + dots if (len(total_dots) == 7): break print("borders ", borders) total_dots = [left_border] + sorted(total_dots) + [right_border] print("total_dots ", total_dots) return total_dots def image_statisctic(h, member_vds, sum_pix): # делим картинку на 8 частей # в каждой из частей определяем - какое количество # пикселей там присутсвует. Если в левой части гистограммы большое скопление - # картинка темная, иначе - светлая. # Если в каждой части примерно равное количество - картинка выровненная. # Если большая часть в середине - то картинка не контрастная - необходимо немного # переместить пиксели влево и вправо, чтобы добиться небольшого контраста. print("********************** image_statisctic **********************") region = BIT_DEPTH_MAX_VALUE//8 regions = [[j*region, region*j+region] for j in range(0,8)] pixels = [] for region in regions: start = region[0] end = region[1] pix_region = sum(h[start:end]) pixels.append(pix_region) print("pixels in regions: {0} \t".format(pixels)) #borders = histogram_borders(h, member_vds) total_dots = calculate_points(h, sum_pix, pixels, regions, member_vds) return total_dots def find_equal_regions(h, sum_pix): # данная штука делит количество всех пикселей на 7. # и находит те области гистограммы, где содержится 1/7 часть # все пикселей. Цель - разрядить гистограмму таким образом, # посредством смещения в ту или иную сторону. region = sum_pix//8 print("pixel_counter: {0} pixels in image; 1/6 part of pixels: {1}".format(sum_pix, region)) cum = 0 j = 0 region_grade = [] previos_val = 0 for i in range(0, BIT_DEPTH_MAX_VALUE): cum = cum + h[i] #print("cum=",cum) if (cum >= region): cum = 0 region_grade.append([previos_val, i-1]) previos_val = i-1 if (j == 5): region_grade.append([previos_val, 255]) j = j+1 print("equal regions: ", region_grade) return region_grade def show_plot_graph(h, member_params, member_vds, equal_regions, image_filename="", wrt_path=""): max = 255 #equal_regions = [0] + equal_regions + [255] colors = [ (1, 0, 0, 0.4), (0, 0, 1, 0.4), (0, 1, 0, 0.4) , (0, 1, 1, 0.4), (1, 1, 0, 0.4), (1, 0, 1, 0.4), (0, 1, 0.5, 0.4), (1, 0,0, 0.4) ] keys = list(range(0,len(h))) values = list(h.ravel()) # каждый кусок 1/8 части гистограммы нам нужно расскрасить for region in equal_regions: position = equal_regions.index(region) start = region[0] end = region[1] x = keys[start:end] y = values[start:end] plt.bar(x, y, color=colors[position]) #plt.bar(list(graph[0]), list(graph[1]),color=colors[7] ) fuzzyfication.plt_member_functions(member_params, member_vds, max_top=35000) if (wrt_path): fig_wrt_path = wrt_path+"\\fig\\" Path(fig_wrt_path).mkdir(parents=True, exist_ok=True) plt.savefig(fig_wrt_path+image_filename+"_figure.png", dpi=500) else: plt.show() plt.close() def show_graphs(h1, h2, member_params, member_vds, total_pixels, image_filename="", wrt_path=""): #статистика equal_regions = find_equal_regions(h1, total_pixels) #графики #plt.bar(list(h1.keys()), list(h1.values()), color=(0, 0, 1, 0.6)) #plt.bar(list(h2.keys()), list(h2.values()), color=(1, 0, 0, 0.6)) #plt.show() plt.plot(member_params, [0,0,0,0,0,0,0,0,0], 'r^') #show_cdf_func(src_hyst) #show_transformation_func(member_params, member_vds) #show_first_derivative(median_first_derivative) plt.bar(list(range(0,len(h2))),list(h2.ravel()), color=(0.2, 0.4, 0.6, 0.3)) #show_plot_graph([h1.keys(), h1.values()], member_params, member_vds, equal_regions,image_filename, wrt_path ) show_plot_graph(h1, member_params, member_vds, equal_regions,image_filename, wrt_path ) def show_histogram(h): #plt.hist(img.ravel(),256,[0,256]) plt.bar(list(range(0,len(h))),list(h.ravel())) plt.show() def fuzzy_main_process(path): image_filename = path.split("\\")[-1] image_path = "\\".join(path.split("\\")[:-1]) wrt_path = image_path+"\\processed\\" Path(wrt_path).mkdir(parents=True, exist_ok=True) img = cv2.imread(path, 0) height, width = img.shape np_src_histogram = get_histogram(img) #show_histogram(np_src_histogram) #gaus_img = gaus_filter(img) #gaus_img_h = get_histogram(gaus_img) #show_histogram(gaus_img_h) #normalized_image = normalize_image(img, np_src_histogram) #normalized_histogram = get_histogram(normalized_image) #merged_histogram = src_hyst = np_src_histogram # merge_insignificant_bins(normalized_histogram, normalized_image) #show_histogram(src_hyst) #median_histogram = get_median_histogram(src_hyst) #median_first_derivative = build_first_derivative(median_histogram) #derivative_maxs = get_derivative_maxs(median_first_derivative) #target_histogram = median_histogram print(" ") print(" ") print("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||") print(" ") print("filename: \t", image_filename) print(" ") print("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||") member_vds = [0,32,64,96,128,160,192,224, 255] member_params = image_statisctic(src_hyst, member_vds, height*width) #member_params = [0, 12, 20, 26, 32, 46, 86, 120, 224] fuzzy_image = fuzzyfication.get_fuzzy_image(img, member_params, member_vds) fuzz_hyst = get_histogram(fuzzy_image) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) clahe_image = clahe.apply(fuzzy_image) #local_max = find_local_max(src_hyst) cv2.imwrite(wrt_path+image_filename, clahe_image) """ colored_image = apply_lut(img) cv2.imwrite(wrt_path+"lut_"+image_filename, colored_image) """ #show_graphs(src_hyst, fuzz_hyst, member_params, member_vds, height*width,image_filename, wrt_path ) def clahe_method(path): image_filename = path.split("\\")[-1] image_path = "\\".join(path.split("\\")[:-1]) wrt_path = image_path+"\\processed\\clahe\\" Path(wrt_path).mkdir(parents=True, exist_ok=True) img = cv2.imread(path, 0) height, width = img.shape clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(5,5)) clahe_image = clahe.apply(img) cv2.imwrite(wrt_path+"clahe_"+image_filename, clahe_image) #------------------------------MAIN----------------------------------------- #src_path = "D:\\image_library\\fuzzy_logic\\test\\" src_path = "D:\\image_library\\fuzzy_logic\\room\\video\\" #src_path = "D:\\image_library\\fuzzy_logic\\street\\yes\\" #src_path = "D:\\image_library\\fuzzy_logic\\kodak\\" images = glob.glob(src_path+"*.*") img_amount = len(images) img_counter = 0 print("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||") print("PROCESSING...") print("TOTAL_IMAGES: ", img_amount) for image_path in images: img_counter = img_counter + 1 print(" ") print("- - - - - - -") print("IMAGE {0} of {1}".format(img_counter, img_amount)) fuzzy_main_process(image_path) #clahe_method(image_path) #concat_images = np.concatenate( (my_resize(img4,50), my_resize(img4, 50)), axis=1) #cv2.imshow('modified_image',concat_images ) #my_subplots(img4, img4) gc.collect() cv2.waitKey(0) cv2.destroyAllWindows() <file_sep>/raw/converter.py from bitstring import BitArray import tifffile as tiff import numpy as np import cv2 def get_binary(path): n = 8 with open(path, 'rb') as byte_reader: file = byte_reader.read() binary_file = BitArray(bytes=file).bin #byte_list = [''.join(reversed(binary_file[i:i+n])) for i in range(0, len(binary_file), n)] byte_list = [binary_file[i:i+n] for i in range(0, len(binary_file), n)] k = 14 byte_list = [i[::-1] for i in byte_list] byte_srt = ''.join(byte_list) byte_list_14 = [''.join(reversed(byte_srt[i:i+k])) for i in range(0, len(byte_srt), k)] return byte_list_14 def create_tiff(path, raw, width, height): new_image = np.zeros(shape=[height, width], dtype=np.uint16) num = 0 for i in range(0,height): for j in range(0, width): new_image[i,j] = int(raw[num],2) num = num + 1 tiff.imsave(path, new_image) def create_test_tiff(width, height): new_image = np.zeros(shape=[height, width], dtype=np.uint16) num = 0 for i in range(0,height): for j in range(0, width): print(num) new_image[i,j] = num num = num + 1000 return new_image def tiff_to_raw(wrt_path, tiff_path): img = cv2.imread(tiff_path,-1) print(img[0][0]) #cv2.imshow('16bit TIFF', img) #cv2.waitKey() def extractor(org_bin, base_bin, width, height): new_image = np.zeros(shape=[height, width], dtype=np.uint16) num = 0 print(org_bin[0]) print(org_bin[1]) print(org_bin[2]) for i in range(0,height): for j in range(0, width): a = int(org_bin[num],2) b = int(base_bin[num],2) res = 0 if a-b+8000 <0 else a-b+8000 new_image[i,j] = res #print("a,b,res,new_image[i,j] ",a,b,res,new_image[i,j]) #print("res",res) #print("new_image[{0},{1}]={2}".format(i,j,new_image[i,j])) # num = num + 1 return new_image height = 512 width = 640 org_path = "src\\2\\org.raw" base_path = "src\\2\\base.raw" wrt_file = "src\\2\\res.tiff" org_bin = get_binary(org_path) base_bin = get_binary(base_path) extracted_image = extractor(org_bin, base_bin, width, height) tiff.imsave(wrt_file, extracted_image)
86033cea006957842ea09990bbdc27298db637ea
[ "C", "Python" ]
13
Python
edwardianec/hystogram_equalization
cf1649c9c6592cdd35a29952e274c08b60b37944
91e4a44be56a2bc8e8e0957894a54d49541bc666
refs/heads/master
<repo_name>Jesusz0r/YelpCamp<file_sep>/routes/profile.js 'use strict'; const express = require('express'); const Campground = require('../models/campground'); const Comment = require('../models/comment'); const User = require('../models/user'); const middlewareObj = require('../middleware'); const router = express.Router(); router.get('/profile', middlewareObj.isLoggedIn, (req, res) => { User.findById(req.user.id).populate('campgrounds').exec() .then((currentUser) => { res.render('profile/profile', { currentUser: currentUser }); }) .catch((err) => { req.flash('error', err.message); res.status(500).render('profile/error'); throw new Error(err); }); }); router.put('/profile/edit/mail', middlewareObj.isLoggedIn, (req, res) => { User.findById(req.user.id) .then((user) => { if (req.body.mail === user.mail && req.body.newmail) { user.mail = req.body.newmail; user.save() .then((user) => { req.flash('success', 'Successfuly updated your email.'); return res.redirect('/profile'); }); } else if (req.body.mail !== user.mail) { req.flash('error', 'The email introduced doesn\'t match with your current email.'); return res.redirect('/profile'); } else { req.flash('error', 'Please provide a new email.'); return res.redirect('/profile'); } }) .catch((err) => { req.flash('error', err.message); return res.redirect('/profile'); }); }); router.put('/profile/edit/password', middlewareObj.isLoggedIn, (req, res) => { User.findById(req.user.id) .then((user) => { const { oldPassword, newPassword, confirmNewPassword } = req.body; if (oldPassword && newPassword === confirmNewPassword) { if (user.comparePassword(oldPassword)) { user.setPassword(<PASSWORD>, (err) => { if (err) { req.flash('error', err.message); return res.redirect('/profile'); } user.save() .then(() => { req.flash('success', 'Password successfuly changed.'); return res.redirect('/profile'); }) .catch((err) => { req.flash('error', err.message); return res.redirect('/profile'); }); }); } else { req.flash('error', 'Incorrect old password.'); return res.redirect('/profile'); } } else if (!oldPassword || !newPassword || !confirmNewPassword) { req.flash('error', 'Please fill in all password fields.'); return res.redirect('/profile'); } else { req.flash('error', 'The new password fields does not match.'); return res.redirect('/profile'); } }); }); module.exports = router;<file_sep>/routes/comment.js 'use strict'; const express = require('express'); const router = express.Router(); const Campground = require('../models/campground'); const Comment = require('../models/comment'); const User = require('../models/user'); const middlewareObj = require('../middleware'); const xssFilter = require('xss-filters'); router.post('/campgrounds/:id/comments', middlewareObj.isLoggedIn, (req, res) => { User.findById(req.user.id). then((user) => { Campground.findById(req.params.id) .then((campground) => { let newComment = { comment: xssFilter.inHTMLData(req.body.comment), author: req.user.username }; Comment.create(newComment) .then((comment) => { comment.author.id = req.user._id; comment.author.username = req.user.username; comment.save(); campground.comments.push(comment); campground.save(); user.comments.push(comment); user.save(); req.flash('success', 'Comment successfuly created!'); return res.redirect(`/campgrounds/${campground._id}`); }); }) .catch((err) => { req.flash('error', err.message); return res.redirect('/campgrounds'); }); }) .catch((err) => { req.flash('error', err.message); return res.redirect(`/campgrounds/${req.body.id}`); }); }); router.get('/campgrounds/:id/comments/:comment_id/edit', middlewareObj.checkCommentOwnership, (req, res) => { Comment.findById(req.params.comment_id) .then(function(err, comment) { return res.render('comments/edit', { campground_id: req.params.id, comment: comment }); }) .catch((err) => { req.flash('error', err.message); return res.redirect(`/campgrounds/${req.params.id}`); }); }); router.put('/campgrounds/:id/comments/:comment_id/edit', middlewareObj.checkCommentOwnership, (req, res) => { Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment) .then((err, comment) => { req.flash('success', 'Comment successfuly updated!'); return res.redirect(`/campgrounds/${req.params.id}`); }) .catch((err) => { req.flash('error', err.message); return res.redirect(`/campgrounds/${req.params.id}`); }); }); router.delete('/campgrounds/:id/comments/:comment_id', (req, res) => { Comment.findByIdAndRemove(req.params.comment_id) .then((comment) => { req.flash('success', 'Comment successfuly deleted!'); return res.redirect('/campgrounds/' + req.params.id); }) .catch((err) => { req.flash('error', err.message); return res.redirect(`/campgrounds/${req.params.id}`); }); }); module.exports = router;<file_sep>/models/user.js 'use strict'; const mongoose = require('mongoose'); const localPassportMongoose = require('passport-local-mongoose'); const crypto = require('crypto'); let User = new mongoose.Schema({ username: { type: String, required: true, unique: true, lowercase: true }, mail: { type: String, required: true, unique: true, lowercase: true, match: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i }, attemps: Number, last: Date, salt: String, hash: String, comments: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' } ], campgrounds: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Campground' } ] }); User.methods.comparePassword = function(password) { const hash = crypto.pbkdf2Sync(password, this.salt, 2500, 512, 'sha256').toString('hex'); return this.hash === hash; } User.plugin(localPassportMongoose, { interval: 1000, usernameLowerCase: true, limitAttempts: true, maxAttempts: 5 }); module.exports = mongoose.model('User', User);<file_sep>/routes/authentication.js 'use strict'; const express = require('express'); const passport = require('passport'); const User = require('../models/user'); const router = express.Router(); const xssFilter = require('xss-filters'); /* User Authentication //////////////////////*/ // Route to the login form router.get('/login', (req, res) => { res.render('authentication/login'); }); // Post route from the login form router.post('/login', (req, res) => { passport.authenticate('local', { failureRedirect: '/login', failureFlash: req.flash('error') })(req, res, () => { if (req.isAuthenticated()) { req.flash('success', `Welcome back ${req.user.username}`); return res.redirect('/'); } }); }); // Route to the sign up form router.get('/signup', (req, res) => { res.render('authentication/signup'); }); // Post route from the sign up form router.post('/signup', function(req, res) { const newUser = { username: xssFilter.inHTMLData(req.body.username), mail: xssFilter.inHTMLData(req.body.mail) }; User.register(newUser, req.body.password, function(err, user) { if (err) { req.flash('error', err.message); console.log(err); return res.redirect('/signup'); } passport.authenticate('local')(req, res, () => { req.flash('success', 'You successfuly registered. Welcome!'); return res.redirect('/'); }); }); }); // Logout route router.get('/logout', (req, res) => { req.logout(); req.flash('success', 'You logged out successfuly!'); return res.redirect('/'); }); module.exports = router;<file_sep>/routes/campground.js 'use strict'; const express = require('express'); const multer = require('multer'); const router = express.Router(/* { mergeParams: true} here we tell router to merge all the params of all routes together, so we can use req.body.id */); const Campground = require('../models/campground'); const Comment = require('../models/comment'); const User = require('../models/user'); const middlewareObj = require('../middleware'); const xssFilter = require('xss-filters'); const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, './public/images/uploads'); }, filename: (req, file, cb) => { cb(null, file.originalname); } }); const upload = multer({ storage: storage }); /* Campgrounds Routes //////////////////////*/ // Root route /Campgrounds router.get('/', (req, res) => { Campground.find().sort({ createdOn: 'desc' }).exec() .then((allCampgrounds) => { return res.render('campgrounds/campgrounds', { campgrounds: allCampgrounds }); }) .catch((err) => { req.flash('error', err.message); return res.status(500).render('error/500', { error: err }); }); }); // /Campgrounds/new route router.get('/new', middlewareObj.isLoggedIn, (req, res) => { res.render('campgrounds/new'); }); // Post route /Campgrounds/new to create a new campground router.post('/new', middlewareObj.isLoggedIn, upload.single('image'), (req, res) => { User.findById(req.user.id) .then((user) => { const newCampground = new Campground({ title: xssFilter.inHTMLData(req.body.title), content: req.body.content, image: req.file.originalname, author: { id: req.user._id, username: req.user.username } }); Campground.create(newCampground) .then((camp) => { user.campgrounds.push(camp); user.save() .then(() => { req.flash('success', 'Campground successfuly created!'); return res.redirect('/campgrounds/' + camp._id); }); }); }) .catch((err) => { req.flash('error', err.message); return res.redirect('/campgrounds/new') }); }); // Route to show a single campground /Campgrounds/:id router.get('/:id', (req, res) => { Campground.findById(req.params.id).populate("comments").sort({ comments: 'desc' }).exec() .then((foundCampground) => { return res.render('campgrounds/show', { foundCampground }); }) .catch((err) => { req.flash('error', err.message); return res.redirect('/campgrounds'); }); }); // Route to delete a single campground /Campgrounds/:id router.delete('/:id', middlewareObj.checkCampgroundOwnership, (req, res) => { Campground.findByIdAndRemove(req.params.id) .then((camp) => { req.flash('success', 'Campground successfuly deleted!'); return res.redirect('/campgrounds'); }) .catch((err) => { req.flash('error', 'We could not delete that campground'); return res.redirect('/campgrounds'); }); }); // Route to show a single campground /Campgrounds/:id router.get('/:id/edit', middlewareObj.checkCampgroundOwnership, (req, res) => { Campground.findById(req.params.id) .then((foundCampground) => { return res.render('campgrounds/edit', { foundCampground }); }) .catch((err) => { req.flash('error', err.message); return res.redirect(`/campgrounds/${req.params.id}`); }); }); router.put('/:id/edit', middlewareObj.checkCampgroundOwnership, upload.single('image'), (req, res) => { const editedCampground = { title: xssFilter.inHTMLData(req.body.title), content: req.body.content, }; Campground.findByIdAndUpdate(req.params.id, editedCampground) .then((campground) => { campground.image = req.file ? req.file.filename : campground.image; req.flash('success', 'Campground successfuly edited!'); return res.redirect(`/campgrounds/${req.params.id}`); }) .catch((err) => { req.flash('error', err.message); return res.redirect(`/campgrounds/${req.params.id}`); }); }); module.exports = router;<file_sep>/README.md # YelpCamp Simple CRUD application made with Node.js, Express and MongoDB. You can create new campgrounds, create users, add comments, remove if you're the owner.
0c78e566f9550dd65e5b892f0b72c5a5fe887ffe
[ "JavaScript", "Markdown" ]
6
JavaScript
Jesusz0r/YelpCamp
c2d3226673e764c8503688e3e40a6fb734b12c99
16a5dde6a58b9b7e28ffc936b94b3e78945de5bc
refs/heads/master
<file_sep><?php include "header.php"; if (isset($_SESSION['id'])) { } else { header("Location: pealeht.php?error=login"); exit(); } ?> <div class="container rounded"> <div class="page-header"> <h3>Kontakt</h3> </div> <p> <NAME>ORUM </p> </div> <footer> <hr /> <p> © 2017 <NAME> </p> </footer> </body> </html> <file_sep><?php include "header.php"; ?> <div class="container rounded"> <div class="page-header"> <h3>Residentuur</h3> </div> <ul class="viide"> <li> <a href="http://www.med.ut.ee/et/residentuur">Üldinfo</a> </li> <li> <a href="http://ettas.ee/2-uncategorised/14-residentide-nimekiri">Residendid</a> </li> <li> <a href="http://ettas.ee/2-uncategorised/15-info-residentidele">Info residentidele</a> </li> <li> <a href="http://ettas.ee/2-uncategorised/16-res-materjalid">Materjalid</a> </li> <li> <a href="http://ettas.ee/2-uncategorised/17-res-soovitatav-kirjandus">Soovitatav kirjandus</a> </li> <li> <a href="http://ettas.ee/forums">Foorum</a> </li> </ul> </div> <footer> <hr /> <p> © 2017 <NAME> </p> </footer> </body> </html> <file_sep><?php session_start(); ?> <!DOCTYPE html> <html lang="et"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="keywords" content="ETTAS, Eesti Töötervishoiuarstide Selts, Töötervishoid" /> <meta name="robots" content="index/follow" /> <title>ETTAS</title> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" type="text/css" href="css/style.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <?php function echoActiveClass($requestUri) { $current_file_name = basename($_SERVER['PHP_SELF'], ".php"); if ($current_file_name == $requestUri) echo 'class="active"'; } ?> <header> <nav class="navbar navbar-default navbar-static-top"> <div class="container2"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="pealeht.php">ETTAS</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav nav1"> <li <?=echoActiveClass("pealeht")?>><a href="pealeht.php">Avaleht</a></li> <li <?=echoActiveClass("liikmed")?>><a href="liikmed.php">Liikmed</a></li> <li <?=echoActiveClass("pohikiri")?>><a href="pohikiri.php">Põhikiri</a></li> <li <?=echoActiveClass("viited")?>><a href="viited.php">Viited</a></li> <li <?=echoActiveClass("materjalid")?>><a href="materjalid.php">Materjalid</a></li> <li <?=echoActiveClass("teated")?>><a href="teated.php">Uudised</a></li> <li <?=echoActiveClass("phindamine")?>><a href="phindamine.php">Pädevuse hindamine</a></li> <li <?=echoActiveClass("arhiiv")?>><a href="arhiiv.php">Arhiiv</a></li> <li <?=echoActiveClass("kontakt")?>><a href="kontakt.php">Kontakt</a></li> <li <?=echoActiveClass("residentuur")?>><a href="residentuur.php">Residentuur</a></li> <?php if(isset($_SESSION['id'])){ echo "<li><a href='kasutajale.php'>Liikmele</a></li>"; } ?> </ul> <?php if(isset($_SESSION['id'])){ echo "<form action='includes/logout.inc.php'> <button id='form1' class='btn btn-primary'>Välju</button> </form>"; } else{ echo "<form class='form-inline my-2 my-lg-0' action='includes/login.inc.php' method='POST'> <div id='form'><input type='text' name='uid' class='form-control mb-2 mr-sm-2 mb-sm-0' id='inlineFormInput' placeholder='Kasutaja' required> <input type='<PASSWORD>' name='pwd' class='form-control' id='inlineFormInputGroup' placeholder='Parool' required> <button id='logbtn' type='submit' class='btn btn-primary'>Sisene</button></div> </form>"; } ?> </div> </div> </nav> </header> <file_sep><?php include "header.php"; ?> <div class="container rounded"> <div class="page-header"> <h3>Kontakt</h3> </div> <p> <NAME>ELTS </p> <p> Kutsehaiguste- ja Töötervishoiukeskus <br /> SA Põhja-Eesti Regionaalhaigla <br /> Hiiu 39 <br /> 11619 <br /> Tallinn </p> <p> e-mail: <a href="mailto:<EMAIL>"><EMAIL></a><br /> telefon: 6172942 </p> </div> <footer> <hr /> <p> © 2017 <NAME> </p> </footer> </body> </html> <file_sep><?php include "header.php"; ?> <div class="container rounded"> <div class="page-header"> <h3>Arhiiv</h3> </div> <p> ETTAS küsitlus 2009 <a href="http://ettas.ee/files/docs/Kysitlus_tootervishoiuarstidele.pdf">Küsitlus</a>(<a href="http://ettas.ee/files/docs/Kysitlus_tootervishoiuarstidele.doc">DOC-formaadis</a>) </p> <br /><br /> <p> ETTAS aastakoosolek lükkub nädala võrra edasi 21. maile. Koosolek toimub Tartu Ülikoolis, Biomedicum´is , Ravila 19, kl 12-17, ruumis 1024. </p> <br /> <p> <b>Päevakava</b> </p> <ul class="viide"> <li> 12.00 Tegevusteraapia olemus ja rakendamine töötervishoius. <NAME>la, tegev terapeut </li> <li> 12.30 ETTAS aastaaruanne. Viive Pille, ETTAS juhataja </li> <li> 13.15 ETTAS Meda Pharma tootetutvustus (diskussioon kohvipausil) </li> <li> 13.45 Kohvipaus </li> <li> 14.00 Toidulisandid – kasu või kahju? Ruudo Annus, TTH arst-resident </li> <li> 14.30 EPP AS tooteesitlus. Ravisukatooted. Nahakaitsetooted; kaitsekreemid, päikesekaitse. </li> <li> 14.45 Kohvipaus (EPP AS toodetega tutvumine jätkub) </li> <li> 15.00 Terviseameti Töötervishoiu büroo tutvustus. TSH diagnoosimise juhised (Blue Book). <NAME>, SM Terviseamet, TTH osakonna juhataja. </li> <li> 15.10 Töörühmad: terviskontrolli otsused – töötervishoiuarsti töö efektiivsuse indikaator, <NAME>, <NAME> </li> <li> 16.10 Kokkuvõtted, otsused, tegevuste planeerimine. </li> </ul> <br /> <p> Toitlustamise täpsemaks planeerimiseks on oluline eelnevalt teada osavõtjate arvu, seega palun registreeruge 10. maiks aadressil: <a href="mailto:<EMAIL>"><EMAIL></a>. </p> <br /> <p> Aktuaalse teemana meie erialal jätkub töötervishoiuarstide poolt väljastatavate tervisekontrolli otsuste sisu (ettepanekud ja töökorraldus) analüüsimine ja järelduste tegemine Tööinspektsiooni vastava sisulise sihtkontrolli tulemustest Sotsiaalministeeriumis. Seega pidasime juhatusega vajalikuks informeerida seltsis dialoogist SM-ga ja jätkata koosolekul vastavat arutelu. Palun mõelge läbi, milliseid oma töökogemusi, mõtteid saaksite jagada kolleegidega rühmatöödes. Oodatud on ETTAS liikmete ettepanekud koosoleku ettekanneteks! </p> <br /> <p> Kolleegid, kes ei ole varasemast kätte saanud pädevustunnistusi, tulge palun koosolekule Teie tunnistused ootavad! Kõik eelmisel aastal pädevust taotlenud kolleegid on selle saanud ning vastav info on olemas Terviseameti kodulehel. </p> <br /> <p> <b>Kolleegid, palun jälgige ja analüüsige oma töö kvaliteeti!</b> </p> <br /> <p> NB! Residentide juhendajad, vaadake üle milliseid otsuseid residendid kirjutavad ning iseseisvalt töötervishoiuarstina ei tohiks resident ühtegi otsust ega teatist allkirjastada! </p> <br /> <p> Tööinspektsiooni poolt saadetud kirjast mõned lõigud: </p> <p> Töötervishoiuarstide Seltsile arutamiseks-informatsiooniks: <br /> </p> <p> 1. Tööst põhjustatud haigestumiste teatiste vormid varieeruvad väga palju erinevate arstide lõikes - ehk oleks seltsi koosolekul hea üle korrata, et TI kodulehel on teatise vorm olemas, panen selle manusesse ka, et kõikidele üheselt saaks info edastada.<br /> </p> <p> 2. Töötervishoiuarstid on hakanud tervisekontrolli otsuste ettepanekute ossa kirjutama töötaja sõnade kohaselt, milliseid isikukaitsevahendeid töötaja parajasti kasutab. Samas töötaja räägib arstile sellest nö mälu järgi - ja nii ununeb mõni isikukaitsevahend suure tõenäosusega nimetamata. Tööandja, kes saab sellise otsuse ei oska sellest kuidagi mingit ettepanekut välja lugeda, sest kui töötaja kasutab neid - kas see tähendab siis seda, et muid ei olekski vaja või...? Samas on tööandja väljastanud töötajale oluliselt rohkem, kui töötajal parasjagu meeles oli arstile üles lugeda... <br /> </p> <p> Tööandja on parajas segaduses: tegelikult kasutab töötaja veel tööandja poolt väljastatud tolmumaski ja kõrvatroppe, aga samas pole neid arsti poolt üles loetletud - tööandja mures - kas tulevikus, kui peaks näiteks diagnoositama kutsehaigus töötajal, mille on põhjustanud tolm - ja töötervishoiuarst ei ole kirja pannud antud otsusel, et ta tõepoolest tolmumaski kasutab - võib jääda kohtunikule (ükskõik kellele) mulje, et neid ei ole antud. Või pole neid ka arst vajalikuks pidanud?<br /> </p> <p> see ei olegi esitatud niivõrd küsimusena, vaid arutelu teemana, kas peaks ikka üles lugema need isikukaistevahendid, mida tööandja nagunii on väljastanud - aga kui lugeda üles, siis võiks ikka tõe huvides ju kõik kirja panna, mitte ainult mõned. </p> <p> Jätkuvalt jõudu ning innukust ja ootame arvukat osavõttu aastakoosolekust! </p> <p> Palun rakendage ka nn naabrivalve meetodit seltsi liikmetest kolleegide teavitamiseks koosolekust ja info levitamiseks. </p> <br /><br /> <p> <b>Lugupeetud kolleegid!</b> </p> <p> Baltic Sea Network 16. aastakonverents toimub 30. september - 1. oktoober 2010 Tartus aadressil W.Struve 1 </p> <p> Registreerumise tähtajaks on 22. august. Registreerimiseks teatada osalemise <br /> <a href="mailto:<EMAIL>"><EMAIL></a> või <a href="mailto:<EMAIL>"><EMAIL></a>. </p> <p> NB! konverentsi eest maksma ei pea, ainult ööbimine ja transport. </p> <p> Konverentsi ööbimiskoht on <a href="http://www.dorpat.ee/index.php?page=3">Dorpati hotell</a>, aga see pole kohustuslik, võib soovi korral ka ise otsida sobivama koha. </p> <p> Konverentsi kava saab alla laadida <a href="http://ettas.ee/files/docs/BSN_Annual_Meeting_Programme_2010.doc">siit</a>. </p> <p> Ootame teid kõiki osa võtma! </p> <p> <NAME><br />ETTAS<br />617 2942 </p> </div> <footer> <hr /> <p> © 2017 <NAME> </p> </footer> </body> </html> <file_sep><?php function setComment($conn){ if(isset($_POST['commentSubmit'])) { $uid=$_POST['uid']; $date = $_POST['date']; $message = $_POST['message']; $sql ="INSERT INTO comments (uid,date,message) VALUES ('$uid','$date','$message')"; $result =mysqli_query($conn,$sql); } }; function getComment($conn) { $sql ="SELECT * FROM comments"; $result =mysqli_query($conn,$sql); while($row=mysqli_fetch_assoc($result)){ $id = $row['uid']; $sql_userid ="SELECT * FROM user WHERE id='$id'"; $result_userid =mysqli_query($conn,$sql_userid); if($row_userid=mysqli_fetch_assoc($result_userid)){ echo "<div class='well'><b>".$row_userid['uid']."</b><br /><i>".$row['date']."</i><br /><br />".nl2br($row['message'])."<br /><br />"."</div>"; } } } ?> <file_sep><?php include "header.php"; ?> <div class="container rounded"> <div class="page-header"> <h3>Põhikiri</h3> </div> <br /> <h3 class="text-center">MITTETULUNDUSÜHING EESTI TÖÖTERVISHOIUARSTIDE SELTS</h3> <br /> <h3 class="text-center">PÕHIKIRI</h3> <br /> <br /> <div class=spets1> <ol> <li> <!--1.--> <b>Üldsätted</b> <ol> <li> Mittetulundusühing Eesti Töötervishoiuarstide Selts (edaspidi ETTAS) on Eesti Vabariigis füüsiliste ja juriidiliste isikute demokraatlikel põhimõtetel tegutsev teaduslik-praktiline mittetulunduslik ühendus (asutatud 13. märtsil 1996.a.). </li> <li> ETTAS tegevus rajaneb tema asutajate ja liikmete algatusel ja ühisel tegutsemisel, seltsi juhtkonna valitavusel ja regulaarsel aruandlusel oma liikmeskonnale. </li> <li> ETTAS on eraõiguslik juriidiline isik oma pitsati, pangakonto ja sümboolikaga. </li> <li> ETTAS juhindub oma töös Eesti Vabariigis kehtivaist seadustest ja õigusaktidest, käesolevast põhikirjast ning juhtorganite asutamis- ja teistest otsustest. </li> <li> ETTAS tunnustab rahvusvahelisi töötervishoiualaseid konventsioone, direktiive, standardeid ja töötervishoiuspetsialistide eetikakoodeksit. </li> <li> Ingliskeelne ametlik nimetus: Estonian Society of Occupational Health Physicians. </li> <li> ETTAS asukohaks on Eesti Vabariik (Hiiu 39, 11619, Tallinn, Kutsehaiguste ja Töötervishoiukeskus, SA Põhja-Eesti Regionaalhaigla). </li> </ol> </li> <li> <!--2.--> <b>Eesmärgid ja tegevus</b> <ol> <li> ETTAS tegevuse eesmärgiks on töötervishoiu edendamine ja seltsi liikmete ametialaste huvide esindamine. </li> <li> ETTAS on Eesti töötervishoiuarstide ja töötervishoiualase teadusliku, pedagoogilise ja praktilise tööaspektidega seotud arstide ühendus. ETTAS esindab ja kaitseb oma liikmete õigusi ja huve riigi- ja kohalike omavalitsuste organites, suhetes teiste juriidiliste ja füüsiliste isikutega. ETTAS tegevust kannavad seltsi allüksustena erialasisesed töörühmad ja üksikliikmed. </li> <li> ETTAS tegevuse põhisuunaks on: <ol> <li> töötervishoiu kui eriala arendamine ja osalemine arengukontseptsiooni väljatöötamises, tööst põhjustatud haiguste ja kutsehaiguste kaasaegsete ennetus-, diagnostika- ja ravitöö metoodika koordineerimine, teooria ja praktika edendamine; </li> <li> ETTAS liikmete erialase kvalifikatsiooni tõstmine, töötervishoiuarstide sertifitseerimine ja pädevuse hindamine, täienduskoolituste korraldamine, töötervishoiualase informatsiooni kogumine ja edastamine; </li> <li> EV töötajaskonna terviseedenduse, tervisekasvatuse, töökeskonna parendamise ja eelnevaga seonduvate keskonnakaitse aktuaalsete küsimuste tõstatamine ja aktiivne osavõtt nende lahendamisest, ettepanekute avaldamine töökeskkonda ja töötajate tervisekaitset hõlmavate seaduste kohta; </li> <li> koostöö arendamine riigi-, omavalitsus-, teadus- ja kultuuriasutustega, loominguliste liitudega, ühiskondlike organisatsioonidega, ETTAS tegevusest huvitatud juriidiliste ja eraisikutega, Euroopa Liidu ja teiste riikide töötervishoiuspetsialiste ühendavate organisatsioonidega; </li> <li> ETTAS arendab seltsi majandustegevust sel määral, kui see on vajalik tema põhikirja eesmärkide saavutamiseks. ETTAS võib korraldada üritusi, välja anda ja avaldada oma tegevust kajastavaid sõnumeid, trükiseid, reklaambuklette ja vastavat kirjandust kui see ei ole vastuolus tema põhikirja ja EV seadusandlusega. </li> </ol> </li> <li> ETTAS vahendid moodustuvad: <ol> <li> ETTAS liikmemaksudest; </li> <li> annetustest, eraldistest, toetustest jms. (sihtotstarbelised või sihtotstarvet määramata); </li> <li> tuludest ürituste korraldamisel; </li> <li> muudest laekumistest. </li> </ol> </li> <li> ETTAS ei taotle oma majandustegevuses tulu, saadud tulu ei jagata ETTAS liikmete vahel, vaid suunatakse põhikirjalise tegevuse arendamiseks. ETTAS võib oma nimel omandada varalisi ja mittevaralisi õigusi ning kanda kohustusi, olla hagejaks või kostjaks kohtus, tal on oma vara, iseseisev bilanss, pangaarve ja nimeline pitsat. </li> <li> ETTAS vastutab oma kohustuste eest talle kuuluva varaga. </li> <li> ETTAS omandis võib olla igasugune vara, mis on põhikirjaliste eesmärkide saavutamiseks vajalik ja mille omandamine ei ole vastuolus seadusega. ETTAS haldab, valdab, kasutab ja käsutab iseseisvalt kogu talle kuuluvat vara: tal on õigus osta ja müüa, koormata piiratud asjaõigustega, anda üürile, rentida, kinkida, vahetada ning maha kanda moraalselt vananenud põhivahendeid. </li> <li> ETTAS ei kanna varalist vastutust oma liikmete varaliste kohustuste eest, liikmed ei kanna varalist vastutust ETTAS varaliste kohustuste eest. </li> <li> ETTAS vara kindlustamise otsustab juhatus, kui EV seadusandlusest ei tulene teisiti. </li> </ol> </li> <li> <!--3.--> <b>ETTAS liikmelisus</b> <ol> <li> ETTAS kuulumise eelduseks on põhikirjas toodud eesmärkide ja tegevussuundade tunnustamine ja järgimine. ETTAS liikmeks arvatakse uued liikmed kandidaadi avalduse esitamisel üldkogu otsuse alusel juhatuse otsusega ja uue liikme liikmelisus hakkab kehtima pärast liikmemaksu tasumist. </li> <li> ETTAS liikmed jagunevad: tegevliikmeteks, auliikmeteks ja toetajaliikmeteks. </li> <li> Liikmelisust ETTAS ja liikmeõiguse teostamist ei saa üle anda ega pärandada. </li> <li> ETTAS tegevliikmeteks võivad olla kõik arstid, kes soovivad edendada töötervishoiu teaduslikke, pedagoogilisi või praktilisi aspekte. </li> <li> ETTAS auliikmeks valitakse ETTAS juhatuse ettepanekul üldkogu lihthäälteenamusega isikuid, kellel on erilisi teeneid Eesti töötervishoiu ja tervishoiu edendamisel või ETTAS tegevusele kaasaaitamisel. ETTAS auliikmed ei tasu seltsi liikmemaksu. </li> <li> ETTAS toetajaliikmeks arvatakse juhatuse otsusel füüsilised või juriidilised isikud, kelle tegevus on olnud suunatud töötervishoiu või tervishoiu edendamisele ja ETTAS tegevusele kaasaaitamisele. </li> <li> ETTAS arvatakse välja üldkogu otsuse alusel juhatuse otsusega: <ol> <li> liikme isikliku avalduse alusel; </li> <li> juhatuse kirjaliku otsusega seltsi liikme tegevuse korral, mis on sobimatu ETTAS kuulumise põhimõtetega või olulisel määral ETTAS huve ja mainet kahjustav; </li> <li> objektiivse põhjuseta liikmemaksu tasumata jätmisel kahel järjestikusel aastal; </li> <li> füüsilise isiku surma korral. </li> </ol> </li> <li> ETTAS tegevliikmetel on õigus: <ol> <li> osa võtta ETTAS tegevusest vastavalt põhikirjas toodud eesmärkidele; </li> <li> valida ja olla valitud ETTAS juhtorganitesse ja kontrollorganitesse; </li> <li> esitada ETTAS juhtorganitele ettepanekuid, teha järelpärimisi nende tegevuse kohta ja põhjendatud taotluse alusel, täites autorikaitse ja andmekaitse nõudeid, tutvuda vastava dokumentatsiooniga, milles ei kajastu ärisaladused; </li> <li> taotleda ETTAS kaitset ja toetust kutsetöös; </li> <li> lahkuda ETTAS esitades juhatusele kirjaliku avalduse. </li> </ol> </li> <li> ETTAS tegevliikmete kohustused: <ol> <li> osaleda ETTAS üritustel ja täita põhikirjas sätestatud kohustusi; </li> <li> tasuda õigeaegselt liikmemaksu; </li> <li> mitte kahjustada ETTAS huve ja mainet. </li> </ol> </li> </ol> </li> <li> <!--4.--> <b>ETTAS juhtimine ja struktuur</b> <ol> <li> ETTAS juhtorganid on üldkogu (seltsi liikmete üldkoosolek), juhatus ja seltsi esimees. </li> <li> ETTAS kõrgeim organ on üldkogu, mis tuleb kokku vähemalt kaks korda aastas vastavalt juhatuse poolt määratud ajale. Üldkogu vaheajal juhib ETTAS tegevust juhatus. </li> <li> <u>Juhatusse kuulub 7 liiget: seltsi esimees, seltsi aseesimees, laekur ja 4 juhatuse liiget.</u> </li> <li> Juriidilist jõudu omavad finantsdokumendid, mis on allkirjastatud seltsi esimehe poolt või aseesimehe ja laekuri poolt. </li> <li> Üldkogu pädevusse kuulub: <ol> <li> ETTAS põhikirja muutmine; </li> <li> ETTAS ühinemise, jagunemise ja tegevuse lõpetamise otsustamine; </li> <li> ETTAS liikmemaksude ja tasumise korra määramine; </li> <li> ETTAS majandusaasta aruande kinnitamine; </li> <li> ETTAS tegevuskava ja eelarve kinnitamine; </li> <li> ETTAS juht- ja järelvalveorganite liikmete arvu määramine ja valimine valimistähtaja kinnitamisega; </li> <li> ETTAS juhatuse poolt valitud uute töögruppide loomise kinnitamine; </li> <li> ETTAS juhatuse poolt esitatud sertifitseerimiskomisjoni kinnitamine. </li> </ol> </li> <li> Üldkogu juhatab juhatuse liige, kelleks reeglina on ETTAS esimees. </li> <li> Üldkogu kohta koostatakse protokoll, mis allkirjastatakse koosoleku juhataja ja protokollija poolt. </li> <li> Üldkogu on otsustusvõimeline 50% + 1 liikme osalemisel. </li> <li> Üldkogul mitteosalevatel liikmetel on õigus taasesitamist võimaldavas vormis delegeerida teist ETTAS liiget enda eest hääletama. Volikiri peab olema koosoleku juhatajale esitatud enne üldkogu algust. </li> <li> Otsused võetakse vastu lihthääleenamusega. </li> <li> ETTAS põhikirja muutmiseks on vajalik otsustusvõimelisel üldkogul üle 2/3 osalenute poolthääletamine. </li> <li> Üldkogu toimumise aeg, päevakord ja koht teatatakse liikmetele vähemalt kuu aega enne üldkogu toimumist. </li> <li> Juhatuse pädevusse kuulub: <ol> <li> ETTAS töö juhtimine üldkogu istungitevahelistel perioodidel; </li> <li> üldkogu ja erakorralise üldkogu kokkukutsumine; </li> <li> ETTAS nimel esitatavate pöördumiste ettevalmistamine avaldamiseks; </li> <li> ETTAS esindamine või esindamise delegeerimine riigi- ja kohalike omavalitsuste organites ja muudes organisatsioonides; </li> <li> ETTAS nimel lepingute ja kokkulepete sõlmimine; </li> <li> sertifitseerimiskomisjoni isikkoosseisu komplekteerimine ja töötervishoiu-arstide täiendõppe korraldamine; </li> <li> stipendiumide, toetuste ja preemiate määramine; </li> <li> kandidaatide esitamine autasustamiseks ja aunimetuste omistamiseks; </li> <li> ETTAS raamatupidamise korraldamine; ETTAS raamatupidamise aastaaruande, tegevusaruande ja eelarve koostamine ja üldkogule esitamine hiljemalt majandusaastale järgneva kuue kuu jooksul; </li> <li> töögruppide ja toimkondade loomine; </li> </ol> </li> <li> ETTAS töögrupid on erialasiseste kitsaste valdkondade spetsialistide ühendused, mille eesmärgiks on oma töövaldkonna arendamine. Töögrupi tegevust juhib töögrupi juht, kes valitakse töögrupi liikmete poolt lihthääleenamusega vähemalt kord 2 aasta jooksul. Töögrupi juht määrab grupisisese töökorralduse, peab arvestust liikmete kohta ja esitab üldkogul juhatusele tegevusaruande iga tegevusaasta järgselt. </li> </ol> </li> <li> <b>Juhtorganite valimine</b> <ol> <li> Üldkogu valib seltsi esimehe, juhatuse ja revisjonikomisjonirevidendi. Kandidaadid nimetatud ametikohtadele esitatakse juhatusele seltsi tegevliikmete poolt kirjalikult vähemalt kuu aega enne valimisi. </li> <li> Kandidaadiks võib üles seada ETTAS tegevliiget. Kandideerida ja hiljemalt kolm päeva enne üldkogu peab ta vastavale kohale kandideerimise nõusolekust juhatust kirjalikult teavitama. </li> <li> Juhatus valitakse kolmeks aastaks. Seltsi esimees valitakse salajasel hääletusel lihthäälte enamusega. Seltsi esimees võib olla järjest valitud maksimaalselt kaheks valimisperioodiks. <p></p> Kui juhatuse liige esitab juhatusele avalduse enda taandamiseks saab asendusliikmeks üldkogul suurima häältearvuga juhatusest välja jäänud kandidaat. Teised juhatuse liikmed reeglina ümbervalimisele ei kuulu. </li> <li> Üldkogu võib tagasi kutsuda mõjuval põhjusel juhatuse liikme, milleks on eelkõige kohustuste täitmata jätmine tahtmatuse või suutmatuse tõttu. <p></p> Esimehe tööülesanded võtab üle seltsi aseesimees. Aseesimehe või laekuri ülesandeid kuni järgmiste valimisteni täidab juhatuse liikmete hulgast juhatuse koosolekul lihthäälteenamusega valitud liige. </li> <li> Üldkogu valib juhatuse liikmed lihthäälteenamusega salajasel hääletusel. </li> </ol> </li> <li> <b>Revisjon</b> <ol> <li> ETTAS tegevuse kontrollimiseks valitakse üldkoosoleku poolt kolmeks aastaks revisjonikomisjoni. Revisjonikomisjon valib oma liikmete seast esimehe. </li> <li> Revisjionikomisjon kontrollib majandusaasta raamatupidamise aastaaruande ja tegevusaruande seaduslikkust. <br /><u>Seadusandlusega sätestatud juhul tellitakse auditeerimine.</u> </li> <li> Revisjon viiakse läbi ETTAS kord aastas ja aruanne esitatakse ETTAS juhatusele, kes esitab selle üldkoosolekule. </li> </ol> </li> <li> <b>ETTAS tegevuse lõpetamine</b> <ol> <li> ETTAS tegevus lõpetatakse: <ol> <li> üldkogu otsusega. ETTAS lõpetab tegevuse kui juhatuse vastavasisuline ettepanek saab üldkogul 2/3 häälteenamuse. ETTAS tegevuse lõpetamine toimub Eesti Vabariigi seadusandlusega ettenähtud korras; </li> <li> pankrotimenetlusel, kohtuotsusega või muudel seadusega ettenähtud juhtudel; </li> <li> ETTAS liikmeskonna vähenemise tõttu üldkogu võimetuse korral määrata põhikirjaga ettenähtud juhtorganite liikmeid; </li> </ol> </li> <li> ETAS tegevuse lõpetamisel moodustab üldkogu kolmeliikmelise likvideerimis-komisjoni, kellel on juhatuse õigused ja volitused. </li> <li> Likvideerimiskomisjon teeb ainult neid tehinguid, mis on vajalikud ETTAS likvideerimiseks ja lahendab ETTAS varade üleandmise samalaadsete eesmärkidega ühingule, avalik–õiguslikule juriidilisele isikule või kasutamise põhikirjaliste eesmärkide saavutamiseks tegutsedes avalikes huvides seaduses ettenähtud korras. </li> </ol> </li> </ol> </div> <h4><b>MTÜ ETTAS põhikiri kinnitati Tallinnas 07.märtsil 2008.a. ETTAS liikmete üldkoosoleku otsusega.</b></h4> </div> <footer> <hr /> <p> © 2017 <NAME> </p> </footer> </body> </html> <file_sep><?php include "header.php"; ?> <div class="container rounded"> <div class="page-header"> <h3>Tere tulemast <NAME>ide Seltsi veebilehele!</h3> <?php $url=$_SERVER['REQUEST_URI']; if (strpos($url,'error=pw') !== false){ echo "</br><p class='text-center' id='error'>Vale kasutajanimi või parool.</p>"; } if (strpos($url,'error=login') !== false){ echo "</br><p class='text-center' id='error'>Foorumi kasutamiseks peate olema sisselogitud.</p>"; } if(isset($_SESSION['id'])){ echo "<p> Olete sisse logitud! </p>"; } ?> </div> </div> <footer> <hr /> <p> © 2017 <NAME> </p> </footer> </body> </html> <file_sep><?php session_start(); include '../dbh.php'; $uid= $_POST['uid']; $pwd= $_POST['pwd']; $sql="SELECT * FROM user WHERE uid='$uid'"; $result = mysqli_query($conn,$sql); $row=mysqli_fetch_assoc($result); $hash_pw = $row['pwd']; $hash = password_verify($pwd, $hash_pw); if ($hash == 0) { header("Location: ../pealeht.php?error=pw"); exit(); } else { $sql="SELECT * FROM user WHERE uid='$uid' AND pwd='$<PASSWORD>'"; $result = mysqli_query($conn,$sql); if (empty($uid)) { header("Location: ../pealeht.php?error=empty"); exit(); } if (empty($pwd)) { header("Location: ../pealeht.php?error=empty"); exit(); } else { if(!$row=mysqli_fetch_assoc($result)){ header("Location: ../pealeht.php"); echo "Incorrect username or password!"; } else{ $_SESSION['id']=$row['id']; header("Location: ../pealeht.php"); } } } ?> <file_sep><?php session_start(); include '../dbh.php'; $first= $_POST['first']; $last= $_POST['last']; $uid= $_POST['uid']; $pwd= $_POST['pwd']; $hash = password_hash($pwd, PASSWORD_DEFAULT); $sql="INSERT INTO user (first, last, uid, pwd) VALUES ('$first', '$last', '$uid', '$hash')"; $result = mysqli_query($conn,$sql); header("Location: ../index.php"); ?> <file_sep><?php include "header.php"; if(isset($_SESSION['id'])){ } else { header("Location: pealeht.php?error=login"); exit(); } include "dbh.php"; include "includes/comments.inc.php"; date_default_timezone_set('Europe/Tallinn'); ?> <div class="container rounded"> <div class="page-header"> <h3>Liikmete osa</h3> </div> <div class="row"> <div class="col-lg-6 col-md-12 col-sm-12"> <button type="button" class="btn btn-primary btn-block" data-toggle="collapse" data-target="#tekst1">Teema</button> <div id="tekst1" class="collapse"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu enim ut tellus dapibus convallis. In eleifend libero odio, eget accumsan nibh viverra non. Sed vitae pretium erat. Vivamus hendrerit mi non dui fermentum, a molestie lorem ultrices. Pellentesque porta nisi elit, vitae tempus enim lobortis non.<br /><br /> <?php echo "<form method='POST' action='".setComment($conn)."'> <input type='hidden' name='uid' value='".$_SESSION['id']."' /> <input type='hidden' name='date' value='".date('Y-m-d H:i:s')."' /> <textarea name='message' placeholder='Avalda arvamust'></textarea><br /> <button type='submit' name='commentSubmit' class='btn btn-primary'>Comment</button> </form>"; getComment($conn); ?> </div> <br /> </div> <div class="col-lg-6 col-md-12 col-sm-12"> <button type="button" class="btn btn-primary btn-block" data-toggle="collapse" data-target="#tekst2">Teema</button> <div id="tekst2" class="collapse"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu enim ut tellus dapibus convallis. In eleifend libero odio, eget accumsan nibh viverra non. Sed vitae pretium erat. Vivamus hendrerit mi non dui fermentum, a molestie lorem ultrices. Pellentesque porta nisi elit, vitae tempus enim lobortis non. </div> </div> </div> <br /> <div class="row"> <div class="col-lg-6 col-md-12 col-sm-12"> <button type="button" class="btn btn-primary btn-block" data-toggle="collapse" data-target="#tekst3">Teema</button> <div id="tekst3" class="collapse"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu enim ut tellus dapibus convallis. In eleifend libero odio, eget accumsan nibh viverra non. Sed vitae pretium erat. Vivamus hendrerit mi non dui fermentum, a molestie lorem ultrices. Pellentesque porta nisi elit, vitae tempus enim lobortis non. </div> <br /> </div> <div class="col-lg-6 col-md-12 col-sm-12"> <button type="button" class="btn btn-primary btn-block" data-toggle="collapse" data-target="#tekst4">Teema</button> <div id="tekst4" class="collapse"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu enim ut tellus dapibus convallis. In eleifend libero odio, eget accumsan nibh viverra non. Sed vitae pretium erat. Vivamus hendrerit mi non dui fermentum, a molestie lorem ultrices. Pellentesque porta nisi elit, vitae tempus enim lobortis non. </div> </div> </div> </div> <footer> <hr /> <p> © 2017 <NAME> </p> </footer> </body> </html> <file_sep><?php include "header.php"; ?> <div class="container rounded"> <div class="page-header"> <h3><b>Teated</b></h3> </div> <p> Tervise Arengu Instituut korraldab Tallinnas ja Tartus alkoholi liigtarvitamise varajase avastamise ja lühisekkumise (ALVAL) koolitusi. </p> <p></p> <br> <p> ALVALi koolituse eesmärk on võimaldada tervishoiutöötajal pädevalt, kindlalt ja asjakohaselt tõstatada patsiendiga alkoholi tarvitamise teema, seda sobivalt arutada ning viia läbi lühisekkumine, lähtuvalt tõenduspõhistest andmetest. Koolituse käigus saavad osalejad teada alkoholi tarvitamise riskipiiridest, harjutavad sõelumist AUDITiga ja "keerulise" alkoholiteema käsitlemist ning uurivad, millal, kuhu ja kelle juurde saab liigtarvitava patsiendi edasi suunata. </p> <p></p> <br /> <p> Koolitusel osalejatele antakse tunnistus ja koolitus annab täienduspunkte nii perearstidele kui pereõdedele. Koolitusele on oodatud peremeditsiini ala residendid, perearstid, pereõed, vaimse tervise õed, aga ka teised tervishoiutöötajad. </p> <p></p> <br /> <p> Koolitused toimuvad Tallinnas 25.-26.01, 16.-17.02, 28.02-01.03, 21.-22.03, 12.-13.04, 18.-19.04, 27.-28.04, 11.-12.05, 18.-19.05 ja 25.-26.05 ning <br />Tartus 16.-17.02, 21.-22.02, 09.-10.03, 22.-23.03, 30.-31.03, 25.-26.04, 09.-10.05, 23.-24.05 ja 08.-09.06. </p> <p></p> <br /> <p> Koolitus on tasuta ja osalejatele hüvitatakse majutuskulu. </p> <p></p> <p> <b>Koolituse ülesehitus:</b> </p> <p></p> <p> <b>I päev</b> </p> <ul> <li> 9.30 Kogunemine ja registreerimine </li> <li> 10.00 Sissejuhatus: ALVAL Eestis. Ülevaade koolitusest. Lühisekkumine – mis ja miks? Hoiakud alkoholi suhtes </li> <li> 11.30 Puhkepaus </li> <li> 11.45 Takistused ja probleemid. Lühisekkumine lähivaates </li> <li> 13.15 Lõuna </li> <li> 14.15 Alkoholiühikud. Alkoholi tarvitamise riskipiirid. Alkoholiprobleemi tõstatamine </li> <li> 15.45 Puhkepaus </li> <li> 16.00 Sõelumine ja tagasiside. Suunamine. Kokkuvõte ja küsimused </li> <li> 17.30 Esimese koolituspäeva lõpp </li> </ul> <p> <b>II päev</b> </p> <ul> <li> 9.00 Kogunemine ja registreerimine </li> <li> 9.30 Tagasivaade eilsele. Lühisekkumise läbiviimine – põhioskused </li> <li> 11.00 Puhkepaus </li> <li> 11.15 Lühisekkumise läbiviimine – põhioskused </li> <li> 12.45 Lõuna </li> <li> 13.45 Lühisekkumise läbiviimine täies mahus </li> <li> 15.15 Puhkepaus </li> <li> 15.30 Lühisekkumise läbiviimine täies mahus. Kokkuvõte </li> <li> 17.00 Koolituse lõpp </li> </ul> <p></p> <br /><br /> <p> Koolituse kohta on täpsem info üleval veebilehel: <a href="http://www.tai.ee/et/kainem-ja-tervem-eesti/koolitused">www.tai.ee/et/kainem-ja-tervem-eesti/koolitused</a> </p> <p> Lisainfo ja registreerimine e-posti aadressil <a href="mailto:<EMAIL>"><EMAIL></a>. </p> <br /><br /><br /><br /> <p> Koolitused toimuvad toetuse andmise tingimuste „Kainem ja tervem Eesti“ raames, mille eesmärk on parandada alkoholi liigtarvitamise ennetamiseks ja alkoholitarvitamise häire raviks vajalike tervishoiu- ja tugiteenuste kättesaadavust ja kvaliteeti Eestis. Lisainfot teenuste, koolituste ja programmi vältel valminud materjalide kohta leiate veebilehel <a href="http://www.tai.ee/kte">www.tai.ee/kte</a>. </p> <br /><br /> <hr /> <br /><br /> <p> <b>Uuest aastast jõustusid muudatused nakkushaiguste tervisekontrollis</b> </p> <a href="http://www.terviseamet.ee/info/uudised/u/artikkel/uuest-aastast-joustusid-muudatused-nakkushaiguste-tervisekontrollis.html">www.terviseamet.ee/info/uudised/u/artikkel</a> <p></p> <p> Alanud aastast jõustusid muudatused nakkushaiguste ennetamise ja tõrje seaduses, mis reguleerivad töötaja, tööandja ja ettevõtja tervisekontrolli nakkushaiguste suhtes. </p> <p> Ühe olulisema muudatusena kaob sellest aastast tööandjatel kohustus saata töötaja töötamise ajal korrapärasesse tervisekontrolli, sealhulgas iga kahe aasta järel kopsude röntgenuuringule. Arvestades, et töötaja võib nakatuda ning haigestuda nakkushaigusesse mis tahes ajahetkel, ei ole võimalik määrata tõenduspõhist ajaperioodi, mille jooksul on töötajate regulaarne tervisekontroll nakkushaiguste suhtes otstarbekas ja vajalik. </p> <p> Kuigi regulaarne tervisekontroll nakkushaiguste suhtes kaob, jääb tööandjal õigus saata töötaja täiendavasse tervisekontrolli vastavalt töökoha riskihindamise tulemustele. Vajadus riskihindamiseks ja täiendavaks tervisekontrolliks võib tekkida olukorras, kus tööprotsesside käigus on toimunud nakkuse levik, saastunud toodang või töökollektiivis ilmneb mõnel töötajal nakkushaigus. Sellisel juhul on asjakohane, et tööandja saadab vastavalt riskihindamise tulemusele töötaja või töötajad täiendavasse tervisekontrolli. </p> <p> Nii tööandjatel kui ka töötajatel on oluline teada sedagi, et kehtima hakanud muudatused kitsendavad tegevusvaldkondi, kus töötajate tervisekontroll nakkushaiguste suhtes on edaspidi ette nähtud. </p> <p> Tervisekontrolli läbimine on jätkuvalt nõutav toitu ja joogivett käitlevate töötajate või toidu ja joogiveega kokkupuutuvate töötajate puhul. Kontrolli peavad läbima loomapidajad ja isikud, kes oma tööülesannete tõttu puutuvad vahetult kokku põllumajandusloomade ja loomsete saadustega; õpetajad ja lasteasutuste töötajate ning teised töökohustuste tõttu laste ja noorukitega vahetult kokkupuutuvad töötajad; abivajajale vahetult teenust osutavad hoolekandetöötajad; tervishoiutöötajad ning teised patsiendiga vahetult kokkupuutuvad tervishoiuasutuse töötajad; kliendiga vahetult kokkupuutuvad ilu- ja isikuteenuseid osutavad töötajad ja kõikidel eelpool loetletud tegevusaladel praktikat sooritavad või täiendusõppes osalevad õpilased, üliõpilased ja töötajad. </p> <p> Nimetatud valdkondades töötavate isikute tervisekontroll enne tööle asumist on kohustuslik. Tervisekontrolli eesmärk on ennetada nakkushaiguste levikut klientidele, tarbijatele või patsientidele nakkusohtlike töötajate poolt tööprotsesside kaudu. Tervisekontroll on ette nähtud töövaldkondades, mis võivad olla võimalike nakkushaiguste puhangute ja epideemiate tekkekohtadeks. </p> <p> Võrreldes varem kehtinud seadusega antakse sellest aastast volitus teha tervisekontrolli nakkushaiguste suhtes lisaks perearstile ka töötervishoiuarstile. </p> <p> Ühe muudatusena oli soov selle aasta algusest asendada seni kasutusel olnud eraldiseisev tervisetõendi vorm tervisekontrolli läbimise kohta nakkushaiguste suhtes e-tõendiga, aga e-tõendi arendustegevus ei ole toimunud algse plaani kohaselt. E-tõendi väljatöötamine on plaanis 2017. a. jooksul. Seega tuleb jätkata tervisetõendite väljastamist paberkandjal. </p> <p> Palume perearstil ning töötervishoiuarstil nakkushaiguste suhtes tervisekontrolli läbiviimisel lähtuda olemasolevast terviseameti juhisest ning väljastada tervisekontrolli läbimise kohta tervisetõend paberkandjal. </p> <br /><br /><br /> <hr /> <br /><br /><br /> <div class="text-center"> <p> <b>In Memoriam dr <NAME></b> </p> <p> Meie seast on lahkunud hea kolleeg dr <NAME> </p> <p> 02.11.1951 – 31.12.2016 </p> <p> Dr <NAME> asus tööle <NAME>lasse 1. septembril 1987 ning töötas kardioloogina ja hiljem personali arstina, millest kasvas välja huvi töötervishoiu vastu ning hilisem spetsialiseerumine töötervishoiuarstiks. Kutsehaiguste ja töötervishoiu keskuses töötas dr <NAME> alates 2004. aastast. Katrin oli südamlik, rõõmsameelne ja suurte erialaste teadmistega kolleeg. </p> <br /> <p> Katrinit jäävad mälestama kolleegid, sõbrad ja perekond. </p> </div> <br /><br /> <hr /> <br /> <p> ETTAS juhatus annab teada,et 01.12.2016 kaitses edukalt PhD kraadi meie Seltsi esinaine dr.Viive Pille. </p> <p> Õnnitleme kolleegi selle tähtsa saavutuse puhul ja rõõmustagem ühiselt, et tema poolt tehtust ja uuritust tõuseb kasu ka meie erialale. </p> <p> (Kindlasti loodame kuulda väikest ülevaadet ka järgmisel ETTAS koosolekul) </p> <br /><br /> <hr /> <br /> <p> <b>Liimemaks 30€ tasuda ETTAS-e arvele: EE672200221045581473 Swedbank AS</b> </p> <br /><hr /><br /> <p> <b>Koolitused</b> </p> <ul class="viide"> <li> <a href="http://www.kliinikum.ee/koolitus/">TÜ Arstiteaduskonna täienduskeskus</a> </li> <li> <a href="http://www.itk.ee/index.php?page=188">Ida-Tallinna Keskhaigla koolituskeskus</a> </li> <li> <a href="http://www.ltkh.ee/?id=788&PHPSESSID=cceb758d71b34f2954d00dbb92984e98">Lääne-Tallinna Keskhaigla koolituskeskus</a> </li> <li> <a href="http://www.regionaalhaigla.ee/?op=body&id=123">Regionaalhaigla koolituskeskus</a> </li> </ul> </div> <footer> <hr /> <p> © 2017 <NAME> </p> </footer> </body> </html> <file_sep><?php include "header.php"; ?> <div class="container rounded"> <div class="page-header"> <h3><b>Viited</b></h3> </div> <ul class="viide"> <li> <a href="https://www.riigiteataja.ee/index.html">Seadusandlus</a> </li> <li> <a href="http://www.ti.ee/est/avaleht/">Tööinspektsioon</a> </li> <li> <a href="http://www.tervisekaitse.ee/tkuus.php">Tervisekaitse</a> </li> <li> <a href="http://www.sm.ee/et">Sotsiaalministeerium</a> </li> <li> <a href="http://tervishoiuamet.ee/">Tervishoiuamet</a> </li> <li> <a href="http://www.haigekassa.ee/">Haigekassa</a> </li> <li> <a href="http://www.sam.ee/">Ravimiamet</a> </li> <li> <a href="http://www.who.int/occupational_health/en/">WHO</a> </li> <li> <a href="http://www.ilo.org/public/english/protection/euportal/en/">ILO</a> </li> </ul> <p></p> <p></p> <p> <b>Ajakirjad</b> </p> <ul class="viide"> <li> <a href="http://www.mu.ee/">Meditsiiniuudised</a> </li> <li> <a href="http://eestiarst.ee/et/index.html">Eesti Arst</a> </li> </ul> </div> <footer> <hr /> <p> © 2017 <NAME>ötervishoiuarstide Selts </p> </footer> </body> </html> <file_sep><?php include "header.php" ?> <div class="container rounded"> <div class="page-header"> <h3><b>Pädevuse hindamine</b></h3> </div> <h4> <b>Töötervishoiuarstide pädevuse hindamine</b> </h4> <br /> <p> <b>Sertifitseerimise taotleja esitab komisjonile:</b> </p> <ul class="viide"> <li> <b>avaldus</b> </li> <li> <b>kirjalik aruanne oma töö kohta (perioodi pikkus kuni 5 aastat viimasest sertifitseerimisest)</b> </li> <li> <b>täienduskoolitused jms tabeli vormis, kindlasti märkida ära koolitustundide arv</b> </li> </ul> <p> <b>Dokumendid saata sertifitseerimiskomisjoni esimehele hiljemalt 30. aprilliks 2010. aadressil Hiiu 39, 11619, Tallinn, Kutsehaiguste ja Töötervishoiukeskus, SA Põhja-Eesti Regionaalhaigla.</b> </p> <br /><br /> <a href="http://ettas.ee/files/docs/eriarstpadevus.doc"><b>Eriarstide pädevuse hindamise kriteeriumid ja süsteem</b></a> <br /> <a href="http://ettas.ee/files/docs/TTA_taienduspunktid.doc"><b>Töötervishoiuarstide täienduspunktid</b></a> <br /><br /> <h4><b>Sertifitseerimiskomisjoni liikmed:</b></h4> <ul> <li> <b>professor <NAME> - komisjoni esimees</b> </li> <li> <b><NAME> </b> </li> <li> <b><NAME>ille</b> </li> <li> <b>Eda Merisalu</b> </li> <li> <b>Uno Kiplok </b> </li> </ul> <br /><br /> <a href="http://ettas.ee/files/docs/sertkomisjoni_pohikiri.doc"><b>Sertifitseerimiskomisjoni põhikiri</b></a> <br /> <p> </p> </div> <footer> <hr /> <p> © 2017 <NAME> </p> </footer> </body> </html> <file_sep><?php include "header.php"; ?> <div class="container rounded"> <div class="page-header"> <h3><b>Materjalid</b></h3> </div> <ul class="viide"> <li> <a href="http://ettas.ee/files/docs/Fsioloogilised_ohutegurid.pdf">Füsioloogilised ohutegurid</a> </li> <li> <a href="http://ettas.ee/files/docs/BIOLOOGILISED_OHUTEGURID_taiendustega.doc">Bioloogilised ohutegurid</a> </li> <li> <a href="http://ettas.ee/files/docs/Ergonoomika1.pdf">Ergonoomika loeng</a> </li> <li> <a href="http://ettas.ee/files/docs/Ergonoomika.pdf">Tööergonoomika loeng</a> </li> <li> <a href="http://ettas.ee/files/docs/Erg_farma.pdf">Ergonoomika (farmakoloogia)</a> </li> </ul> <p> </p> <p> <b>Juhendid</b> </p> <ul class="viide"> <li> <a href="http://ettas.ee/files/docs/ekspertiisidokumendid.pdf">Kutsehaiguse ekspertiisiks vajalikud dokumendid </a> </li> <li> <a href="http://ettas.ee/files/docs/ulajasemete_haigused03_10_2001.pdf">Ülajäsemete ülekoormushaiguste diagnoosijuhend</a> </li> <li> <a href="http://www.emta.ee/index.php?id=23811#arsti%20soovitused">Maksuameti koostatud juhend töötervishoiu kulude maksustamisest</a> </li> <li> <a href="http://www.ut.ee/tervis/aergo/index.html">Arvutitöö ergonoomika</a> </li> </ul> <p> </p> <p> <b>Veel lisaks koosolekud, muud materjalid</b> </p> <ul class="viide"> <li> <b>27.10.2005</b> <a href="http://osh.sm.ee/good_practice/ettekanded_25.10.2006.htm">Töötervishoiupäeva ettekanded </a> </li> <li> <b>25.10.2006</b> <a href="http://osh.sm.ee/good_practice/ttp-2005-ettekanded.htm">Töötervishoiupäeva ettekanded </a> </li> <li> <b>01.12.2006</b> <a href="http://ettas.ee/files/docs/Hematoloogilised_kutsehaigused.pdf">Seltsi koosolekul esitatud ettekanne kutsega seotud hematoloogilisest patoloogiast </a> </li> <li> <b>25.05.2007</b> <a href="http://ettas.ee/files/docs/ASBESTOOS.PPT">Karin Ojala ettekanne</a> </li> <li> <b>25.05.2007</b> <a href="http://ettas.ee/files/docs/Asbestiga_seotud_haigused_Paide.ppt">Toomas Uibu ettekanne </a> </li> <li> <b>30.05.2008</b> <a href="http://ettas.ee/files/docs/Tervishoiustatistiliste_aruannete_esitamine_ttervishoid.ppt">Merike Rätsepa ettekanne</a> </li> <li> <b>30.05.2008</b> <a href="http://ettas.ee/files/docs/Tervishoiuameti_tegevused.ppt">Irma Noole ettekanne </a> </li> <li> <b>19.09.2008</b> <a href="http://ettas.ee/files/docs/Reisberg080919.ppt">Rein Reisbergi ettekanne </a> </li> <li> <b>19.09.2008</b> <a href="http://ettas.ee/files/docs/Pille19_09_08.ppt">Viive Pille ettekanne </a> </li> <li> <b>09.01.2015</b> <a href="http://ettas.ee/files/docs/Ttervishoiu_teenuse_korraldamine_ettevttes.pdf">Tööinspektor Egle Heimoneni ettekanne</a> </li> <li> <b>09.01.2015</b> <a href="http://ettas.ee/files/docs/Ttervishoiuteenuse_korraldamine_ettevttes_2013_kokkuvte.pdf">Tööinspektsiooni sihtkontrolli kokkuvõte</a> </li> <li> <b>26.10.2007</b> <a href="http://ettas.ee/files/docs/protokoll26_10_07.doc">ETTAS koosoleku protokoll </a> </li> <li> <b>07.03.2008</b> <a href="http://ettas.ee/files/docs/ettas070308protokoll.doc">ETTAS koosoleku protokoll </a> </li> <li> <b>27.05.2011</b> <a href="http://ettas.ee/files/docs/Occupational_hygiene_and_indoor_air.pptx">ETTAS koosoleku ettekanne</a> (<a href="http://ettas.ee/files/docs/ettas_pilt_1.JPG">pilt1</a>, <a href="http://ettas.ee/files/docs/ettas_pilt_2.JPG">pilt2</a>) </li> </ul> </div> <footer> <hr /> <p> © 2017 <NAME> </p> </footer> </body> </html> <file_sep><?php include "header.php"; ?> <div class="container rounded"> <div class="page-header"> <h3><b>Liikmed</b></h3> </div> <h4><b>Juhatus</b></h4> <ul> <li> <NAME> - juhatuse esimees </li> <li> Ahe Vilkis </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> Ülle Lahe </li> <li> <NAME> </li> </ul> <h4><b>Liikmed</b></h4> <ul> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> - Toetajaliige </li> <li> <NAME> </li> <li> <NAME> - Toetajaliige </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> Argo Soon </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> Ene-Reet Soonets - Toetajaliige </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> Hedy-<NAME> </li> <li> <NAME> </li> <li> Hubert-<NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME>-Rannit </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> - Toetajaliige </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> - Toetajaliige </li> <li> Mare-Reet Urb </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> - Toetajaliige </li> <li> Oivo Rein - Toetajaliige </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> - Toetajaliige </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME> </li> <li> <NAME>ember </li> </ul> <p> Liikmemaksu on võimalik tasuda ETTAS arvelduskontole EE672200221045581473 Swedbankis. </p> <p></p> <p> Liikmemaksu suurus alates 2014 on 30€ </p> </div> <footer> <hr /> <p> © 2017 <NAME> </p> </footer> </body> </html>
20514c986544c6d50c1c4bb098968013cbee68b1
[ "PHP" ]
16
PHP
KristjanTs/ettas
a295d0198a76d98867e913b240e86622c2a5c38c
c84b9653ed5c414790215df8670931b3bbbaa4e1
refs/heads/master
<repo_name>robbie-c/babel-env-var<file_sep>/README.md # babel-env-var Inline environment variables (or .env files) at build time # Caveat Like many babel-based approaches to .env files, this will not always pick up changes, and this can be particularly time-wasting or even dangerous. The author @robbie-c does not recommend this type of approach any more, and instead would suggest alternatives. Some include: * Autogenerated config files containing whatever whitelisted env vars you would like to include. These can be added to a watchman watchlist or similar. * For a react-native app you can use build variants, and pull in those variables into JS code. * Basically like infinity other approaches. # Quick Start Add something like this to your babel config: ```javascript module.exports = function(api) { api.cache(true); return { plugins: [ [ require("babel-env-var"), { dotEnvDir: path.resolve(__dirname), whitelist: ["MY_ENV_VAR"], defaults: { MY_ENV_VAR: "some important environment variable" } } ] ] } }; ``` Then in your code: ```javascript import { MY_ENV_VAR } from "babel-env-var/imports"; console.log(MY_ENV_VAR); ``` <file_sep>/imports.d.ts interface EnvVar { [x: string]: any; } declare const envVar: EnvVar; export = envVar;
65b117a8baed968ed65de95f2e467e8002ec9de1
[ "Markdown", "TypeScript" ]
2
Markdown
robbie-c/babel-env-var
8ed872320be1b735d8f6c671d68271af8c58dc93
e35de345251a50f12e48730bfc003c6df1ca9b89
refs/heads/master
<repo_name>haobtc/bixin-api<file_sep>/src/bixin_api/contrib/django_app/admin.py from django.contrib import admin # Register your models here. from . import models admin.site.register( ( models.BixinUser, models.Event, models.Deposit, models.Withdraw, ) ) <file_sep>/src/bixin_api/storage/abstract.py class NaiveStorageBackend: def set(self, key, value, expire_at): pass def get(self, key, require_unexpired=True): pass def delete(self, key): pass <file_sep>/examples/flask/app.py from io import BytesIO from flask import Flask, send_file, request, jsonify from redis import Redis import qrcode from bixin_api import Client from bixin_api.event import make, LoginEvent from bixin_api.storage.redis import RedisStore from bixin_api.utils import login BIXIN_CONF = dict( name="your_vendor_name", secret="secret", aes_key="aes_key", ) redis_client = Redis() store = RedisStore(redis_client) bixin_client = Client( vendor_name=BIXIN_CONF['name'], secret=BIXIN_CONF['secret'], access_token=None, ) session_id = "1" app = Flask(__name__) def mk_qrcode(url): with BytesIO() as f: qrcode.make(url).save(f) return f @app.route('/api/v1/u/events/', methods=['POST']) def callback(): event = make(request.data, aes_key=BIXIN_CONF['aes_key']) if not isinstance(event, LoginEvent): return {} session = login.get_unexpired_session( storage_backend=store, session_id=event.qr_code_id, ) if session is None: return {} session = login.mark_session_as_bind(session=session) login.save_session(store, session) return "" @app.route('/qr_code/') def qr_code(): session = login.get_or_create_session( storage_backend=store, bixin_client=bixin_client, session_id=session_id, ) session.save() fp = mk_qrcode(session.url) return send_file( fp, mimetype='image/png', ) @app.route('/qr_code/status/') def qr_code_status(): session = login.get_unexpired_session( storage_backend=store, session_id=session_id, ) if session.is_bind: # login the user here and delete the qrcode record, anyway data = { "session_id": session_id, 'status': "already bind", } else: data = { "session_id": session_id, 'status': 'not bind yet', } return jsonify(data) app.run(debug=False, host='0.0.0.0', port=2333) <file_sep>/src/setup.py import os from setuptools import setup, find_packages here = os.path.dirname(os.path.abspath(__file__)) requires = ( "pendulum>=1.3.2", "requests", "pycrypto", 'gql', ) setup( name='bixin-api', version='0.0.4', packages=find_packages(here), license='MIT', author='the-chosen-ones', description='BixinAPI api wrapper', install_requires=requires, ) <file_sep>/src/bixin_api/models.py import json class PlatformUser: """ Data is like: { "username": "unique-internal-username", "verified": True, "vendor.BTC.cash": "0", "vendor.BTC.hold": "0", "vendor.BCC.hold": "0", "vendor.ETH.cash": "0", "vendor.ETH.hold": "0", "vendor.CNY.cash": "0", "vendor.BCC.cash": "0", "vendor.CNY.hold": "0", "target_id": "8c82ca5cf0374185a663cf9bc298f65e", "avatar_url": "https://ojjwxmb4j.qnssl.com/upload/2017/09/28/3f8742a776b24e10ab196a5449737c3e.png-thumb", "lock": { "is_locked": False, "reason": "", "endtime": 0 }, "fullname": "the-display-name", "id": 125103, } """ def __init__( self, id, username, verified, target_id, avatar_url, lock, fullname, openid=None, **vendor_assets ): self.openid = openid self.id = id self.username = username self.verified = verified self.target_id = target_id self.avatar_url = avatar_url self.lock = lock self.fullname = fullname self.vendor = vendor_assets def is_verified(self): """ If a user passed all kinds of identification it will be true, else false. """ return self.verified @classmethod def from_raw(cls, json_resp): return cls(**json_resp) def as_dict(self): return dict( id=self.id, username=self.username, verified=self.verified, target_id=self.target_id, avatar_url=self.avatar_url, lock=self.lock, fullname=self.fullname, vendor=self.vendor, openid=self.openid, ) class BixinVendorUser: """ type VendorUserInfo { openid: String target_id: String username: String fullname: String avatar_url: String verified: Boolean is_locked: Boolean wallet_balance: JSONString vendor_fund_balance: JSONString verifiedInfo: userVerifyInfo } """ def __init__( self, openid, target_id, username, fullname, avatar_url, verified, is_locked, wallet_balance, vendor_fund_balance, verifiedInfo, ): self.openid = openid self.target_id = target_id self.username = username self.fullname = fullname self.avatar_url = avatar_url self.verified = verified self.is_locked = is_locked self.wallet_balance = json.loads(wallet_balance) if wallet_balance else {} self.vendor_fund_balance = json.loads(vendor_fund_balance) if vendor_fund_balance else {} self.verified_info = verifiedInfo <file_sep>/src/bixin_api/contrib/django_app/api.py from decimal import Decimal from bixin_api.client import PubAPI from .config import get_client def get_vendor_address(symbol): client = get_client() address = client.get_first_vendor_address(currency=symbol) return address def mk_transfer_in(user_id, symbol, amount, address=None): """ 数字货币还款/添加质押物 """ from bixin_api.contrib.django_app.models import Deposit from bixin_api.contrib.django_app.models import BixinUser if address is None: address = get_vendor_address(symbol) deposit = Deposit.objects.create( amount=amount, symbol=symbol, user=BixinUser.objects.get(openid=user_id), address=address, ) return deposit.order_id, address def mk_transfer_out(user_id, symbol, amount): from bixin_api.contrib.django_app.models import Withdraw from bixin_api.contrib.django_app.models import BixinUser withdraw = Withdraw.objects.create( address=None, symbol=symbol, amount=amount, user=BixinUser.objects.get(openid=user_id) ) return withdraw.order_id def get_transfer_status(order_id): """ :returns: 'SUCCESS' or 'PENDING' """ from bixin_api.contrib.django_app.models import Deposit deposit = Deposit.objects.get(order_id=order_id) return deposit.status def subscribe_transfer_event(callback): """ callback(order_id, order_type, order_status) order_status will be 'SUCCESS' or 'FAILED' order_type will be 'transfer_in' or 'transfer_out' """ from .registry import register_callback assert callable(callback) register_callback(callback) def get_exchange_rate(base_coin: str, quote: str) -> Decimal: api = PubAPI() ret = api.get_price(base_coin.upper(), quote.upper()) return Decimal(ret) <file_sep>/src/bixin_api/contrib/django_app/management/commands/sync_deposit.py from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'sync deposit order for once' def handle(self, *args, **options): from bixin_api.contrib.django_app.synchronizers import sync_transfer_to_deposit sync_transfer_to_deposit() self.stdout.write( self.style.SUCCESS("succeed") ) <file_sep>/src/bixin_api/contrib/django_app/urls.py from django.urls import ( path, ) from . import views urlpatterns = [ path('events_callback/', views.events_view), path('test/transfer_in/', views.transfer_debug_qr_code), path('test/transfer_out/', views.transfer_out), ] <file_sep>/src/bixin_api/utils/login.py from collections import namedtuple import json import time from ..storage.abstract import NaiveStorageBackend __KEY_PREFIX = "login." LoginSession = namedtuple( "LoginSession", ( 'session_id', 'url', 'is_bind', 'expire_at', 'bixin_user_id', ), ) def _get_save_key(key): return "%s%s" % (__KEY_PREFIX, key) def save_session(storage_backend, session: LoginSession): save_key = _get_save_key(session.session_id) storage_backend.set( save_key, value=json.dumps(session._asdict()), expire_at=session.expire_at, ) def delete_session(storage_backend, session_id): """ :type storage_backend: bixin_api.storage.abstract.NaiveStorageBackend """ key = _get_save_key(session_id) return storage_backend.delete(key) def mark_session_as_bind(session: LoginSession): session_dict = session._asdict() session_dict.pop('is_bind') return LoginSession( session.is_bind, **session_dict ) def create_session( session_id, url, expire_at=None, bixin_user_id=None, ): return LoginSession( session_id=session_id, url=url, is_bind=False, expire_at=expire_at or time.time() + 360, bixin_user_id=bixin_user_id, ) def get_or_create_session( storage_backend, bixin_client, session_id, expire_at=None, ): """ :type storage_backend: bixin_api.storage.abstract.NaiveStorageBackend :type bixin_client: bixin_api.client.Client """ assert isinstance(storage_backend, NaiveStorageBackend) session = get_unexpired_session(storage_backend, session_id) if session_id is not None: return session login_url = bixin_client.get_login_qr_code( qr_code_id=session_id, is_app=True, ) session = create_session( session_id=session_id, url=login_url, expire_at=expire_at, ) save_session(storage_backend, session) return session def get_unexpired_session(storage_backend, session_id): """ Return None if no result. """ key = _get_save_key(session_id) data = storage_backend.get(key) if data is not None: return LoginSession(**json.loads(data)) return None <file_sep>/src/bixin_api/contrib/django_app/management/commands/create_test_bixin_user.py from django.core.management.base import BaseCommand def create_bixin_user(): from bixin_api.contrib.django_app.models import BixinUser user, created = BixinUser.objects.get_or_create( openid='openid_example', defaults=dict( username="hi-iam-user", target_id='111111', ) ) return user class Command(BaseCommand): help = 'Closes the specified poll for voting' def handle(self, *args, **options): create_bixin_user() self.stdout.write( self.style.SUCCESS("succeed") ) <file_sep>/ChangeLog.md + Thu Apr 19 CST 2018 + Rename package to bixin_api + Rename `login/utils/login.mk_qr_code_cls` to `mk_login_session_cls` + Rename `poim_user_id` of `LoginSession` to `bixin_user_id` + Tue Apr 24 CST 2018 + Refactor LoginSession as standlone functions + Give example for flask-login <file_sep>/src/bixin_api/exceptions.py from functools import wraps DEFAULT_CODE = -1 class APIError(ValueError): def __init__(self, msg, code=DEFAULT_CODE): self.code = code super(APIError, self).__init__(msg) class APIErrorCallFailed(APIError): """ Http read timeout will cause this failure. In case of read-timeout, we can not know the status of our api-call. """ pass class APIErrorCallStatusUnknown(APIError): """ Http read timeout will cause this failure. In case of read-timeout, we can not know the status of our api-call. """ pass def normalize_network_error(func): from requests import exceptions as exc call_failures = ( exc.HTTPError, exc.ConnectTimeout, ) call_status_unknown = ( exc.ReadTimeout, ) @wraps(func) def decorated(*args, **kwargs): try: return func(*args, **kwargs) except exc.RequestException as e: if isinstance(e, call_failures): raise APIErrorCallFailed( msg=str(e), ) elif isinstance(e, call_status_unknown): raise APIErrorCallStatusUnknown( msg=str(e) ) else: raise return decorated <file_sep>/src/bixin_api/contrib/django_app/models.py import uuid from .fields import BixinDecimalField, JsonField from django.db import models def hex_uuid(): return uuid.uuid4().hex class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True, db_index=True) updated_at = models.DateTimeField(auto_now=True, db_index=True) class Meta: abstract = True class BixinUser(BaseModel): """ Only stable properties will be stored here. """ username = models.CharField(max_length=200, blank=True, null=True, default='') target_id = models.CharField(max_length=32, unique=True, null=True) openid = models.CharField(max_length=32, unique=True, null=True, db_index=True) class Deposit(BaseModel): STATUS_CHOICES = [(x, x) for x in ['PENDING', 'SUCCESS', 'FAILED']] order_id = models.CharField(default=hex_uuid, max_length=64, db_index=True) symbol = models.CharField(max_length=32) status = models.CharField(max_length=32, choices=STATUS_CHOICES, default='PENDING') amount = BixinDecimalField(default=0) address = models.CharField(max_length=128) user = models.ForeignKey( BixinUser, on_delete=models.CASCADE, related_name='deposit' ) @property def order_type(self): return 'transfer_in' @property def is_pending(self): return self.status == 'PENDING' def mark_as_succeed(self, amount=None): self.status = 'SUCCESS' if amount is not None: self.amount = amount class Withdraw(BaseModel): STATUS_CHOICES = [(x, x) for x in ['PENDING', 'SUCCESS', 'FAILED']] order_id = models.CharField( default=hex_uuid, max_length=64, db_index=True ) address = models.CharField(max_length=128, null=True, blank=True) symbol = models.CharField(max_length=32) status = models.CharField(max_length=32, choices=STATUS_CHOICES, default='PENDING') amount = BixinDecimalField(default=0) user = models.ForeignKey( BixinUser, on_delete=models.CASCADE, related_name='withdraw' ) def __str__(self): return '<withdraw - id: {} symbol: {} amount {} user_id: {}>'.format( self.order_id, self.symbol, self.amount, self.user.id ) def __unicode__(self): return self.__str__() @classmethod def get_pending_ids(cls): return cls.objects.filter(status='PENDING').values('order_id', 'user__id') @property def order_type(self): return 'transfer_out' def as_transfer_args(self): data = { 'currency': self.symbol, 'category': self.order_type, 'amount': str(self.amount), 'client_uuid': self.order_id, 'openid': self.user.openid, } return data @property def is_pending(self): return self.status == 'PENDING' def mark_as_succeed(self): self.status = 'SUCCESS' self.save() def mark_as_failed(self): self.status = 'FAILED' self.save() class Event(models.Model): STATUS_CHOICES = [(x, x) for x in ['RECEIVED', 'PROCESSED']] status = models.CharField( max_length=32, choices=STATUS_CHOICES, default='RECEIVED', ) event_id = models.IntegerField(db_index=True) vendor_name = models.CharField(max_length=50) subject = models.CharField(max_length=32, db_index=True) payload = JsonField(null=True, blank=True, max_length=5000) uuid = models.CharField(max_length=50) def __str__(self): return '{}'.format(self.event_id) <file_sep>/src/bixin_api/contrib/django_app/decorators.py from django.conf import settings from functools import wraps from django.http import HttpResponseNotFound def require_debug(view_fn): @wraps(view_fn) def wrapped(*args, **kwargs): if not settings.DEBUG: return HttpResponseNotFound() return view_fn(*args, **kwargs) return wrapped <file_sep>/src/bixin_api/storage/redis.py import time from .abstract import NaiveStorageBackend class RedisStore(NaiveStorageBackend): _prefix = "bixin_api." def __init__(self, redis_client): """ :type redis_client: redis.Redis """ self.client = redis_client def _get_key(self, the_key): return "%s%s" % (self._prefix, the_key) @classmethod def get_ttl(cls, expire_at): now = time.time() ttl_seconds = expire_at - now if ttl_seconds < 0: ttl_seconds = 0 return int(ttl_seconds) def set(self, key, value, expire_at): key = self._get_key(key) ttl = self.get_ttl(expire_at=expire_at) return self.client.setex(name=key, value=value, time=ttl) def get(self, key, require_unexpired=True): key = self._get_key(key) return self.client.get(key) def delete(self, key): key = self._get_key(key) return self.client.delete(key) <file_sep>/src/bixin_api/client.py from datetime import timedelta from threading import Lock import uuid from urllib.parse import urljoin, urlencode import pendulum import requests from bixin_api.models import BixinVendorUser from gql import gql, Client as GQLClient from gql.transport.requests import RequestsHTTPTransport from .constants import PLATFORM_SERVER from .exceptions import APIErrorCallFailed, normalize_network_error from . import constants as csts class Client: # _bixin_ua = 'bixin_android/2016122600 (Channel/bixin;Version/1.0.0)' _bixin_ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' def __init__(self, vendor_name, secret, access_token=None, server_url=None): self.vendor_name = vendor_name self.secret = secret self.server_url = server_url or PLATFORM_SERVER self.default_timeout = 15 self.session = requests.session() self._token = access_token self._token_expired_at = pendulum.now() @property def access_token(self): with Lock(): if self._token is not None: if self._token_expired_at < pendulum.now(): return self._token self._token, self._token_expired_at = self.fetch_access_token() return self._token def fetch_access_token(self): path = '/platform/token?vendor={vendor}&secret={secret}'.format( vendor=self.vendor_name, secret=self.secret ) url = urljoin(self.server_url, path) resp = self.session.get(url, timeout=self.default_timeout) if resp.status_code == 200: a = resp.json() expired_at = pendulum.now() + timedelta(seconds=a['expire_in']) access_token = a['access_token'] else: raise APIErrorCallFailed( code=resp.status_code, msg=resp.text ) self._token = access_token self._token_expired_at = expired_at return access_token, expired_at def get_login_qr_code(self, qr_code_id, is_app=False): assert isinstance(qr_code_id, str) base_url = csts.QR_LOGIN_URL protocol = "{}/qrcode/?uuid={}:{}".format( base_url, self.vendor_name, qr_code_id, ) if is_app: protocol = "bixin://login/confirm?{}".format(urlencode({'url': protocol})) return protocol def request_platform(self, method, path, params=None, client_uuid=None, kwargs=None): params = params or {} params['access_token'] = self.access_token url = urljoin(self.server_url, path) if kwargs is None: kwargs = {} kwargs.update(dict(timeout=self.default_timeout)) if method == 'GET': body = urlencode(params) if body: url = '%s?%s' % (url, body) r = requests.get(url, **kwargs) else: # POST cu = params.get('client_uuid', client_uuid) or uuid.uuid4().hex params['client_uuid'] = cu kwargs['data'] = params r = requests.post(url, **kwargs) if r.status_code == 200: return r.json() if r.status_code == 400: data = r.json() if 'access_token' in data: return self.request_platform(method, path, params=params) raise APIErrorCallFailed(code=r.status_code, msg=data) raise APIErrorCallFailed(code=r.status_code, msg=r.text) def get_user_by_im_token(self, user_token): url = '/platform/api/v1/user/im_token/{}/'.format(user_token) url = urljoin(self.server_url, url) headers = { 'User-Agent': self._bixin_ua } resp = self.request_platform( 'GET', url, params={'ua': self._bixin_ua}, kwargs={'headers': headers} ) return resp def get_user(self, user_id): user_info = self.request_platform('GET', '/platform/api/v1/user/%s' % user_id) return user_info def get_user_list(self, offset=0, limit=100): params = { 'offset': offset, 'limit': limit, } return self.request_platform('GET', '/platform/api/v1/user/list', params=params) def get_transfer(self, client_uuid): return self.request_platform( 'GET', '/platform/api/v1/transfer/item', {'client_uuid': client_uuid}, ) def get_transfer_list(self, offset=0, limit=100, status=None, type=None, order='desc'): """ :param type: 'deposit' or None return { 'has_more': False, 'items': [ { 'amount': '0.001', 'args': {'order_id': 'f99cbe34a3064bb398d0c49c1eb02120', 'outside_transfer_type': 'SINGLE', 'transfer_type': ''}, 'category': '', 'client_uuid': '5aa055014cbe4edbbae70432ea912cab', 'currency': 'ETH', 'id': 1169842, 'note': '', 'reply_transfer_id': 0, 'status': 'SUCCESS', 'user.id': 125103, 'vendor': 'bitexpressbeta' }, { 'amount': '0.001', 'args': {'order_id': '0bd811cea8c041b992264d1950a2b8b7', 'outside_transfer_type': 'SINGLE', 'transfer_type': ''}, 'category': '', 'client_uuid': '88fd4f0888044043be01ed05d479921c', 'currency': 'ETH', 'id': 1169807, 'note': '', 'reply_transfer_id': 0, 'status': 'SUCCESS', 'user.id': 125103, 'vendor': 'bitexpressbeta' }, ] } """ return self.request_platform( 'GET', '/platform/api/v1/transfer/list', { 'offset': offset, 'limit': limit, 'status': status, 'type': type, 'order': order } ) def send_withdraw(self, currency, amount, user_id, category=None, client_uuid=None): data = dict( currency=currency, category=category, amount=amount, user=user_id, client_uuid=client_uuid, ) r = self.request_platform( 'POST', '/platform/api/v1/withdraw/create', params=data, ) return True def get_deposit_protocol(self, currency, amount, order_id): url = 'bixin://currency_transfer/' \ '?target_addr={address}' \ '&amount={amount}' \ '&currency={currency}' \ '&order_id={order_id}' \ '&category=deposit' address = self.get_first_vendor_address(currency=currency) url = url.format( order_id=order_id, address=address, currency=currency, amount=amount, ) return url def get_first_vendor_address(self, currency='BTC'): resp = self.get_vendor_address_list( currency=currency, ) assert len(resp['items']) > 0 address = resp['items'][0] return address def get_vendor_address_list(self, currency='BTC', offset=0, limit=20): params = { 'offset': offset, 'limit': limit, 'currency': currency } return self.request_platform('GET', '/platform/api/v1/address/list', params) def get_jsapi_ticket(self): return self.request_platform('GET', '/platform/api/v1/ticket/jsapi') def pull_event(self, since_id, limit=20): payload = {'since_id': since_id, 'limit': limit} return self.request_platform('GET', '/platform/api/v1/event/list', payload) class PubAPI: _price_path = '/api/v1/currency/ticker?symbol={base}_{quote}' def __init__(self, server_base_url=None): self.session = requests.session() self.server_url = server_base_url or PLATFORM_SERVER @normalize_network_error def get_price(self, base, quote): """ :return: { ok: true, data: { price: "13.06400384", is_converted: true } } :rtype: float """ path = self._price_path.format( base=base.lower(), quote=quote.lower() ) url = urljoin( self.server_url, path, ) resp = self.session.get(url) data = resp.json() if not data['ok']: raise APIErrorCallFailed( msg="Failed to fetch given price for {} {}".format( base, quote ), ) return data['data']['price'] class GraphQLClient(Client): _gql_server_url = 'https://bixin.im/platform/graphql' _gql_ua = 'bixin_android/2018051401 (Channel/bixin; com.bixin.bixin_android; Version/3.1.3)' def __init__(self, vendor_name, secret, access_token=None, server_url=None, gql_server_url=None): super(GraphQLClient, self).__init__( vendor_name=vendor_name, secret=secret, access_token=access_token, server_url=server_url, ) self.gql_server_url = gql_server_url or self._gql_server_url transport = RequestsHTTPTransport( url=self.gql_server_url, use_json=True, ) self.gql = GQLClient(transport=transport, fetch_schema_from_transport=True) def get_user_by_im_token(self, user_token): """ ret: {'userByImToken': {'avatar_url': None, 'fullname': '', 'is_locked': False, 'openid': 'b97812328ead4d57b992f18d3f168ccb', 'target_id': 'f2a7c018ed4a47b999e1c4893da42d79', 'username': 'bx_u6962575070', 'vendor_fund_balance': None, 'verified': False, 'verifiedInfo': {'bankcard': '{ "verified": false, 'card_number': '', # should be exist if true }', 'face': '{"verified": false}', 'idcard': '{ "verified": false, 'real_name': '', # should be exist if true 'card_number': '', # should be exist if true }', 'passport': '{ "verified": false, 'first_name': '', 'last_name': '', 'country': '', 'card_number': '', }', 'phone': '+8615650758818'}, 'wallet_balance': '{"DASH": "0", "AE": "0", "LTC": "0", ' '"READ": "0", "DOGE": "0", "ELF": "0", ' '"DAI": "0", "EOS": "0", "TRX": "0", ' '"AVH": "0", "MKR": "0", "BTC": "0", ' '"VEN": "0", "FGC": "0", "ETH": "0", ' '"RDN": "0", "USDT": "0", "ENU": "0"}'}} """ access_token = self.access_token query = """ query { userByImToken(access_token: "%s", im_token: "%s", ua_str:"%s"){ openid target_id username fullname avatar_url verified is_locked wallet_balance vendor_fund_balance verifiedInfo{ phone idcard passport bankcard face } } } """ % (access_token, user_token, self._gql_ua) query = gql(query) ret = self.gql.execute(query) return BixinVendorUser( **ret['userByImToken'], ) def send_verification_sms(self, phone: str, code) -> bool: if not phone.startswith('+86'): phone = "+86" + phone query = """ mutation { sendSmsByPhone( phone: "%s", sms_data:{sms_args: "[('code', '%s')]", notify_type: "verify_code"}, access_token: "%s" ){ ok } } """ % (phone, code, self.access_token) query = gql(query) ret = self.gql.execute(query) return ret['sendSmsByPhone']['ok'] def transfer2openid(self, currency, amount, openid, category=None, client_uuid=None): client_uuid = '"%s"' % client_uuid if client_uuid else 'null' category = '"%s"' % category if category else 'null' query = """ mutation{ withdrawByOpenid( withdraw_data: { currency: "%s", amount: "%s", category: %s, client_uuid: %s, }, openid: "%s", access_token: "%s", ){ transfer{ status } } } """ % ( currency, amount, category, client_uuid, openid, self.access_token ) query = gql(query) ret = self.gql.execute(query) return ret['transfer']['status'] == 'SUCCESS' def get_transfer_list(self, offset=0, limit=100, status=None, type=None, order='desc'): """ return [ {'order_id': '237e3920c6f04923968d0a8ec096613d', 'status': 'SUCCESS'} {'order_id': None, 'status': 'SUCCESS'} ] """ assert order in ('desc', 'asc') query = """ query { transfers( access_token: "%s", limit: %s, offset: %s, order: %s, ){ hasMore totalCount detail { order_id status created_at } } } """ % (self.access_token, limit, offset, '"%s"' % order) query = gql(query) ret = self.gql.execute(query) return ret['transfers']['detail'] <file_sep>/src/bixin_api/contrib/README.md bixin-api django-app -------------------- # 安装配置 ## 创建Vendor 去 https://bixin.im/openplatform/ 创建Vendor并获取币信 的 `vendor_name` 和 `secret`以及 `aes_key` 回调的URL可以稍后再填写 ## 配置django-app 添加币信config到 `settings.py` 或者 `local_settings.py` ``` BIXIN_CONFIG = { 'client': { 'server_url': None, # None is valid here 'vendor_name': '', 'secret': '', 'aes_key': '', }, 'graphql_client': { 'server_url': None, # None is valid here } } ``` 然后在 `settings.py` 内启用币信应用 ``` INSTALLED_APPS += [ 'bixin_api.contrib.django_app', ] ``` 配置回调地址, 打开 `urls.py` , 在urlpatterns内添加 ``` path('bixin/', include('bixin_api.contrib.django_app.urls')) ``` # 测试 ``` make check ``` 测试服务器和开放平台配置 callback 地址填 `http://your-hostname.com/bixin/events_callback/` 即可 # 开发约定 ## 更新数据模型后 上线后需要一直track变更,每次数据更新的都需要生成migrations文件, 以便能使用django migration来维护线上数据结构的更新升级。 ``` make make-migrations ``` 将生成的文件提交到代码库内,并不要手工修改这些文件:) <file_sep>/src/bixin_api/contrib/django_app/registry.py import logging import django.dispatch order_done = django.dispatch.Signal( providing_args=['order_id', 'order_type', 'order_status'], ) order_callback_registry = set() def register_callback(callback): if callback in order_callback_registry: return order_callback_registry.add(callback) def send_event(order_id, order_type, order_status): order_done.send( sender="order_manager", order_id=order_id, order_type=order_type, order_status=order_status, ) def _call(sender, order_id=None, order_type=None, order_status=None, **kwargs): for fn in order_callback_registry: try: fn(order_id, order_status) except Exception: logging.exception( "Failed to call callback %s" % fn.__name__ ) order_done.connect(_call, dispatch_uid="order_status_update") __all__ = ( 'register_callback', 'send_event', ) <file_sep>/src/Makefile re-build: rm -fr ./dist/* python setup.py bdist_wheel python setup.py sdist upload-pkgs: twine upload ./dist/*.tar.gz twine upload ./dist/*.whl <file_sep>/src/bixin_api/contrib/django_app/utils.py import pendulum def utc_now(): return pendulum.now('UTC') <file_sep>/src/bixin_api/shortcuts.py import sys def get_access_token(vendor_name, secret_key): from bixin_api import Client client = Client(vendor_name=vendor_name, secret=secret_key) token = client.fetch_access_token() print(token) if __name__ == '__main__': get_access_token(*sys.argv[1:]) <file_sep>/src/bixin_api/contrib/django_app/config.py from bixin_api import Client from bixin_api.client import GraphQLClient _BASE_KEYS = { 'client', 'graphql_client', } _CLIENT_REQUIRED_KEYS = { 'vendor_name', 'secret', 'aes_key', } _GRAPHQL_REQUIRED_KEYS = {} def get_client_config(): from django.conf import settings if not hasattr(settings, 'BIXIN_CONFIG'): raise ValueError("BIXIN_CONFIG should be set in django settings.") if 'client' not in settings.BIXIN_CONFIG: raise ValueError("client config is required") bixin_config = settings.BIXIN_CONFIG['client'] for key in _CLIENT_REQUIRED_KEYS: if key not in bixin_config: raise ValueError( "config <%s> should be set in client config" ) return bixin_config def get_gql_config(): from django.conf import settings if not hasattr(settings, 'BIXIN_CONFIG'): raise ValueError("BIXIN_CONFIG should be set in django settings.") if 'client' not in settings.BIXIN_CONFIG: raise ValueError("client config is required") bixin_config = settings.BIXIN_CONFIG['graphql_client'] for key in _GRAPHQL_REQUIRED_KEYS: if key not in bixin_config: raise ValueError( "config <%s> should be set in graphql_client config" ) return bixin_config def get_client(): config = get_client_config() return Client(config['vendor_name'], config['secret'], server_url=config.get('server_url')) def get_gql_client(): gql_config = get_gql_config() client_config = get_client_config() return GraphQLClient( client_config['vendor_name'], client_config['secret'], server_url=client_config.get('server_url'), gql_server_url=gql_config.get('server_url') ) <file_sep>/src/bixin_api/constants.py PLATFORM_SERVER = 'https://bixin.im' QR_LOGIN_URL = 'https://login.bixin.im' BIXIN_APP_HOST = 'https://openapi.bixin.im'<file_sep>/src/bixin_api/contrib/django_app/management/commands/execute_withdraw.py import time from django.core.management.base import BaseCommand from bixin_api.contrib.django_app.synchronizers import ( execute_withdraw, WithdrawExecutor ) def main(): t = WithdrawExecutor() t.start() print("Start syncing...") while True: try: time.sleep(2) except KeyboardInterrupt: print("Exiting...please wait and don't press CRTL+C") t.stop() t.join() exit(0) class Command(BaseCommand): help = 'sync deposit order for once' def add_arguments(self, parser): parser.add_argument( '--once', action='store_true', dest='once', help='only run once', ) def handle(self, *args, **options): once = options.pop('once', False) if once: execute_withdraw() self.stdout.write( self.style.SUCCESS("succeed") ) else: main() <file_sep>/src/bixin_api/contrib/django_app/synchronizers.py import decimal import logging import time from threading import Thread from bixin_api.contrib.django_app.config import get_gql_client from django.db import transaction from .models import Deposit, Withdraw from .registry import send_event client = get_gql_client() def sync_transfer_to_deposit(): transfers = client.get_transfer_list(status='SUCCESS', limit=20, type='deposit', order='desc') for transfer in transfers: deposit_id = transfer['order_id'] if not deposit_id: continue with transaction.atomic(): try: deposit = Deposit.objects.select_for_update().get( order_id=deposit_id, ) except Deposit.DoesNotExist: continue if deposit.status != 'PENDING': continue if transfer['status'] != 'SUCCESS': continue deposit.mark_as_succeed() send_event(deposit.order_id, deposit.order_type, deposit.status) def execute_withdraw(): pending_ids = Withdraw.get_pending_ids() for order in pending_ids: order_id = order['order_id'] with transaction.atomic(): try: withdraw = Withdraw.objects.select_for_update().get( order_id=order_id, ) except Withdraw.DoesNotExist: continue if withdraw.status != 'PENDING': continue # TODO(winkidney): user may withdraw twice if the worker killed # This known issue should be fixed. try: client.transfer2openid( **withdraw.as_transfer_args() ) except Exception: logging.exception( "Failed to do withdraw (transfer-out) operation for %s" % withdraw, ) withdraw.mark_as_failed() else: withdraw.mark_as_succeed() send_event(withdraw.order_id, withdraw.order_type, withdraw.status) class StoppableThread(Thread): def __init__(self): super(StoppableThread, self).__init__() self._stopped = False self.setDaemon(True) def stop(self): self._stopped = True class TransferSync(StoppableThread): def run(self): while not self._stopped: time.sleep(0.05) try: sync_transfer_to_deposit() except Exception: logging.exception( "Failed to sync deposit orders:" ) class WithdrawExecutor(StoppableThread): def run(self): while not self._stopped: time.sleep(0.2) try: execute_withdraw() except Exception: logging.exception( "Failed to sync deposit orders:" ) <file_sep>/src/bixin_api/contrib/django_app/apps.py from django.apps import AppConfig class BixinEventsConfig(AppConfig): name = 'bixin_events' <file_sep>/src/bixin_api/contrib/django_app/management/commands/order_sync_worker.py import time from bixin_api.contrib.django_app.synchronizers import TransferSync from django.core.management.base import BaseCommand def main(): t = TransferSync() t.start() print("Start syncing...") while True: try: time.sleep(2) except KeyboardInterrupt: print("Exiting...please wait and don't press CRTL+C") t.stop() t.join() exit(0) class Command(BaseCommand): help = 'Closes the specified poll for voting' def handle(self, *args, **options): main() <file_sep>/README.md # BixinAPI A python wrapper for `bixin-api` ## Feature + `BixinClient` for qr-code login + User info access + Basic data model for events/user-data + `Login` implementation with Redis backend ## install `pip install bixin-api` ## Examples Please view `examples/flask/app.py` ## ChangeLog + [ChangeLog](./ChangeLog.md) ## How to subscribe to deposit and withdraw order status change Refer: ``` from bixin_api.contrib.django_app.api import ( subscribe_transfer_event, ) def fn(order_id, status): """ :param status: 'SUCCESS' or 'FAILED' """ pass subscribe_transfer_event(fn) ``` <file_sep>/src/bixin_api/__init__.py from .client import Client from .event import ( Event, LoginEvent, ) __all__ = ( 'Client', 'Event', 'LoginEvent', ) <file_sep>/src/bixin_api/event.py import json from .crypto import PRPCrypt SUB_LOGIN = 'vendor_qr_login' SUB_DEPOSIT_CREATED = 'user2vendor.created' SUBJECT_CHOICES = { SUB_LOGIN, SUB_DEPOSIT_CREATED, } class Event: """ Example data: - login: { 'event_id': 633776, 'vendor_name': 'bitexpressbeta', 'payload': { 'qr_uuid': '8a129893-3196-4ccc-93fa-02a69d1b2d7e', 'user_id': 125103 }, 'uuid': '0db56cfd74984e2eb0c254d7e6b22160', 'subject': 'vendor_qr_login', } - transfer: {'event_id': 1182650, 'payload': {'amount': '0.001', 'currency': 'ETH', 'json_args': {'order_id': '9b1f084b85514ea3b90ab4073d9df088', 'outside_transfer_type': 'SINGLE', 'transfer_type': ''}, 'note': '', 'transfer.id': 1169783, 'user.id': 125103}, 'subject': 'user2vendor.created', 'uuid': 'b2208f6dc71c4a928060f8917c8b6441', 'vendor_name': 'bitexpressbeta' } """ def __init__( self, event_id, vendor_name, payload, uuid, subject, ): self.event_id = event_id self.vendor_name = vendor_name self.payload = payload self.uuid = uuid self.subject = subject def is_valid(self, vendor_name): return vendor_name == self.vendor_name def as_dict(self): return { 'event_id': self.event_id, 'vendor_name': self.vendor_name, 'payload': self.payload, 'uuid': self.uuid, 'subject': self.subject, } class LoginEvent(Event): @property def qr_code_id(self): return self.payload['qr_uuid'] @property def user_id(self): return self.payload['user_id'] class DepositEvent(Event): @property def order_id(self): return self.payload['order_id'] _subject_event_map = { SUB_LOGIN: LoginEvent, SUB_DEPOSIT_CREATED: DepositEvent, } def instantiate_event(data): assert data['subject'] in SUBJECT_CHOICES event_cls = _subject_event_map.get(data['subject'], Event) return event_cls(**data) def make(raw_text, aes_key=None): if aes_key is not None: raw_text = PRPCrypt(key=aes_key).decrypt(raw_text) data = json.loads(raw_text) return instantiate_event(data) <file_sep>/src/bixin_api/config.py def mk_config( vendor_name, address, secret, aes_key, bot_access_token, target_id=None, ): return dict( name=vendor_name, address=address, secret=secret, aes_key=aes_key, bot_access_token=bot_access_token, target_id=target_id, ) <file_sep>/src/bixin_api/contrib/django_app/migrations/0001_initial.py # Generated by Django 2.0.5 on 2018-06-27 10:43 import bixin_api.contrib.django_app.fields import bixin_api.contrib.django_app.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='BixinUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), ('updated_at', models.DateTimeField(auto_now=True, db_index=True)), ('username', models.CharField(blank=True, default='', max_length=200, null=True)), ('target_id', models.CharField(max_length=32, null=True, unique=True)), ('openid', models.CharField(db_index=True, max_length=32, null=True, unique=True)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Deposit', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), ('updated_at', models.DateTimeField(auto_now=True, db_index=True)), ('order_id', models.CharField(db_index=True, default=bixin_api.contrib.django_app.models.hex_uuid, max_length=64)), ('symbol', models.CharField(max_length=32)), ('status', models.CharField(choices=[('PENDING', 'PENDING'), ('SUCCESS', 'SUCCESS'), ('FAILED', 'FAILED')], default='PENDING', max_length=32)), ('amount', bixin_api.contrib.django_app.fields.BixinDecimalField(decimal_places=30, default=0, max_digits=65)), ('address', models.CharField(max_length=128)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='deposit', to='django_app.BixinUser')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Event', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('status', models.CharField(choices=[('RECEIVED', 'RECEIVED'), ('PROCESSED', 'PROCESSED')], default='RECEIVED', max_length=32)), ('event_id', models.IntegerField(db_index=True)), ('vendor_name', models.CharField(max_length=50)), ('subject', models.CharField(db_index=True, max_length=32)), ('payload', bixin_api.contrib.django_app.fields.JsonField(blank=True, default='{}', max_length=5000, null=True)), ('uuid', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Withdraw', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), ('updated_at', models.DateTimeField(auto_now=True, db_index=True)), ('order_id', models.CharField(db_index=True, default=bixin_api.contrib.django_app.models.hex_uuid, max_length=64)), ('address', models.CharField(blank=True, max_length=128, null=True)), ('symbol', models.CharField(max_length=32)), ('status', models.CharField(choices=[('PENDING', 'PENDING'), ('SUCCESS', 'SUCCESS'), ('FAILED', 'FAILED')], default='PENDING', max_length=32)), ('amount', bixin_api.contrib.django_app.fields.BixinDecimalField(decimal_places=30, default=0, max_digits=65)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='withdraw', to='django_app.BixinUser')), ], options={ 'abstract': False, }, ), ] <file_sep>/src/bixin_api/contrib/django_app/views.py # -*- coding: utf-8 -*- import qrcode as qrcode from bixin_api.contrib.django_app.decorators import require_debug from bixin_api.event import make from django.db import transaction from .config import get_client_config, get_client from django.http import HttpResponseNotAllowed, JsonResponse, HttpResponse from django.views.decorators.csrf import csrf_exempt from . import models @csrf_exempt def events_view(request): if request.method != "POST": return HttpResponseNotAllowed(("POST",)) aes_key = get_client_config()['aes_key'] event = make(request.body, aes_key=aes_key) data = event.as_dict() event_id = data.pop('event_id') models.Event.objects.get_or_create( event_id=event_id, defaults=data, ) return JsonResponse({}) def mk_qrcode(url): from io import BytesIO f = BytesIO() qrcode.make(url).save(f) f.seek(0) return f @csrf_exempt @transaction.atomic @require_debug def transfer_debug_qr_code(request): """ Only work for debug. """ from bixin_api.contrib.django_app.models import Deposit, BixinUser deposit = Deposit.objects.create( amount="0.001", symbol='ETH', user=BixinUser.objects.first(), ) client = get_client() url = client.get_deposit_protocol( currency='ETH', amount='0.001', order_id=deposit.order_id, ) image = mk_qrcode(url) resp = HttpResponse( content=image, content_type="image/png" ) return resp @require_debug def transfer_out(request): from bixin_api.contrib.django_app.api import mk_transfer_out mk_transfer_out( user_id="1111111", symbol='BTC', amount=0.001, ) return HttpResponse('done')
6686fc155cec5848655ced4bbcdd8dbf9ccbf0ac
[ "Markdown", "Python", "Makefile" ]
33
Python
haobtc/bixin-api
c0c4660ff09adcf9f70d76c5dc2ff6bb314932f9
fd2a093b20d137b3d5d3ff48c3903f776ca2ce23
refs/heads/master
<file_sep>extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; extern crate noise; extern crate num; extern crate rustc_serialize; extern crate time; use piston::window::WindowSettings; use piston::event::{Event, Events}; use piston::input::{Button, Input, Key}; use glutin_window::GlutinWindow as Window; use opengl_graphics::{OpenGL, GlGraphics}; use graphics::Image; use graphics::rectangle::square; // Why pub? Because that makes the docs work. pub mod core; pub mod mapgen; pub mod model; pub mod renderer; pub mod state; use core::Config; use state::State; use renderer::{Renderer, TextureManager}; fn main() { let state = state::Game::new(); let gl_context = OpenGL::_2_1; let config = match Config::load() { Ok(config) => config, Err(e) => { println!("Couldn't load config:"); println!(" {:?}", e); return; } }; let window_settings = WindowSettings::new(config.game_title().clone(), config.window_size() ).exit_on_esc(true); let window = Window::new(gl_context, window_settings); let mut tex_mgr = TextureManager::new(); let image = Image::new().rect(square(100.0, 10.0, 64.0)); let path_to_stamos = "./data/graphics/stamos.png"; let texture = match tex_mgr.get(path_to_stamos) { Ok(john) => john, Err(e) => { println!("Couldn't load <NAME>:"); println!(" {:?}", e); return; } }; // This is the object used for drawing let mut gl = GlGraphics::new(gl_context); let mut renderer = Renderer::new(); for event in window.events() { match event { Event::Input(Input::Press(Button::Keyboard(Key::Return))) => println!("Return pressed!"), Event::Input(Input::Release(Button::Keyboard(Key::Return))) => println!("Return released!"), Event::Render(args) => { use graphics::*; gl.draw(args.viewport(), |c, gl| { clear([1.0, 1.0, 1.0, 1.0], gl); image.draw(texture, default_draw_state(), c.transform, gl); state.render(&args, gl, &mut renderer); }); }, _ => {} } } } <file_sep>* Explosions, lots of explosions! * Some sort of secondary mission. * Island name generator, using Markov chains. <file_sep>use core::{Entity, Vec2}; /// The camera pub struct Cam<'a> { /// The entity in focus in_focus: &'a Entity, } // TODO: [x] Make the camera locked to the player? (Or is this a bad idea?) impl<'a> Cam<'a> { /// Creates a new Cam fn new(focus: &'a Entity) -> Cam { Cam { in_focus: focus, } } /// Get position fn get_pos(&self) -> Vec2<f64> { self.in_focus.get_cur_pos() } } <file_sep>//! The models, i.e. game objects, such as entities, objects, items, and so on. mod data; mod player; pub use self::player::Player; <file_sep>use core::{Vec2}; use mapgen::{CHUNK_SIZE, ChunkRelCoord}; use mapgen::seed::Seed2; use noise::Seed; const ISLAND_HEIGHT: f64 = 1.4; pub struct Island { hills: Vec<Vec2<i64>>, } impl Island { /// Get overlay value. NOTE: Pos is relative to chunk coordinate. fn get_overlay(&self, pos: Vec2<i64>) -> f64 { let value = (CHUNK_SIZE as f64) / ( self.hills.iter().min_by(|&x| (*x - pos).norm()).unwrap().norm() as Vec2<f64>) * ISLAND_HEIGHT; if value < 1.0 { value } else { 1.0 } } /// Generate a the `num` island of a chunk consiting of `nhills` number of /// hills within a radius of `radius` given a seed, `seed`. fn generate_island(seed: Seed2, radius: f64, nhills: i64, chunk: Vec2<i64>, num: i64) -> Island { let hills: Vec<Vec2<i64>> = vec![]; for i in 1..nhills { hills.push(Vec2( seed.feed(0).feed(i).feed(num) .feed_vec(chunk).get() as i64, seed.feed(1).feed(i).feed(num) .feed_vec(chunk).get() as i64 )); } Island { hills: hills, } } } <file_sep>[package] name = "open_sea" version = "0.1.0" authors = ["<NAME> <<EMAIL>>", "Ticki <<EMAIL>>"] [[bin]] name = "open-sea" [dependencies] pistoncore-glutin_window = "0.1.0" piston2d-opengl_graphics = "0.1.0" rustc-serialize = "0.3.15" time = "0.1" noise = "0.1.5" piston = "0.1.4" piston2d-graphics = "0.1.4" num = "0.1.25" <file_sep>// NOTE: Object is a term for an entity or a prop. use time; use opengl_graphics::*; use graphics::*; use core::{Vec2}; /// A trait for positioned objects pub trait Position { /// Get the x coordinate fn get_pos(&self) -> Vec2<i64>; /// Set the Vec coordinate fn set_pos(&mut self, new_pos: Vec2<i64>); } // TODO: This should probably just be a Vec2, especially since you're doing // things like Dir::to_vec, and you want to allow two different // directions at once. /// The direction of a given object #[derive(Clone, Copy)] pub enum Dir { N, S, E, W, NE, NW, SE, SW, } impl Dir { fn to_vec(self) -> Vec2<i64> { match self { Dir::N => Vec2(0, 1), Dir::S => Vec2(0, -1), Dir::E => Vec2(1, 0), Dir::W => Vec2(-1, 0), Dir::NE => Vec2(1, 1), Dir::NW => Vec2(1, -1), Dir::SE => Vec2(-1, 1), Dir::SW => Vec2(-1, -1), } } /// Calculate the "locked" direction (i.e. the direction locked to the grid) fn to_locked(self) -> Dir { let mov = time::precise_time_s().round() as i64 % 2; match (self, mov) { (Dir::NE, 0) | (Dir::NW, 0) => Dir::N, (Dir::SE, 0) | (Dir::SW, 0) => Dir::S, (Dir::NE, 1) | (Dir::SE, 1) => Dir::E, (Dir::NW, 1) | (Dir::SW, 1) => Dir::W, _ => self, } } } // TODO: Dir or direction? For consistency, I temporary chose the short naming. Should we shift to // long names? What's the rust standarts? // TODO: Implement two directions at once. (See comment above.) /// A movable object pub trait Move: Position { /// Get the direction fn get_dir(&self) -> Dir; /// Set the direction fn set_dir(&mut self, new_dir: Dir); /// Is the object moving? fn is_moving(&self) -> bool; /// Can the object move? Or is it blocked? fn can_move(&self) -> bool; /// Move the object fn move_obj(&mut self, mov: Vec2<i64>) { let coord = self.get_pos(); self.set_pos(coord + mov); } fn get_cur_pos(&self) -> Vec2<f64> { Vec2::from(self.get_new_pos()) * self.get_trans_state() + Vec2::from(self.get_pos()) } /// Get new coordinate fn get_new_pos(&self) -> Vec2<i64> { // TODO: This is only temporary. Should diagonal moves be allowed or not? let mov = self.get_dir(); self.get_pos() + mov.to_vec() } /// Move object in direction. fn move_obj_dir(&mut self) { let new_coord = self.get_new_pos(); self.set_pos(new_coord) } /// Get the timestamp of the last move fn get_last_move(&self) -> f64; /// Set the timestamp of the last move fn set_last_move(&mut self, new: &f64); /// Get the speed of the object fn get_speed(&self) -> f64; /// Moves regularly fn move_reg(&mut self) { let now = &time::precise_time_s(); if self.is_moving() && self.can_move() && self.get_last_move() - now > 1.0 / self.get_speed() { self.set_last_move(now); self.move_obj_dir(); } } /// Get transitition point, which is in the interval [0,1] fn get_trans_state(&self) -> f64; /// Get animation frame fn get_animation_frame(&self) -> i16; } /// Trait for sprited objects pub trait Sprite: Move { /// Get current sprite fn get_sprite(&self) -> &Texture; /// Get width, not neccesarily the width of the sprite, but rather the space /// the given object occupies. Given in fields. fn get_width(&self) -> i16; /// Get height, see note above fn get_height(&self) -> i16; /// Get the opacity of the object fn get_opacity(&self) -> f64; // fn draw(&self, c: &Context, gl: &mut GlGraphics); } // TODO: Add event trait, for objects you can click on etc. <file_sep>use std::collections::BTreeMap; use rustc_serialize::json::Json; use core::Vec2; use model::data::error::ModelError; /// Parse occupied_tiles given by a rectangle pub fn parse(block: &Json, ret: &mut Vec<Vec2<i8>> ) -> Result<(), ModelError> { match block { &Json::Object(ref obj) => parse_2(obj, ret), _ => Err(ModelError::TypeError { obj: "\"rectangle\" key in \"occupied_tiles\"", expected: "object" }) } } /// Parse from binary tree fn parse_2(obj: &BTreeMap<String, Json>, ret: &mut Vec<Vec2<i8>> ) -> Result<(), ModelError> { if obj.len() != 2 { return Err(ModelError::WrongNumKeys { expected: 2, context: "\"rectangle\" object in \"occupied_tiles\"" }); } let type_err = |key| Err(ModelError::TypeError { obj: key, expected: "[i8, i8]" }); let mut start = None; let mut size = None; for (key, val) in obj.iter() { match key as &str { "start" => { let extract_result = extract_i8_pair(val); if let Err(()) = extract_result { return type_err( "\"start\" key in \"rectangle\" object in \"occupied_tiles\""); } start = Some(extract_result.unwrap()); }, "size" => { let extract_result = extract_i8_pair(val); if let Err(()) = extract_result { return type_err( "\"size\" key in \"rectangle\" object in \"occupied_tiles\""); } size = Some(extract_result.unwrap()); }, other => return Err(ModelError::InvalidKey { key: other.to_string(), context: "\"rectangle\" object in \"occupied_tiles\"" }) }; } // Push all the occupied tiles into `ret` let (left, top) = start.unwrap(); let (w, h) = size.unwrap(); let (right, bottom) = (left + w, top + h); let mut y = top; while y < bottom { let mut x = left; while x < right { ret.push(Vec2(x, y)); x += 1; } y += 1; } Ok(()) } // TODO: document these, not sure about their functionality fn extract_i8_pair(value: &Json) -> Result<(i8, i8), ()> { match value { &Json::Array(ref arr) => { if arr.len() != 2 { return Err(()); } Ok(( try!(extract_i8(&arr[0])), try!(extract_i8(&arr[1])) )) }, _ => Err(()) } } fn extract_i8(value: &Json) -> Result<i8, ()> { match value { // TODO refactor all these methods into Json extract module or something // TODO bounds checking &Json::I64(n) => Ok(n as i8), &Json::U64(n) => Ok(n as i8), _ => Err(()) } } <file_sep>use opengl_graphics::Texture; use core::Matter; /// Props, i.e. non dynamic objects pub trait Prop: Matter + Clone + Copy { fn get_sprite(&self) -> &Texture; } <file_sep>//! The module for the automatic map generation use noise::{Brownian2, Seed, open_simplex2}; use core::{Tile, TileMap, Vec2}; mod island; pub use self::island::{Island}; pub mod seed; mod chunk; use self::chunk::{Chunk}; use self::seed::{Seed2}; // TODO: consider just using `usize`. It /is/ an unsigned scalar. pub const CHUNK_SIZE: i64 = 128; #[allow(non_upper_case_globals)] pub const CHUNK_SIZE_usize: usize = 128; /// Chunk coordinate pub type ChunkCoord = Vec2<i64>; /// Chunk relative coordinate pub type ChunkRelCoord = Vec2<i16>; /// A map /// /// Note: It's chunked into big chunks and small chunks. /// Small chunks keeps the noise data. Big chunks /// determines the overlay layer. pub struct MapGenerator { seed: Seed2, // TODO: Use pointer to seed instead? } /// Types of big chunks pub enum ChunkType { /// Reserved for history, empty per default, but gets opened as the game is /// played. Manually designed. History, /// Automatic map generated chunk Auto, /// Manually random generated chunk Manually, /// Empty chunk Empty, } // TODO: Find out how to prevent double islands (manually generated islands) // TODO: Use Vec2 in this methods: impl MapGenerator { /// Creates a new map pub fn new(seed: Seed2) -> MapGenerator { MapGenerator { seed: seed, } } /// Get the type of the chunk fn get_chunk_type(&self, pos: ChunkCoord) -> ChunkType { let val = self.seed.feed_vec(pos).get_f64(); if val > 0.3 { ChunkType::Empty } else if val > 0.1 { ChunkType::Auto } else if val > 0.05 { ChunkType::History } else { ChunkType::Manually } } /// Get the overlay value fn get_overlay_value(&self, pos: Vec2<i64>) -> f64 { match self.get_chunk_type(pos) { ChunkType::Empty => 0.0, ChunkType::Auto => { let chunk = Chunk::generate(self.seed, pos); match chunk.islands.iter().min_by(|&x| x.get_overlay(pos)) { Some(x) => x.get_overlay(pos), None => 0.0, } } _ => 0.0, } } } impl<'a> TileMap<'a> for MapGenerator { /// Get the tile at a given point fn get_tile(&self, coord: Vec2<i64>) -> Tile<'a> { let val = (self.seed.get_noise(CHUNK_SIZE as f64, coord) + self.get_overlay_value(coord)) / 2.0; // TODO! Remember to interpolate between the chunks // TODO: Implement this when the component system is finished unimplemented!(); } } <file_sep>Big horrible realization: `CharacterCache`'s type `Texture` is *not* just used to retrieve the size of the image (i.e., it is not just an instance of `ImageSize`). It *must* match the `Texture` type of your `Graphics` instance in order to make text drawing calls with it. To clarify, our `Graphics` instance is `GlGraphics`, whose texture is `opengl_graphics::Texture`. So everything is mangled to shit. :+1: I'll work on it more later, wai.<file_sep>use core::*; use opengl_graphics::*; use graphics::*; /// A player pub struct Player { pos: Vec2<i64>, dir: Dir, trans: f64, frame: i16, last_move: f64, } impl Position for Player { fn get_pos(&self) -> Vec2<i64> { self.pos } fn set_pos(&mut self, new_pos: Vec2<i64>) { self.pos = new_pos; } } // TODO: Implement new trait methods for Player impl Move for Player { fn get_dir(&self) -> Dir { self.dir } fn set_dir(&mut self, new_dir: Dir) { self.dir = new_dir; } fn is_moving(&self) -> bool { // TODO: Code here. unimplemented!() } fn can_move(&self) -> bool { // TODO: Check if the way is blocked, using the cache. unimplemented!() } fn get_last_move(&self) -> f64 { self.last_move } fn set_last_move(&mut self, new: &f64) { self.last_move = *new; } fn get_speed(&self) -> f64 { 1.0 } fn get_trans_state(&self) -> f64 { self.trans } fn get_animation_frame(&self) -> i16 { self.frame } } impl Sprite for Player { fn get_sprite(&self) -> &Texture { unimplemented!(); // TODO: Sprite here } fn get_width(&self) -> i16 { 1 } fn get_height(&self) -> i16 { 1 } fn get_opacity(&self) -> f64 { 1.0 } fn draw(&self, c: &Context, gl: &mut GlGraphics) { unimplemented!() } } impl Matter for Player {} impl Entity for Player { fn id(&self) -> Id { Id(0) // NOTE: Player's ID is always 0 } fn is_solid(&self, x: i16, y: i16) -> bool { false // TODO: Should it be solid? } fn update(&mut self, dt: f64) { self.move_reg(); } } <file_sep>use std::error::Error; use std::io; use std::io::Read; use std::fmt; use std::fs::File; use std::string::FromUtf8Error; /// Wraps a couple types of errors for `read_file`. #[derive(Debug)] pub enum ReadUtf8FileError { IoError(io::Error), Utf8Error(FromUtf8Error) } impl fmt::Display for ReadUtf8FileError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { &ReadUtf8FileError::IoError(ref e) => f.write_fmt(format_args!("{}", e)), &ReadUtf8FileError::Utf8Error(ref e) => f.write_fmt(format_args!("{}", e)) } } } impl Error for ReadUtf8FileError { fn description(&self) -> &str { "a problem occurred trying to read a file" } } impl From<io::Error> for ReadUtf8FileError { fn from(e: io::Error) -> ReadUtf8FileError { ReadUtf8FileError::IoError(e) } } impl From<FromUtf8Error> for ReadUtf8FileError { fn from(e: FromUtf8Error) -> ReadUtf8FileError { ReadUtf8FileError::Utf8Error(e) } } /// An easy function to quickly read a whole file. /// /// The price you pay is that errors are wrapped a bit. pub fn read_utf8_file(path: &str) -> Result<String, ReadUtf8FileError> { let mut f = try!(File::open(path)); let mut buffer = Vec::new(); let _ = try!(f.read_to_end(&mut buffer)); Ok( try!(String::from_utf8(buffer)) ) } <file_sep>use std::fmt::Debug; use std::ops::{Add, Sub, Mul, Div}; use num::{Float, Num}; use core::angle::{Angle, AngleDatum}; #[derive(Clone, Copy, Debug)] /// Vector struct, implements vector operations pub struct Vec2<T>(pub T, pub T) where T: Copy + Debug + Num; impl<T> Vec2<T> where T: Copy + Debug + Num { /// Get x component pub fn x(&self) -> T { self.0 } /// Get y component pub fn y(&self) -> T { self.1 } /// Get norm (i.e. complex absolute value) pub fn norm(&self) -> T { self.x() * self.x() + self.y() * self.y() } } impl<F: AngleDatum> Vec2<F> { /// Convert polar form to Vec2 pub fn from_magnitude(magnitude: F, direction: Angle<F>) -> Vec2<F> { Vec2( F::cos(direction.as_radians()) * magnitude, F::sin(direction.as_radians()) * magnitude ) } } impl<T> Add for Vec2<T> where T: Copy + Debug + Num { type Output = Vec2<T>; fn add(self, other: Vec2<T>) -> Self::Output { Vec2(self.0 + other.0, self.1 + other.1) } } impl<T> Sub for Vec2<T> where T: Copy + Debug + Num { type Output = Vec2<T>; fn sub(self, other: Vec2<T>) -> Self::Output { Vec2(self.0 - other.0, self.1 - other.1) } } impl<T> Mul<T> for Vec2<T> where T: Copy + Debug + Num { type Output = Vec2<T>; fn mul(self, scalar: T) -> Self::Output { Vec2(self.0 * scalar, self.1 * scalar) } } impl<T> Div<T> for Vec2<T> where T: Copy + Debug + Num { type Output = Vec2<T>; fn div(self, scalar: T) -> Self::Output { Vec2(self.0 / scalar, self.1 / scalar) } } impl From<Vec2<i64>> for Vec2<f64> { #[inline] fn from(old: Vec2<i64>) -> Vec2<f64> { Vec2(old.x() as f64, old.y() as f64) } } <file_sep>// Todo: Add tile metadata // use models::*; use core::{Vec2, Entity, Prop}; use model::{Player}; /// A block: a field consisting of three layers, containing tiles. #[derive(Clone)] pub struct Tile<'a> { pub layers: Vec<&'a Prop>, pub solid: bool, // NOTE: When a tile load it's occupied_tiles should be set // to have solid = true (This is sorta a todo) } // TODO: Make load_also, for the sprites which occupies more than one field. // This is to tell the renderer that it should also render this sprite. /// A map pub struct Map<'a> { entities: Vec<&'a Entity>, player: &'a Player, tile_map: &'a TileMap<'a>, // TODO: Instead, implement this trait for Map } /// A tiled map pub trait TileMap<'a> { /// Get the tile on this given coordinate fn get_tile(&self, coord: Vec2<i64>) -> Tile<'a>; fn add_prop(&mut self, prop: &Prop) { unimplemented!() // TODO: Load the prob, and it's collision map, set all tiles in the collision maps's solid // variable to true. And push the prop to the tile. } fn set_tile(&mut self, new_tile: Tile) {} fn get_solid(&self) -> bool { false } fn set_solid(&mut self, new: bool) { unimplemented!() } } <file_sep># Model File Specification This is the specification for model files. (`data/models/*.json`) All units are tiles (16x16 pixels) unless specified otherwise. # Keys #### name This is an arbitrary name for the model. Conventionally, this should match the filename (without ".json".) #### sprite_data This list contains the data for the sprites of the model. Key | Default? | Type | Description -------------|-----------------|-------------|------------ `cut_from` | `[0,0]` | `[u16,u16]` | Where from the image to cut the graphic `cut_offset` | `[0,0]` | `[i8,i8]` | The *pixel* offset of the graphic in the source image `file` | `"tileset.png"` | `string` | The path to the image, relative to `data/graphics` `frame` | `0` | `u32` | The `frame` the graphic belongs to `pin_offset` | `[0,0]` | `[i8,i8]` | The *pixel* offset of the graphic on the model `pin_to` | `[0,0]` | `[i16,i16]` | Where the graphic should be drawn relative to the model `size` | `[1,1]` | `[u16,u16]` | The size of the rectangle cut from the image `sprite` | `"default"` | `string` | The sprite of the model that this graphic belongs to `with` | N/A | `structure` | A set of graphic structures containing different defaults This is a bit complex, so check out the examples. #### occupied_tiles The elements of this list take one of these two forms: - `{ "individual": [ [3,4], [4,4], [5,4] ] }` - `{ "rectangle": { "start": [3,4], "size": [3,1] } }` The two examples are equivalent. # Examples #### Rock A model for a 1x1 tile rock. ```json5 // Contents of the file data/models/rock.json { // The name of the model "name": "Rock", // The sprite is the first from the left, second from the top of the // default tileset "sprite_data": [ { "cut_from": [0,1] } ], // The rock occupies one tile where it is positioned "occupied_tiles": [ { "individual": [ [0,0] ] } ] } ``` #### Tree A model for a 2x2 tile tree. Its "collision box" is just the bottom two tiles. ```json5 // Contents of the file data/models/tree.json { "name": "Tree", // The sprite is in a contiguous block in the default tileset // (It starts at the 5th from the left, 3rd from the top tile) "sprite_data": [ { "cut_from": [4,2], "size": [2,2] } ], // The tree only occupies its bottom two tiles // (so entities can sit behind the tree) "occupied_tiles": [ { "individual": [ [0,1], [1,1] ] } ] } ``` #### House A model for a 5x4 tile house. Its "collision box" is the bottom 5x3 tiles. ```json5 // Contents of the file data/models/house_a.json { "name": "House A", // The sprite is made up of the building, the door, and the window // They are in contiguous blocks in the file data/graphics/house.png "sprite_data": [ { "with": { "defaults": { "file": "house.png" }, // All of these items will cut from house.png by default "data": [ { // the building "cut_from": [0,0], "size": [5,4] }, { // the window "cut_from": [5,0], "pin_to": [3,2] }, { // the door "cut_from": [5,1], "size": [1,2], "pin_to": [1,2] } ] } } ], "occupied_tiles": [ { "rectangle": { "start": [0,1], "size": [5,3] } } ] } ``` #### Flower A model for a 1x1 flower tile. It doesn't collide; it's just decoration for the grass. It's animated so it looks like the flowers blow in the wind. ```json5 // Contents of the file data/models/flower.json { "name": "Flower", // The sprite is made up of the grass and the flowers. It's animated. "sprite_data": [ { "with": { // The default for "frame" is already 0. This just makes it look // consistent with the next "with" block. "defaults": { "frame": 0 }, "data": [ { "cut_from": [1,0] }, // grass { "cut_from": [2,0] } // flowers (first frame) ] }, "with": { "defaults": { "frame": 1 }, "data": [ { "cut_from": [1,0] }, // grass { "cut_from": [3,0] } // flowers (second frame) ] } } ], // Does not occupy space "occupied_tiles": [] } ``` #### Wall Lamp A model for a 1x1 light fixture. It doesn't occupy space or collide; it is fixed on a wall. It can be switched on and off, however. ```json5 // Contents of the file data/models/wall_lamp.json { "name": "Wall Lamp", // When the lamp is switched on, it changes sprites. (That functionality // is not encoded here, but when the model is loaded, the game logic can // access the "off" sprite and the "on" sprite.) The sprite is in the // file data/graphics/light.png. "sprite_data": [ { "with": { "defaults": { "file": "light.png" }, "data": [ { "sprite": "off", "cut_from": [0,0] }, { "sprite": "on", "cut_from": [1,0] } ] } } ], // Does not occupy space "occupied_tiles": [] } ``` <file_sep>use rustc_serialize::json::Json; use core::Vec2; use model::data::error::ModelError; /// Parse individual occupied tiles pub fn parse(block: &Json, ret: &mut Vec<Vec2<i8>> ) -> Result<(), ModelError> { match block { &Json::Array(ref arr) => { for obj in arr { try!(parse_element(obj, ret, "element of list \"individual\"", "[i8, i8]" )); } }, _ => return Err(ModelError::TypeError { obj: "\"individual\" block in \"occupied_tiles\"", expected: "array" }) } Ok(()) } fn parse_element(elem: &Json, ret: &mut Vec<Vec2<i8>>, type_err_obj: &'static str, type_err_exp: &'static str ) -> Result<(), ModelError> { let type_err = ModelError::TypeError { obj: type_err_obj, expected: type_err_exp }; match elem { &Json::Array(ref tile) => { if tile.len() != 2 { return Err(type_err); } let v = Vec2( try!(extract_i8(&tile[0], type_err_obj, type_err_exp)), try!(extract_i8(&tile[1], type_err_obj, type_err_exp)) ); ret.push(v); Ok(()) }, _ => Err(type_err) } } fn extract_i8(value: &Json, type_err_obj: &'static str, type_err_exp: &'static str ) -> Result<i8, ModelError> { match value { &Json::I64(n) => Ok(n as i8), &Json::U64(n) => Ok(n as i8), _ => Err(ModelError::TypeError { obj: type_err_obj, expected: type_err_exp }) } } <file_sep>mod load_model; mod model; pub use self::load_model::LoadModelError; pub use self::model::ModelError; <file_sep>use mapgen::{ChunkCoord, Island}; use mapgen::seed::Seed2; /// A chunk struct Chunk { islands: Vec<Island>, } const MAX_ISLANDS: u16 = 6; const MAX_RADIUS: f64 = 10.0; impl Chunk { fn new() -> Chunk { Chunk { islands: Vec::new() } } fn generate(seed: Seed2, pos: ChunkCoord) -> Chunk { let mut chunk = Chunk::new(); let num_islands = (seed.feed_vec(pos).feed(42).get_f64() * (MAX_ISLANDS as f64)).round() as i64; for i in 1..num_islands { chunk.islands.push(Island::generate_island(seed, // Radius seed.feed(666).feed(i).get_f64() * MAX_RADIUS, // Number of hills 4, // Chunk Coordinate pos, // The island number i)); } chunk } } <file_sep># Naming review - [ ] main.rs - [ ] **core** - [ ] mod.rs - [ ] angle.rs - [ ] cam.rs - [ ] config.rs - [x] map.rs - [x] object.rs - [x] prop.rs - [ ] vec2.rs - [x] **state** - [x] mod.rs - [x] game.rs - [ ] **util** - [ ] mod.rs - [ ] read_utf8_file.rs - [ ] **mapgen** - [ ] mod.rs - [ ] **model** - [ ] mod.rs - [ ] player.rs - [ ] **data** - [ ] mod.rs - [ ] load.rs - [ ] **error** - [ ] mod.rs - [ ] load_model.rs - [ ] model.rs - [ ] **occupied_tile_data** - [ ] mod.rs - [ ] individual.rs - [ ] rectangle.rs - [ ] **sprite_data** - [ ] mod.rs - [ ] sprite_builder.rs - [ ] **settings** - [ ] mod.rs - [ ] modify.rs - [ ] **error** - [ ] mod.rs - [ ] load_model.rs - [ ] model.rs - [ ] **renderer** - [ ] mod.rs - [ ] cache.rs <file_sep>use std::error::Error; use std::fmt; use std::io; use std::string::FromUtf8Error; use rustc_serialize::json; use core::util::ReadUtf8FileError; use super::ModelError; /// A load model error #[derive(Debug)] pub enum LoadModelError { IoError(io::Error), Utf8Error(FromUtf8Error), JsonError(json::ParserError), ModelError(ModelError), } impl fmt::Display for LoadModelError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { &LoadModelError::IoError(ref e) => f.write_fmt(format_args!("{}", e)), &LoadModelError::Utf8Error(ref e) => f.write_fmt(format_args!("{}", e)), &LoadModelError::JsonError(ref e) => f.write_fmt(format_args!("{}", e)), &LoadModelError::ModelError(ref e) => f.write_fmt(format_args!("{}", e)), } } } impl Error for LoadModelError { fn description(&self) -> &str { "a problem occurred trying to load a model" } } impl From<io::Error> for LoadModelError { fn from(e: io::Error) -> LoadModelError { LoadModelError::IoError(e) } } impl From<FromUtf8Error> for LoadModelError { fn from(e: FromUtf8Error) -> LoadModelError { LoadModelError::Utf8Error(e) } } impl From<ReadUtf8FileError> for LoadModelError { fn from(e: ReadUtf8FileError) -> LoadModelError { match e { ReadUtf8FileError::IoError(e) => LoadModelError::IoError(e), ReadUtf8FileError::Utf8Error(e) => LoadModelError::Utf8Error(e) } } } impl From<json::ParserError> for LoadModelError { fn from(e: json::ParserError) -> LoadModelError { LoadModelError::JsonError(e) } } impl From<ModelError> for LoadModelError { fn from(e: ModelError) -> LoadModelError { LoadModelError::ModelError(e) } } <file_sep>// A wrapper around noise.rs // Consider writing our own noise lib // TODO: Take more pointers as arguments use noise::*; use core::Vec2; use std::hash::*; /// A seed #[derive(Clone, Hash)] struct Seed2 { seed: i64, } impl Seed2 { fn new(seed: i64) -> Seed2 { Seed2 { seed: seed, } } /// Add information to the seed fn feed(&self, with: i64) -> Seed2 { Seed2::new(((self.seed) >> 16) ^ with) } /// Add a vector to the seed fn feed_vec(&self, with: Vec2<i64>) -> Seed2 { self.feed(with.x()).feed(with.y()) } /// Get the value of the seed (note: non-continious) fn get(&self) -> u64 { let hasher = SipHasher::new(); self.hash(&mut hasher); hasher.finish() } /// Get a value in the interval [0, 1] fn get_f64(&self) -> f64 { (self.get() as f64) / (u64::max_value() as f64) } /// Get the continious value of the seed fn get_noise(&self, chunk_size: f64, pos: Vec2<i64>) -> f64 { let noise = Brownian2::new(open_simplex2, 4) .wavelength(chunk_size); noise.apply(&self.to_seed(), &[pos.x() as f64, pos.y() as f64]) } fn to_seed(&self) -> Seed { Seed::new(self.seed as u32) } } <file_sep>use std::collections::BTreeMap; use rustc_serialize::json::Json; use super::{Frame, Sprite}; use super::error::ModelError; mod settings; mod sprite_builder; use self::settings::SpriteDataSettings; use self::sprite_builder::SpriteBuilder; /// Process sprite data. pub fn parse(data: &Vec<Json>) -> Result<BTreeMap<String, Sprite>, ModelError> { let mut uncompressed: BTreeMap<String, SpriteBuilder> = BTreeMap::new(); try!(parse_2(data, &SpriteDataSettings::defaults(), &mut uncompressed)); let mut ret = BTreeMap::new(); for (key, val) in uncompressed { let sprite = try!(val.build(&key)); ret.insert(key, sprite); } Ok(ret) } /// Just the recursive version of `parse`. /// /// This fills in `ret` with the processed data. It returns Ok(()) on success. fn parse_2(data: &Vec<Json>, settings: &SpriteDataSettings, ret: &mut BTreeMap<String, SpriteBuilder> ) -> Result<(), ModelError> { for obj in data { try!(process(obj, settings, ret)); }; Ok(()) } /// Process one item in "sprite_data" fn process(json_obj: &Json, settings: &SpriteDataSettings, ret: &mut BTreeMap<String, SpriteBuilder> ) -> Result<(), ModelError> { match json_obj { &Json::Object(ref obj) => process_2(obj, settings, ret), _ => Err(ModelError::TypeError { obj: "\"sprite_data\" list element", expected: "object" }) } } /// Process an object in "sprite_data" /// /// This function just processes a JSON value after it has been verified to be /// an object. fn process_2(obj: &BTreeMap<String, Json>, settings: &SpriteDataSettings, ret: &mut BTreeMap<String, SpriteBuilder> ) -> Result<(), ModelError> { if obj.contains_key("with") { if obj.len() > 1 { return Err(ModelError::WrongNumKeys { expected: 1, context: "object containing \"with\"" }); } process_with(obj, settings, ret) } else { let mut final_settings = settings.clone(); try!(settings::modify(&mut final_settings, obj)); insert_frame(&final_settings, ret) } } fn process_with(with_obj: &BTreeMap<String, Json>, settings: &SpriteDataSettings, ret: &mut BTreeMap<String, SpriteBuilder> ) -> Result<(), ModelError> { let mut new_settings = settings.clone(); let mut data = None; for (key, val) in with_obj.iter() { match key as &str { "defaults" => { if let &Json::Object(ref delta) = val { try!(settings::modify(&mut new_settings, &delta)); } else { return Err(ModelError::TypeError { obj: "\"defaults\"", expected: "object" }); }; }, "data" => { match val { &Json::Object(ref obj) => data = Some(obj), _ => return Err(ModelError::TypeError { obj: "\"data\"", expected: "object" }) } }, other => return Err(ModelError::InvalidKey { key: other.to_string(), context: "\"with\" object" }) }; }; if let Some(obj) = data { return process_2(obj, &new_settings, ret); } Err(ModelError::MissingKey { key: "data", context: "\"with\" object" }) } fn insert_frame(settings: &SpriteDataSettings, ret: &mut BTreeMap<String, SpriteBuilder> ) -> Result<(), ModelError> { let mut sprite = match ret.get(&settings.sprite_name) { Some(sprite) => sprite.clone(), None => SpriteBuilder::new(), }; if let Some(_) = sprite.frames.get(&settings.frame_index) { return Err(ModelError::FrameRedef { sprite_name: settings.sprite_name.clone(), frame_index: settings.frame_index }); }; let frame = Frame { cut_from: settings.cut_from, cut_offset: settings.cut_offset, size: settings.size, pin_to: settings.pin_to, pin_offset: settings.pin_offset, }; sprite.frames.insert(settings.frame_index, frame); ret.insert(settings.sprite_name.clone(), sprite); Ok(()) } <file_sep>Welcome to the Open Sea wiki! [Glossary](glossary.md) [Tasks](tasks.md) [Ideas](ideas.md) [Model File Specification](model-spec.md) <file_sep>use piston::event::RenderArgs; use opengl_graphics::GlGraphics; use core::{Vec2}; use core::cache::*; use core::cam::*; use renderer::Renderer; use state::State; /// The in-game view pub struct Game<'a> { cache: Cache<'a>, cam: Cam<'a>, } impl<'a> State for Game<'a> { fn render(&self, dt: f64, args: &RenderArgs, gl: &mut GlGraphics, renderer: &mut Renderer) { // TODO: Draw objects here. renderer.draw_text(args, gl, "Here's a long string of text.", Vec2(10.0, 30.0) ); } } <file_sep>use std::cmp::max; use std::collections::BTreeMap; use model::data::{Frame, Sprite}; use model::data::error::ModelError; #[derive(Clone, Debug)] pub struct SpriteBuilder { pub resource: Option<usize>, pub frames: BTreeMap<usize, Frame>, } impl SpriteBuilder { pub fn new() -> SpriteBuilder { SpriteBuilder { resource: None, frames: BTreeMap::new() } } pub fn build(mut self, name: &String) -> Result<Sprite, ModelError> { let resource; if let Some(r) = self.resource { resource = r; } else { // TODO get default tileset from resource manager resource = 0; } if self.frames.len() == 0 { panic!("No frames given for sprite.") } let expected_max = self.frames.len(); let mut actual_max = 0; for key in self.frames.keys() { actual_max = max(*key, actual_max); } if actual_max != expected_max { return Err(ModelError::InvalidFrames { sprite_name: name.clone(), length: expected_max, max_index: actual_max }); } let mut frames = Vec::with_capacity(expected_max); let mut i = frames.len(); while i < expected_max { frames.push(self.frames.remove(&i).unwrap()); i = frames.len(); } Ok(Sprite::new(resource, frames)) } } <file_sep>use std::collections::BTreeMap; use std::fmt::Debug; use num::Num; use rustc_serialize::json::Json; use model::data::error::ModelError; use super::SpriteDataSettings; use core::Vec2; pub fn modify(settings: &mut SpriteDataSettings, delta: &BTreeMap<String, Json> ) -> Result<(), ModelError> { for (key, val) in delta.iter() { match key as &str { "sprite" => settings.sprite_name = try!(get_sprite_name(val)), "frame" => settings.frame_index = try!(get_frame_index(val)), "cut_from" => settings.cut_from = try!(get_pair(val, "\"cut_from\"", "[u16, u16]", extract_u16)), "cut_offset" => settings.cut_offset = try!(get_pair(val, "\"cut_offset\"", "[i8, i8]", extract_i8)), "size" => settings.size = try!(get_pair(val, "\"size\"", "[u16, u16]", extract_u16)), "pin_to" => settings.pin_to = try!(get_pair(val, "\"pin_to\"", "[i16, i16]", extract_i16)), "pin_offset" => settings.pin_offset = try!(get_pair(val, "\"pin_offset\"", "[i8, i8]", extract_i8)), other => return Err(ModelError::InvalidKey { key: other.to_string(), context: "\"defaults\" object" }) } } Ok(()) } fn type_error<T>(obj: &'static str, expected: &'static str ) -> Result<T, ModelError> { Err(ModelError::TypeError { obj: obj, expected: expected }) } fn get_sprite_name(value: &Json) -> Result<String, ModelError> { match value { &Json::String(ref s) => Ok(s.clone()), _ => type_error("\"sprite\"", "string") } } fn get_frame_index(value: &Json) -> Result<usize, ModelError> { let type_err = type_error("\"frame\"", "u64"); match value { &Json::I64(n) => { if n < 0 { return type_err; } Ok(n as usize) }, &Json::U64(n) => Ok(n as usize), _ => return type_err } } fn get_pair<T, F>(value: &Json, key: &'static str, expected: &'static str, extract: F ) -> Result<Vec2<T>, ModelError> where T: Copy + Debug + Num, F: Fn(&'static str, &'static str, &Json) -> Result<T, ModelError> { match value { &Json::Array(ref arr) => { if arr.len() != 2 { return type_error(key, expected); } let a = try!(extract(key, expected, &arr[0])); let b = try!(extract(key, expected, &arr[1])); Ok(Vec2(a, b)) }, _ => type_error(key, expected), } } // TODO: generalize these `extract...` methods (use num crate) /// This is only to be used with `get_pair` fn extract_i8(key: &'static str, expected: &'static str, obj: &Json ) -> Result<i8, ModelError> { match obj { // TODO check bounds &Json::I64(n) => Ok(n as i8), &Json::U64(n) => Ok(n as i8), _ => return type_error(key, expected) } } /// This is only to be used with `get_pair` fn extract_i16(key: &'static str, expected: &'static str, obj: &Json ) -> Result<i16, ModelError> { match obj { // TODO check bounds &Json::I64(n) => Ok(n as i16), &Json::U64(n) => Ok(n as i16), _ => return type_error(key, expected) } } /// This is only to be used with `get_pair` fn extract_u16(key: &'static str, expected: &'static str, obj: &Json ) -> Result<u16, ModelError> { match obj { &Json::I64(n) => { if n < 0 { return type_error(key, expected); } // TODO check `n` < 2**16 Ok(n as u16) }, // TODO check `n` < 2**16 &Json::U64(n) => Ok(n as u16), _ => type_error(key, expected) } } <file_sep>//! The module for rendering use std::path::Path; use piston::event::RenderArgs; use opengl_graphics::GlGraphics; use opengl_graphics::glyph_cache::GlyphCache; use graphics; use core::cache::*; use core::Vec2; mod texture_manager; pub use self::texture_manager::{LoadTextureError, TextureManager}; /// The renderer pub struct Renderer { font: GlyphCache<'static>, text: graphics::text::Text, } impl Renderer { /// Create a new renderer pub fn new() -> Renderer { Renderer { font: GlyphCache::new(Path::new("./data/font.ttf")).unwrap(), text: graphics::text::Text::new(20) } } /// Draw text pub fn draw_text(&mut self, args: &RenderArgs, gl: &mut GlGraphics, s: &str, pos: Vec2<f64> ) { use graphics::*; gl.draw(args.viewport(), |c, gl| { let Vec2(x, y) = pos; self.text.draw(s, &mut self.font, default_draw_state(), c.trans(x, y).transform, gl ); }); } } <file_sep>use std::error::Error; use rustc_serialize::{Decoder, json}; use super::util; mod error; pub use self::error::LoadConfigError; const CONFIG_PATH: &'static str = "./data/config.json"; /// The configuration of the window #[derive(RustcDecodable, RustcEncodable)] pub struct Config { title: String, window_size: Vec<u32> } impl Config { pub fn load() -> Result<Config, LoadConfigError> { let config_contents = try!(util::read_utf8_file(CONFIG_PATH)); // See self::error source for why try! isn't used here. match json::decode(&config_contents) { Ok(config) => Ok(config), Err(e) => Err(LoadConfigError::JsonError(e)), } } pub fn game_title(&self) -> &String { &self.title } pub fn window_size(&self) -> [u32; 2] { [ self.window_size[0], self.window_size[1] ] } } <file_sep>## TODO ### In-line TODO (Todos in the codebase, often smaller tasks) [Link to inline TODOs](https://github.com/Ticki/Open-Sea/search?utf8=%E2%9C%93&q=TODO) ### Generic TODO - [ ] ! (Easy) Remove unused piston depedencies - [ ] ! Just get it working: Have a player moving around, and a camera following it. - [ ] Implement server side - [ ] ! Discuss naming conventitions of traits, structs. In ALL modules, particularly the Core module. - [ ] ! Make sure the core module is actually used, where it could be. - [ ] Make a roadmap - [ ] Make a codebase introduction (for new contributors) - [ ] ! Make a event handeler (possibly also a method to be called when the object is clicked etc.) - [ ] Tiles: - Add Tiled support - [x] Animations - [ ] ! Clean up docs. - [x] Make more variance in the island generation. - [ ] ! Add more sprites - Player - Animals? (Pets?) - [ ] Project management? - [ ] ! Consider only using piston-graphics - [x] Make the use of 'use' more consistent (use ...::* vs use ...::{... , ... , ...} - [x] Make use of Core in map.rs - [ ] Discuss long term goal - [ ] Return more pointers? - [ ] Make big chunks bigger? (for more variance in island generation + more flexebility) - [x] Handle errors in Config and Model loader - [x] Find a good font for the game (Could be nice if it was MIT-licensed) - [ ] Finish [naming review](wiki/naming.md) - [x] Make glossary - [ ] Event - Pull it up to handle Piston::Event - Event handler trait - [ ] Pull out object.rs - maybe entity.rs, too <file_sep>use std::collections::BTreeMap; use rustc_serialize::json::Json; use core::util; use super::ModelData; use super::error::{LoadModelError, ModelError}; use super::occupied_tile_data; use super::sprite_data; // TODO make functions Result<_, ModelError> where appropriate impl ModelData { // TODO remove dead_code permit as soon as we start loading ModelData #[allow(dead_code)] /// Load model data pub fn load(path: &str) -> Result<ModelData, LoadModelError> { let obj = try!(ModelData::load_json(path)); Ok(try!( ModelData::parse_json(&obj) )) } /// Load json fn load_json(path: &str) -> Result<BTreeMap<String, Json>, LoadModelError> { let file_contents = try!(util::read_utf8_file(path)); let json_obj = try!(Json::from_str(&file_contents)); match json_obj { Json::Object(data) => Ok(data), _ => try!(Err( ModelError::TopLevelNotObject )) } } fn parse_json(obj: &BTreeMap<String, Json>) -> Result<ModelData, ModelError> { match obj.get("name") { Some(name) => println!("Loading model {}...", name), None => return Err(ModelError::MissingKey { key: "name", context: "model data" }) }; let sprite_data; match obj.get("sprite_data") { Some(&Json::Array(ref raw_sprite_data)) => sprite_data = try!(sprite_data::parse(raw_sprite_data)), Some(_) => return Err(ModelError::TypeError { obj: "key \"sprite_data\"", expected: "array" }), None => return Err(ModelError::MissingKey { key: "sprite_data", context: "model data" }) }; let occupied_tile_data; match obj.get("occupied_tiles") { Some(&Json::Array(ref raw_occupied_tile_data)) => occupied_tile_data = try!( occupied_tile_data::parse(raw_occupied_tile_data) ), Some(_) => return Err(ModelError::TypeError { obj: "key \"occupied_tiles\"", expected: "array" }), None => return Err(ModelError::MissingKey { key: "occupied_tiles", context: "model data" }) }; Ok(ModelData { sprite_data: sprite_data, occupied_tiles: occupied_tile_data }) } } <file_sep>![Open-Sea](data/graphics/logo_scaled.png) **Open Sea** is a sandbox RPG written in Rust using the Piston library. Sail the open sea, explore the world, and play together with your friends. Open Sea is still in its early stages. ![TraviCI](https://api.travis-ci.org/Ticki/Open-Sea.svg) #### Contribute #### Open an issue, or fork the repo and send a pull request. Contributions are much appreciated. [wiki](wiki/readme.md) <file_sep>use std::fmt::Debug; use std::f32; use std::f64; use std::ops::{Add, Sub}; use num::Float; pub trait AngleDatum : Copy + Debug + Float { fn pi() -> Self; fn _2_pi() -> Self; fn _180() -> Self; } impl AngleDatum for f32 { fn pi() -> Self { f32::consts::PI } fn _2_pi() -> Self { f32::consts::PI * 2.0 } fn _180() -> Self { 180.0 } } impl AngleDatum for f64 { fn pi() -> Self { f64::consts::PI } fn _2_pi() -> Self { f64::consts::PI * 2.0 } fn _180() -> Self { 180.0 } } #[derive(Clone, Copy, Debug)] pub struct Angle<T: AngleDatum> { radians: T } impl<T: AngleDatum> Angle<T> { pub fn radians(theta: T) -> Angle<T> { Angle { radians: Self::normalize(theta) } } pub fn degrees(theta: T) -> Angle<T> { Angle { radians: Self::normalize( Self::deg_to_rad(theta) ) } } pub fn as_radians(&self) -> T { self.radians } pub fn as_degrees(&self) -> T { Self::rad_to_deg(self.radians) } fn rad_to_deg(rad: T) -> T { (rad * T::_180()) / T::pi() } fn deg_to_rad(deg: T) -> T { (deg * T::pi()) / T::_180() } /// Return an equivalent radian value on the interval [-PI, PI) fn normalize(radians: T) -> T { let mut normalized = radians; let zero = T::zero(); let _2_pi = T::_2_pi(); while normalized < zero { normalized = normalized + _2_pi; } normalized % _2_pi } } impl<T: AngleDatum> Add for Angle<T> { type Output = Angle<T>; fn add(self, other: Angle<T>) -> Angle<T> { Angle { radians: Self::normalize(self.radians + other.radians) } } } impl<T: AngleDatum> Sub for Angle<T> { type Output = Angle<T>; fn sub(self, other: Angle<T>) -> Angle<T> { Angle { radians: Self::normalize(self.radians - other.radians) } } } <file_sep>use std::error::Error; use std::fmt; #[derive(Debug)] /// An error when loading a model pub enum ModelError { /// Toplevel, not object (brackets needed) TopLevelNotObject, /// Missing keys MissingKey { key: &'static str, context: &'static str }, /// Type error TypeError { obj: &'static str, expected: &'static str }, /// Invalid key InvalidKey { key: String, context: &'static str }, /// Unexpected number of keys WrongNumKeys { expected: usize, context: &'static str }, /// Invalid frames InvalidFrames { sprite_name: String, length: usize, max_index: usize }, /// Redefinition of frames (i.e. duplicates or overlaps) FrameRedef { sprite_name: String, frame_index: usize }, } impl fmt::Display for ModelError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { &ModelError::TopLevelNotObject => f.write_str("Model file must be JSON object"), &ModelError::MissingKey { ref key, ref context } => f.write_fmt(format_args!("{} is missing key {:?}", context, key)), &ModelError::TypeError { ref obj, ref expected } => f.write_fmt( format_args!("Type error: expected value of type `JSON {}` for {}", expected, obj )), &ModelError::InvalidKey { ref key, ref context } => f.write_fmt( format_args!("found unexpected key {:?} in {}", key, context) ), &ModelError::WrongNumKeys { expected, ref context } => f.write_fmt( format_args!("Expected to find exactly {} key(s) in {}", expected, context) ), &ModelError::InvalidFrames { ref sprite_name, length, max_index } => f.write_fmt(format_args!( "Missing frame definitions in sprite {:?} ({} frames found, but max index is {})", sprite_name, length, max_index )), &ModelError::FrameRedef { ref sprite_name, frame_index } => f.write_fmt(format_args!( "Multiple definitions found for frame {} of sprite {:?}", frame_index, sprite_name )), } } } impl Error for ModelError { fn description(&self) -> &str { "the model data is invalid" } } <file_sep>### Hey wai, I have some questions about the code. #### Requests for Documentation The following is a list of items for which I need clearer documentation/explanation. I know much of this is probably terminology from another engine/framework/etc., but not all of it is clear to me. - `View` - `View::start()` and `View::end()` (What are these supposed to do? Also, should they have empty default implementations? You defined them that way.) :: They're events which should be called when the view changes. The reason for the empty default method is that not every view necessarily will have any contents for this event. - `GameView` (Especially in constrast to `View`) :: This is just a temporary naming for a view which is in game (not a menu etc.) - `models` (Is this module for entities/game objects?) :: A model is just a game object. You don't have to document them yourself; we'll can always discuss them tomorrow and I'll write the docs! :: Sorry for the bad docs... #### Design Choices We Should Discuss - I think we should use `f32` or `f64` for positions, otherwise the finest movement granularity we can achieve is one coordinate/pixel per frame (without storing extra data or scaling world coordinates, etc.) :: The i64 positions are for the grid position. Therefore the movement will probably be stored in a different field. - Currently, the `traits` module seems to just be storing a lot of commonly used functionality. I vote that we refactor it into a `core` module where we can put things until they should be organized out. :: I'm okay with that! - Getters and setters are a little archaic. Will things be modifying object coordinates/directions directly? Could these items just be made private? This one really merits a discussion about the design of the movement system. :: Let's discuss this in the chat. #### Talk to you tomorrow<file_sep>#### Glossary Tags Tag | Meaning -----------|-------- :mag: | This term needs to be discussed due to inconsistency or some other issue. :question: | This term needs to be defined, or its definition needs to be verified. Term | Tags | Meaning ----------|------------|-------- `BChunk` | :question: | A square of tiles, 32 tiles wide, and 32 tiles high. entity | | Basically, anything in the game world other than a tile. Examples: trees, players, enemies, chests, and signs. `Map` | :mag: | A collection of tiles and entities. model | | Data for describing a class of game objects, sometimes shared by many instances. prop | | An entity that doesn't do anything. Not a tile. Examples: trees, bushes, rocks. `Tile` | | A graphic that is drawn as part of the background. The tilemap is made of these, and has exactly one every 16x16 pixels. `TileMap` | | The tile data for a map. `View` | | A game state, like the main menu, or exploring the world. object | | Basically just a unified term for both props and entities. `Matter` | | A object with certain matterial descriptors, i.e. properties such as solidness, hardness, destroyability. <file_sep>use piston::event::RenderArgs; use opengl_graphics::GlGraphics; use renderer::Renderer; /// A state, i.e. an rendering state pub trait State { /// Render the view. fn render(&self, dt: f64, args: &RenderArgs, gl: &mut GlGraphics, renderer: &mut Renderer); /// This gets called when the view starts fn start(&mut self) {} /// This gets called when the view ends fn end(&mut self) {} } mod game; pub use self::game::Game; <file_sep>mod modify; pub use self::modify::modify; use core::Vec2; /// This struct simplifies the implementation of `parse` #[derive(Clone, Debug)] pub struct SpriteDataSettings { pub sprite_name: String, pub frame_index: usize, pub cut_from: Vec2<u16>, pub cut_offset: Vec2<i8>, pub size: Vec2<u16>, pub pin_to: Vec2<i16>, pub pin_offset: Vec2<i8>, } impl SpriteDataSettings { pub fn defaults() -> SpriteDataSettings { SpriteDataSettings { sprite_name: "default".to_string(), frame_index: 0, cut_from: Vec2(0, 0), cut_offset: Vec2(0, 0), size: Vec2(1, 1), pin_to: Vec2(0, 0), pin_offset: Vec2(0, 0), } } } <file_sep>use core::{Sprite, Matter}; /// Events. pub enum Event { /// When player 'contacts' (press space in front of) the object Contact, /// When the entity move Movement, /// When the entity collides with player PlayerCollision, /// When the entity is destroyed Destroy, // TODO: Add more } /// Entity ID type pub struct Id(pub i64); /// An entity, a dynamic in-game object with non-trivial functionality pub trait Entity: Sprite + Matter { /// Get the ID of the given entity fn id(&self) -> Id; /// Is the entity solid at point (x, y) relative to the position? fn is_solid(&self, x: i16, y: i16) -> bool; /// The default update method fn def_update(&mut self, dt: f64) { self.move_reg(); } /// Update the entity fn update(&mut self, dt: f64) { self.def_update(dt); } /// Should be called when event happens fn on_event(&mut self, event: Event) { match event { _ => {} } } // Probably need more methods. } <file_sep>use std::collections::BTreeMap; use rustc_serialize::json::Json; use super::error::ModelError; use core::Vec2; mod individual; mod rectangle; /// Parse data about occupied tiles pub fn parse(data: &Vec<Json>) -> Result<Vec<Vec2<i8>>, ModelError> { let mut ret = Vec::new(); try!(parse_2(data, &mut ret)); Ok(ret) } fn parse_2(data: &Vec<Json>, ret: &mut Vec<Vec2<i8>> ) -> Result<(), ModelError> { for obj in data { try!(parse_obj(obj, ret)); } Ok(()) } fn parse_obj(obj: &Json, ret: &mut Vec<Vec2<i8>> ) -> Result<(), ModelError> { match obj { &Json::Object(ref obj) => parse_obj_2(obj, ret), _ => Err(ModelError::TypeError { obj: "\"occupied_tiles\"", expected: "object" }) } } fn parse_obj_2(obj: &BTreeMap<String, Json>, ret: &mut Vec<Vec2<i8>> ) -> Result<(), ModelError> { if obj.len() > 1 { return Err(ModelError::WrongNumKeys { expected: 1, context: "\"occupied_tiles\" list element object" }); } for (key, val) in obj.iter() { match key as &str { "individual" => try!(individual::parse(val, ret)), "rectangle" => try!(rectangle::parse(val, ret)), other => return Err(ModelError::InvalidKey { key: other.to_string(), context: "\"occupied_tiles\" list element object" }) } } Ok(()) } <file_sep>mod read_utf8_file; pub use self::read_utf8_file::{ReadUtf8FileError, read_utf8_file}; <file_sep>use std::error::Error; use std::fmt; use std::io; use std::string::FromUtf8Error; use rustc_serialize::{Decoder, json}; use core::util::ReadUtf8FileError; #[derive(Debug)] pub enum LoadConfigError { IoError(io::Error), Utf8Error(FromUtf8Error), JsonError(<json::Decoder as Decoder>::Error), } impl fmt::Display for LoadConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { &LoadConfigError::IoError(ref e) => f.write_fmt(format_args!("{}", e)), &LoadConfigError::Utf8Error(ref e) => f.write_fmt(format_args!("{}", e)), &LoadConfigError::JsonError(ref e) => f.write_fmt(format_args!("{}", e)), } } } impl Error for LoadConfigError { fn description(&self) -> &str { "a problem occurred trying to load the configuration file" } } impl From<ReadUtf8FileError> for LoadConfigError { fn from(e: ReadUtf8FileError) -> LoadConfigError { match e { ReadUtf8FileError::IoError(e) => LoadConfigError::IoError(e), ReadUtf8FileError::Utf8Error(e) => LoadConfigError::Utf8Error(e), } } } /* This code causes an error (the line numbers are probably correct/close): /* src/core/config/error.rs:81:1: 85:2 error: conflicting implementations for trait `core::convert::From` [E0119] src/core/config/error.rs:81 impl From<<json::Decoder as Decoder>::Error> for LoadConfigError { src/core/config/error.rs:82 fn from(e: <json::Decoder as Decoder>::Error) -> LoadConfigError { src/core/config/error.rs:83 LoadConfigError::JsonError(e) src/core/config/error.rs:84 } src/core/config/error.rs:85 } src/core/config/error.rs:81:1: 85:2 note: conflicting implementation in crate `core` src/core/config/error.rs:81 impl From<<json::Decoder as Decoder>::Error> for LoadConfigError { src/core/config/error.rs:82 fn from(e: <json::Decoder as Decoder>::Error) -> LoadConfigError { src/core/config/error.rs:83 LoadConfigError::JsonError(e) src/core/config/error.rs:84 } src/core/config/error.rs:85 } src/core/config/error.rs:40:1: 47:2 error: conflicting implementations for trait `core::convert::From` [E0119] src/core/config/error.rs:40 impl From<ReadUtf8FileError> for LoadConfigError { src/core/config/error.rs:41 fn from(e: ReadUtf8FileError) -> LoadConfigError { src/core/config/error.rs:42 match e { src/core/config/error.rs:43 ReadUtf8FileError::IoError(e) => LoadConfigError::IoError(e), src/core/config/error.rs:44 ReadUtf8FileError::Utf8Error(e) => LoadConfigError::Utf8Error(e), src/core/config/error.rs:45 } ... src/core/config/error.rs:81:1: 85:2 note: note conflicting implementation here src/core/config/error.rs:81 impl From<<json::Decoder as Decoder>::Error> for LoadConfigError { src/core/config/error.rs:82 fn from(e: <json::Decoder as Decoder>::Error) -> LoadConfigError { src/core/config/error.rs:83 LoadConfigError::JsonError(e) src/core/config/error.rs:84 } src/core/config/error.rs:85 } */ impl From<<json::Decoder as Decoder>::Error> for LoadConfigError { fn from(e: <json::Decoder as Decoder>::Error) -> LoadConfigError { LoadConfigError::JsonError(e) } } // */ <file_sep>use core::Vec2; /// Matter, a trait carrying information about destroyability, solidness, hardness, and other /// properties of matter. pub trait Matter { fn is_solid(&self) -> bool { false } fn is_destroyable(&self) -> bool { false } fn get_hardness(&self) -> i32 { 3 } /// Get their collision map // TODO: Relative coordinates? fn get_collision_map(&self) -> Vec<Vec2<i64>> { Vec::new() } } <file_sep>use mapgen::{CHUNK_SIZE_usize, CHUNK_SIZE}; use core::{Vec2, Tile, TileMap}; /// A chunk grid, i.e. a grid of chunk size cotaining Block pub type ChunkGrid<'a> = [[Tile<'a>; CHUNK_SIZE_usize]; CHUNK_SIZE_usize]; /// A cache of the relevant chunks /// /// The ordering of the chunks are as follows. /// 1---2 /// | | /// 3---4 pub struct Cache<'a> { /// The offset of the cache, i.e. the place where you find chunk1 offset: Vec2<i64>, chunk1: ChunkGrid<'a>, chunk2: ChunkGrid<'a>, chunk3: ChunkGrid<'a>, chunk4: ChunkGrid<'a>, } // NOTE: When moving chunks around remember to use mem::replace impl<'a> Cache<'a> { fn update<'b, T>(&mut self, new_offset: Vec2<i64>, mapgen: T) where T: TileMap<'b>, 'b: 'a { let mut collision_map: Vec<Vec2<i64>> = Vec::new(); // TODO: Optimize this by using parts of the old cache which just should be // moved. // TODO: Consume iters? for (y, row) in self.chunk1.iter_mut().enumerate() { for (x, block_ptr) in row.iter_mut().enumerate() { let coord = Vec2(x as i64, y as i64); *block_ptr = mapgen.get_tile(new_offset + coord); // Lifetime 'a for &i in block_ptr.layers.iter() { for j in i.get_collision_map() { collision_map.push(j); } } } } for (y, row) in self.chunk2.iter_mut().enumerate() { for (x, block_ptr) in row.iter_mut().enumerate() { let coord = Vec2(x as i64, y as i64); *block_ptr = mapgen.get_tile(new_offset + coord + Vec2(CHUNK_SIZE, 0)); for &i in block_ptr.layers.iter() { for j in i.get_collision_map() { collision_map.push(j); } } } } for (y, row) in self.chunk3.iter_mut().enumerate() { for (x, block_ptr) in row.iter_mut().enumerate() { let coord = Vec2(x as i64, y as i64); *block_ptr = mapgen.get_tile(new_offset + coord + Vec2(0, CHUNK_SIZE)); for &i in block_ptr.layers.iter() { for j in i.get_collision_map() { collision_map.push(j); } } } } for (y, row) in self.chunk4.iter_mut().enumerate() { for (x, block_ptr) in row.iter_mut().enumerate() { let coord = Vec2(x as i64, y as i64); *block_ptr = mapgen.get_tile(new_offset + coord + Vec2(CHUNK_SIZE, CHUNK_SIZE)); for &i in block_ptr.layers.iter() { for j in i.get_collision_map() { collision_map.push(j); } } } } self.offset = new_offset; for i in collision_map { if (i - self.offset).x() < CHUNK_SIZE && (i - self.offset).y() < CHUNK_SIZE { let coord = i - self.offset; self.chunk1[coord.y() as usize][coord.x() as usize].solid = true; } else if (i - self.offset).x() >= CHUNK_SIZE && (i - self.offset).y() < CHUNK_SIZE { let coord = i - self.offset - Vec2(0, CHUNK_SIZE); self.chunk2[coord.y() as usize][coord.x() as usize].solid = true; } else if (i - self.offset).x() < CHUNK_SIZE && (i - self.offset).y() >= CHUNK_SIZE { let coord = i - self.offset - Vec2(CHUNK_SIZE, 0); self.chunk3[coord.y() as usize][coord.x() as usize].solid = true; } else if (i - self.offset).x() >= CHUNK_SIZE && (i - self.offset).y() >= CHUNK_SIZE { let coord = i - self.offset - Vec2(CHUNK_SIZE, CHUNK_SIZE); self.chunk3[coord.y() as usize][coord.x() as usize].solid = true; } } } } impl<'a> TileMap<'a> for Cache<'a> { fn get_tile(&self, pos: Vec2<i64>) -> Tile<'a> { let rel_coord = pos - self.offset; // TODO: Handle error cases where requested tile is off cache if rel_coord.x() < CHUNK_SIZE && rel_coord.y() < CHUNK_SIZE { self.chunk1.clone()[rel_coord.y() as usize][rel_coord.x() as usize] } else if rel_coord.x() >= CHUNK_SIZE && rel_coord.y() < CHUNK_SIZE { self.chunk2.clone()[rel_coord.y() as usize][rel_coord.x() as usize] } else if rel_coord.x() < CHUNK_SIZE && rel_coord.y() >= CHUNK_SIZE { self.chunk3.clone()[rel_coord.y() as usize][rel_coord.x() as usize] } else if rel_coord.x() >= CHUNK_SIZE && rel_coord.y() >= CHUNK_SIZE { self.chunk4.clone()[rel_coord.y() as usize][rel_coord.x() as usize] } else { Tile { layers: vec![], solid: false, } } } // TODO: Add method which_chunk } // TODO: Implement tilemap for cache. <file_sep>//! Traits, structs, and other objects for the game // TODO: Make more use of modules here: mod angle; mod config; pub mod map; pub mod util; mod vec2; pub mod cam; pub mod object; mod prop; mod entity; pub mod matter; pub mod cache; pub use self::object::{Move, Sprite, Position, Dir}; pub use self::angle::Angle; pub use self::config::Config; pub use self::map::{Map, Tile, TileMap}; pub use self::vec2::Vec2; pub use self::prop::{Prop}; pub use self::entity::{Entity, Id, Event}; pub use self::matter::{Matter}; <file_sep>use std::collections::BTreeMap; use core::Vec2; mod error; mod load; mod occupied_tile_data; mod sprite_data; pub use self::error::{LoadModelError, ModelError}; /// A frame, i.e. a sprite cutted out of a sprite sheet. #[derive(Clone, Debug)] pub struct Frame { cut_from: Vec2<u16>, cut_offset: Vec2<i8>, size: Vec2<u16>, pin_to: Vec2<i16>, pin_offset: Vec2<i8>, } /// A sprite #[derive(Clone, Debug)] pub struct Sprite { resource: usize, frames: Vec<Frame>, } impl Sprite { /// Create new sprite pub fn new(resource: usize, frames: Vec<Frame>) -> Sprite { Sprite { resource: resource, frames: frames } } } /// Model data: data about a given model #[derive(Debug)] pub struct ModelData { sprite_data: BTreeMap<String, Sprite>, occupied_tiles: Vec<Vec2<i8>>, } <file_sep>use std::collections::HashMap; use std::error::Error; use std::fmt; use std::mem; use opengl_graphics::Texture; pub struct TextureManager { cache: HashMap<String, Texture> } impl TextureManager { pub fn new() -> TextureManager { TextureManager { cache: HashMap::new() } } pub fn get(&mut self, path: &str) -> Result<&Texture, LoadTextureError> { // Thank you, qrlpx in #rust on Moznet. // TODO: Fix when borrow checker gets smarter. // related issue: https://github.com/rust-lang/rust/issues/6393 // related rfc: https://github.com/rust-lang/rfcs/issues/811 // article (#2): http://blog.ezyang.com/2013/12/two-bugs-in-the-borrow-checker-every-rust-developer-should-know-about/ let self_dup: &Self = unsafe { mem::transmute(&*self) }; if let Some(t) = self_dup.cache.get(path) { return Ok(t); } self.cache.insert(path.to_string(), try!(Texture::from_path(path))); Ok(&self.cache[path]) } } // TODO fix `Texture::from_path` to do more robust error handling #[derive(Debug)] pub struct LoadTextureError { message: String } impl LoadTextureError { pub fn new(message: String) -> LoadTextureError { LoadTextureError { message: message } } } // TODO remove this as soon as `Texture::from_path` is fixed impl From<String> for LoadTextureError { fn from(s: String) -> LoadTextureError { LoadTextureError::new(s) } } impl fmt::Display for LoadTextureError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { f.write_fmt(format_args!("LoadTextureError: {}", self.message)) } } impl Error for LoadTextureError { fn description(&self) -> &str { "problem loading the texture (it probably doesn't exist)" } }
c54841a8e964fd7e1d3487cab2a34b84ed5433e6
[ "Markdown", "Rust", "TOML" ]
47
Rust
Ticki/Open-Sea
f909aff9b244df40d046ef07f51443a434522d4c
c27e2963e16947286acf9f2a4ba4f083f8cf4a1b
refs/heads/master
<file_sep>package project.vo_mypage; public class UserInfo2 { private String id; private String pass; private String email; private String phonNum; private String address; public UserInfo2() { super(); // TODO Auto-generated constructor stub } public UserInfo2(String id, String pass, String email, String phonNum, String address) { super(); this.id = id; this.pass = <PASSWORD>; this.email = email; this.phonNum = phonNum; this.address = address; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhonNum() { return phonNum; } public void setPhonNum(String phonNum) { this.phonNum = phonNum; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }<file_sep>package project.mvc.main; import java.io.IOException; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import board.dto.BoardDTO; import project.dao.main.MainLeft_Dao; import project.dao.main.Main_Dao; import project.vo.login.Member; /** * Servlet implementation class MainLeftController */ @WebServlet(name = "mainLeft.do", urlPatterns = { "/mainLeft.do" }) public class MainLeftController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MainLeftController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); HttpSession session = request.getSession(); Member m = (Member)session.getAttribute("member"); // 1. 요청값 처리.. String id = request.getParameter("id"); String pass = request.getParameter("pass"); MainLeft_Dao dao = new MainLeft_Dao(); Main_Dao dao2 = new Main_Dao(); // 전체글 가져오기 DAO ArrayList<BoardDTO> blist = dao2.boardAllList(); ArrayList<BoardDTO> alist = dao2.AnnouceList(); session.setAttribute("blist", blist); // 전체글 리스트 session.setAttribute("alist", alist); // 공지사항 리스트 // 2. 모델 데이터 처리 // 1) 초기 페이지 - 초기 로그인 페이지 설정. // 2) 입력 후 페이지. - 입력 후 정상일 때 페이지 설정. if(m != null) { id = m.getId(); pass = m.getPass(); } if(id==null) id=""; if(pass==null) pass=""; String page = "login/login.jsp"; if(!id.equals("") && !pass.equals("") ) { Member mem = dao.login(new Member(id,pass)); if(mem!=null) { // request.setAttribute("isSuccess", true); // DB 연동의 경우, session값을 설정해서 model데이터를 매핑한다. session.setAttribute("member", dao.login(mem)); session.setAttribute("grade", dao.getGrade(mem)); session.setAttribute("id", id); page="main_include.jsp"; }else { // request.setAttribute("isSuccess", false); } } // 3. 화면단 호출. RequestDispatcher rd = request.getRequestDispatcher(page); rd.forward(request, response); } } <file_sep>package board.controller; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import board.dao.BoardDao; import board.dto.BoardDTO; /** * Servlet implementation class writeUpdateController */ @WebServlet(name = "writeUpdate.do", urlPatterns = { "/writeUpdate.do" }) public class WriteUpdateController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public WriteUpdateController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // 요청값 받기 request.setCharacterEncoding("utf-8"); String numS = request.getParameter("num"); String title = request.getParameter("title"); String content = request.getParameter("content"); String category = request.getParameter("category"); String proc = request.getParameter("proc"); HttpSession session = request.getSession(); if(numS!=null) session.setAttribute("num", new Integer(numS)); //int num = Integer.parseInt(numS); int num = 0; if(session != null) { session.setAttribute("category", category); category = (String)session.getAttribute("category"); num = (Integer)session.getAttribute("num"); } if(title==null) title=""; if(content==null) content=""; if(category==null) category=""; System.out.println("##title:"+title); System.out.println("##content:"+content); System.out.println("##num:"+num); System.out.println("##category:"+category); System.out.println("##proc: " + proc); // 모델 데이터 BoardDao dao = new BoardDao(); if(proc!=null) { if(proc.equals("upt")) { BoardDTO upt = new BoardDTO(num,title,content,category); dao.updateWrite(upt); } } request.setAttribute("dto",dao.getWrite(num,category)); // 페이지 이동 String page ="view\\board\\board_update.jsp"; RequestDispatcher rd = request.getRequestDispatcher(page); rd.forward(request, response); } } <file_sep>DROP TABLE board; CREATE TABLE board( num number, --게시물번호 id varchar2(50) NOT NULL, --작성자 title varchar2(50) NOT NULL, --제목 category varchar2(30), --카테고리 reg_date DATE default sysdate, --작성일자 readcount number, --조회수 favor NUMBER, content varchar2(4000) NOT NULL ); DROP SEQUENCE board1_seq; DROP SEQUENCE board2_seq; DROP SEQUENCE board3_seq; DROP SEQUENCE board4_seq; DROP SEQUENCE board5_seq; DROP SEQUENCE board6_seq; DROP SEQUENCE board7_seq; CREATE SEQUENCE board1_seq INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 9999; CREATE SEQUENCE board2_seq INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 9999; CREATE SEQUENCE board3_seq INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 9999; CREATE SEQUENCE board4_seq INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 9999; CREATE SEQUENCE board5_seq INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 9999; CREATE SEQUENCE board6_seq INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 9999; CREATE SEQUENCE board7_seq INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 9999; SELECT * FROM board ORDER BY num desc; -- 글 등록 INSERT INTO board(num,writer,title,category,readcount,favor,content) values((SELECT nvl(max(num)+1,1) FROM board), '작성자','제목','카테고리',0,0, '내용'); -- 글 수정 UPDATE BOARD SET title='제목(변경)', content='내용(변경)' WHERE num=1; SELECT * FROM board ORDER BY num desc; DELETE FROM board WHERE num=3 AND category='Java'; -- 조회수 증가 UPDATE BOARD SET readcount = readcount+1 WHERE num=1; SELECT * FROM board; INSERT INTO board(num,writer,title,readcount,favor,content) values((SELECT nvl(max(num)+1,1) FROM board), '작성자','제목',0,0, '내용'); CREATE TABLE MEMBER( id varchar2(30), pass varchar2(30), name varchar2(50), email varchar2(100), postcnt NUMBER, commentcnt NUMBER, warncnt number ); INSERT INTO MEMBER values('himan','7777','홍길동','<EMAIL>',7,5,0); CREATE TABLE member_grade( grade varchar2(10), scnt NUMBER, ecnt number ); INSERT INTO member_grade values('IRON',0,5); INSERT INTO member_grade values('BRONZE',6,10); INSERT INTO member_grade values('SILVER',11,15); INSERT INTO member_grade values('GOLD',16,20); INSERT INTO member_grade values('PLATINUM',21,100); INSERT INTO member_grade values('DIAMOND',101,1000); INSERT INTO member_grade values('MASTER',1000,2000); CREATE TABLE com( table_id NUMBER, text_id NUMBER, comment_id NUMBER, comment_type NUMBER, cnt NUMBER, guest_id varchar2(30), content varchar2(100), written_date DATE, likes NUMBER, dislike NUMBER ); DROP TABLE com; SELECT * FROM com; INSERT INTO com values(1,1,1,1,1,'tes','저작권 등 다른 사람의 권리를 침해하거나 명예를 훼손하는 게시물',sysdate,10,3); INSERT INTO com values(1,1,2,1,1,'qqq','이용약관 및 관련 법률에 의해 제재를 받을 수 있습니다',sysdate,5,1); INSERT INTO com values(1,1,3,1,1,'plwog','건전한 토론문화와 양질의 댓글 문화를 위해',sysdate,15,2); INSERT INTO com values(1,1,1,2,1,'bjwiow','이용약관 및 관련 법률에 의해 제재를 받을 수 있습니다',sysdate,0,0); INSERT INTO com values(1,1,1,2,1,'lavkie','종교 등을 비하하는 단어들은 표시가 제한',sysdate,0,10); INSERT INTO com values(1,1,1,2,1,'hhddntr','대댓글 3',sysdate,0,0); INSERT INTO com values(1,1,1,2,1,'rtn','대댓글4',sysdate,0,0); INSERT INTO com values(1,1,1,2,1,'boprer','대댓글5',sysdate,0,0); INSERT INTO com values(1,1,2,2,1,'wefjh','대댓글6',sysdate,0,0); INSERT INTO com values(1,1,2,2,1,'hello man','suprise lol',sysdate,0,0); INSERT INTO com values(1,1,4,1,2,'tes','같은 아이디일 때 상황을 확인하기 위한 댓글',sysdate,0,10); INSERT INTO com values(1,1,1,2,3,'tes','같은 아이디일 때 상황을 확인하기 위한 대댓글',sysdate,5,10); INSERT INTO com values(1,1,2,2,4,'tes','같은 아이디일 때 상황을 확인하기 위한 대댓글22',sysdate,1,2); -- 테이블마다 시퀀스 생성 COMMENT_ID CREATE SEQUENCE table01_seq INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 9999; DROP TABLE com; DROP SEQUENCE table01_seq; --- 관리자 글쓰기 DROP TABLE notice; CREATE TABLE notice( num number, --게시물번호 id varchar2(50) NOT NULL, --작성자 title varchar2(50) NOT NULL, --제목 category varchar2(30), --카테고리 reg_date DATE default sysdate, --작성일자 readcount number, --조회수 favor NUMBER, content varchar2(4000) NOT NULL ); INSERT INTO board(num,id,title,category,readcount,favor,content) values((SELECT nvl(max(num)+1,1) FROM notice), '관리자','제목','카테고리',0,0, '내용'); SELECT * FROM notice; SELECT * FROM MEMBER; INSERT INTO MEMBER values('admin','7777','관리자','<EMAIL>',0,0,0); UPDATE NOTICE SET title = '', content = '' WHERE num=1; SELECT * FROM board; SELECT * FROM notice;<file_sep>package member.dto; public class MemberDTO { /* CREATE TABLE MEMBER( id varchar2(30) PRIMARY KEY, pass varchar2(30), name varchar2(50), email varchar2(100), postcnt NUMBER, commentcnt NUMBER, warncnt number ); */ private String id; private String pass; private String name; private String email; private int postcnt; private int commentcnt; private int warncnt; public MemberDTO() { super(); // TODO Auto-generated constructor stub } public MemberDTO(String id, String pass, String name, String email, int postcnt, int commentcnt, int warncnt) { super(); this.id = id; this.pass = pass; this.name = name; this.email = email; this.postcnt = postcnt; this.commentcnt = commentcnt; this.warncnt = warncnt; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getPostcnt() { return postcnt; } public void setPostcnt(int postcnt) { this.postcnt = postcnt; } public int getCommentcnt() { return commentcnt; } public void setCommentcnt(int commentcnt) { this.commentcnt = commentcnt; } public int getWarncnt() { return warncnt; } public void setWarncnt(int warncnt) { this.warncnt = warncnt; } } <file_sep>package project.vo.login; public class Member { private String id; private String pass; private String name; private String email; private int postcnt; private int commentcnt; private int warncnt; private String grade; public Member() { super(); // TODO Auto-generated constructor stub } public Member(String id, String pass) { super(); this.id = id; this.pass = pass; } public Member(String id, String pass, String name, String email, int postcnt, int commentcnt, int warncnt) { super(); this.id = id; this.pass = pass; this.name = name; this.email = email; this.postcnt = postcnt; this.commentcnt = commentcnt; this.warncnt = warncnt; } public Member(String id, String pass, String name, String email) { super(); this.id = id; this.pass = pass; this.name = name; this.email = email; } public Member(String id, String pass, String name, String email, int postcnt, int commentcnt, int warncnt, String grade) { super(); this.id = id; this.pass = pass; this.name = name; this.email = email; this.postcnt = postcnt; this.commentcnt = commentcnt; this.warncnt = warncnt; this.grade = grade; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getPostcnt() { return postcnt; } public void setPostcnt(int postcnt) { this.postcnt = postcnt; } public int getCommentcnt() { return commentcnt; } public void setCommentcnt(int commentcnt) { this.commentcnt = commentcnt; } public int getWarncnt() { return warncnt; } public void setWarncnt(int warncnt) { this.warncnt = warncnt; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } } <file_sep>package project.vo_mypage; import java.util.Date; public class Board { private int num; private String id; private String title; private String category; private Date reg_date; private int readcount; private int favor; private String content; public Board() { super(); // TODO Auto-generated constructor stub } public Board(int num, String id, String title, String category, Date reg_date, int readcount, int favor, String content) { super(); this.num = num; this.id = id; this.title = title; this.category = category; this.reg_date = reg_date; this.readcount = readcount; this.favor = favor; this.content = content; } public Board(int num, String title, String category, Date reg_date) { super(); this.num = num; this.title = title; this.category = category; this.reg_date = reg_date; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Date getReg_date() { return reg_date; } public void setReg_date(Date reg_date) { this.reg_date = reg_date; } public int getReadcount() { return readcount; } public void setReadcount(int readcount) { this.readcount = readcount; } public int getFavor() { return favor; } public void setFavor(int favor) { this.favor = favor; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }<file_sep>package board.controller; import java.io.IOException; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import board.dao.BoardDao; import board.dto.BoardDTO; /** * Servlet implementation class WriteDeleteController */ @WebServlet(name = "writeDelete.do", urlPatterns = { "/writeDelete.do" }) public class WriteDeleteController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public WriteDeleteController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); BoardDao dao = new BoardDao(); HttpSession session = request.getSession(); String id=(String) session.getAttribute("id"); String num = request.getParameter("num"); String category = request.getParameter("category"); // 아이디가 아이디와 같아야 함 그래야 삭제 가능 if(request.getParameter("id").equals(id)) { BoardDTO del = new BoardDTO(Integer.parseInt(num),category); dao.delete(del); } ArrayList<BoardDTO> list = dao.boardList(category); request.setAttribute("dlist", list); String page ="view\\board\\board_list.jsp"; RequestDispatcher rd = request.getRequestDispatcher(page); rd.forward(request, response); } } <file_sep>package board.controller; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import board.dao.comment_dao; import board.dao.table_dao; import project.vo.login.Member; /** * Servlet implementation class ComController */ @WebServlet(name = "com.do", urlPatterns = { "/com.do" }) public class ComController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ComController() { super(); // TODO Auto-generated constructor stub } public String pStr(String s) { String ret=""; if( s != null) ret = s; return ret; } public int pInt(String s) { int ret = 0; try { ret = Integer.parseInt(s); } catch(Exception e) { System.out.println("pInt: " + e.getMessage()); } return ret; } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); String id = ""; String page = ""; int table_id = 0; int text_id = 0; String cate = ""; String table_idS = request.getParameter("tnum"); String text_idS = request.getParameter("wnum"); //String comment_idS = request.getParameter("comment_id"); //String comment_type = request.getParameter("comment_type"); //comment_type = pStr(comment_type); //String comment = request.getParameter("comment"); //comment = pStr(comment); System.out.println("table_idS1: " + table_idS); System.out.println("text_idS1: " + text_idS); HttpSession session = request.getSession(false); if(table_idS != null) { session.setAttribute("table_id", new Integer(table_idS)); } if(text_idS != null) { session.setAttribute("text_id", new Integer(text_idS)); } Member m = (Member)session.getAttribute("member"); if(session != null) { id = m.getId(); //id = (String)session.getAttribute("id"); table_id = (Integer)session.getAttribute("table_id"); text_id = (Integer)session.getAttribute("text_id"); //cate = (String)session.getAttribute("cate"); //System.out.println("cate: " + cate); page = "view\\board\\comment.jsp"; } else page = "comment\\login.jsp"; System.out.println("table_id2: " + table_id); System.out.println("text_id2: " + text_id); // System.out.println("id: " + id); // System.out.println("tnum: " + table_id); // System.out.println("wnum: " + text_id); // System.out.println("comment_type: " + comment_type); // System.out.println("comment: " + comment); comment_dao dao = new comment_dao(); //table_dao tdao = new table_dao(); //ListDao ldao = new ListDao(); String proc = request.getParameter("proc"); if(proc != null) { if(proc.equals("ins")) { System.out.println("등록!!"); if(pInt(request.getParameter("comment_type")) == 1){ System.out.println("댓글!!"); dao.insertComment(table_id, text_id, pInt(request.getParameter("comment_type")), id,pStr(request.getParameter("comment"))); } else if (pInt(request.getParameter("comment_type")) == 2){ System.out.println("대댓글!!"); dao.insertSubComment(table_id, text_id, pInt(request.getParameter("comment_id")), pInt(request.getParameter("comment_type")), id,pStr(request.getParameter("comment"))); } int commentCnt = dao.getMemComCnt(id); // member 테이블의 댓글작성카운트++ System.out.println("작성 갯수: " + commentCnt); dao.PlusComCnt(id, commentCnt); commentCnt = dao.getMemComCnt(id); System.out.println("작성 갯수(update): " + commentCnt); // 댓글에 대한 상태 저장 테이블, 새로운 열 추가 ( 내가 생성한 것이기 때문에 필요없음) /* dao.insertLike(id, table_id, text_id); System.out.println("새로운 댓글에 대한 좋아요 상태 확인 객체 생성!!"); */ } if(proc.equals("del")) { System.out.println("삭제" + (request.getParameter("cnt"))); dao.delComment(id, pInt((request.getParameter("cnt")))); int commentCnt = dao.getMemComCnt(id); System.out.println("작성 갯수: " + commentCnt); dao.MinusComCnt(id, commentCnt); commentCnt = dao.getMemComCnt(id); System.out.println("작성 갯수(update): " + commentCnt); } if(proc.equals("like")) { System.out.println("좋아요(cnt): " + pInt(request.getParameter("cnt"))); // type 0 : 게시글에 대한 좋아요 , 1 : 댓글, 대댓글 ==> cnt로 구분함 System.out.println("좋아요(type): " + pStr(request.getParameter("type"))); System.out.println("작성자(wid): " + pStr(request.getParameter("wid"))); String type = request.getParameter("type"); if(type.equals("1")) { // goodorhate 테이블에 있는지 확인 // 있다면 update, 없다면 생성 후 update dao.UpdateGood(id, pStr(request.getParameter("wid")), table_id, text_id, pInt(request.getParameter("cnt"))); // 작성자 id 보내야함 dao.UpdateLike(pStr(request.getParameter("wid")), id, table_id, text_id, pInt(request.getParameter("cnt"))); } else { dao.UpdateGood(id, pStr(request.getParameter("wid")), table_id, text_id, 0); dao.UpdateLike(pStr(request.getParameter("wid")),id, table_id, text_id, 0); } } } // 글 내용 가져오기 ( tab 객체 1개) //request.setAttribute("content",tdao.getTab(table_id,text_id)); //request.setAttribute("content", ldao.categoryList("")); // 게시판id, 글id , 회원아이디 가져와야함 request.setAttribute("comList", dao.commentaryList()); // 해당 게시글 안의 댓글 총 숫자 request.setAttribute("getComTotalCnt",dao.getComTotalCnt(table_id, text_id)); RequestDispatcher rd = request.getRequestDispatcher(page); rd.forward(request, response); } } <file_sep>package board.dto; public class Tab { private int table_id; private String table_name; private int text_id; private String title; private String guest_id; private String content; public Tab() { super(); // TODO Auto-generated constructor stub } public Tab(int table_id, String table_name, int text_id, String title, String guest_id, String content) { super(); this.table_id = table_id; this.table_name = table_name; this.text_id = text_id; this.title = title; this.guest_id = guest_id; this.content = content; } public int getTable_id() { return table_id; } public void setTable_id(int table_id) { this.table_id = table_id; } public String getTable_name() { return table_name; } public void setTable_name(String table_name) { this.table_name = table_name; } public int getText_id() { return text_id; } public void setText_id(int text_id) { this.text_id = text_id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getGuest_id() { return guest_id; } public void setGuest_id(String guest_id) { this.guest_id = guest_id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } <file_sep>package board.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import board.dto.BoardDTO; public class ListDao { private Connection con; private PreparedStatement pstmt; private ResultSet rs; public void setCon() throws SQLException{ try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String info = "jdbc:oracle:thin:@localhost:1521:XE"; con = DriverManager.getConnection(info,"scott","tiger"); System.out.println("접속성공"); } public ArrayList<BoardDTO> categoryList(String category){ //ArrayList<Emp> list = null; ArrayList<BoardDTO> list = new ArrayList<BoardDTO>(); // 1. 공통메서드 호출 try { setCon(); // 2. Statement 객체 생성 (연결객체 - Connection) String sql = "SELECT * FROM board\r\n" + "WHERE category like '%'||lower( ? )||'%' \r\n" + "ORDER BY num DESC"; System.out.println(sql); pstmt = con.prepareStatement(sql); pstmt.setString(1, category); // 3. ResultSet 객체 생성 (대화객체 - Statement) rs = pstmt.executeQuery(); while(rs.next()) { BoardDTO e = new BoardDTO(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4), rs.getDate(5),rs.getInt(6),rs.getInt(7),rs.getString(8)); // 2. ArrayList에 할당. list.add(e); } System.out.println("객체의 갯수: " + list.size()); System.out.println("2번째 행의 name: " + list.get(1).getCategory()); // 4. 자원의 해제 rs.close(); pstmt.close(); con.close(); // 5. 예외 처리 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("DB관련 에러: " + e.getMessage()); } catch(Exception e) { e.printStackTrace(); System.out.println("기타 에러: " + e.getMessage()); } return list; } public static void main(String[] args) { ListDao dao = new ListDao(); dao.categoryList(""); } } <file_sep>package favor.dto; public class favorDTO { private String id; private int num; public favorDTO() { super(); // TODO Auto-generated constructor stub } public favorDTO(String id, int num) { super(); this.id = id; this.num = num; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } } <file_sep>package project.vo.login; public class Customer { private String customer_id; private String pw; private String name; private String address; private String email; private String phone; private char gender; private String birth_date; private String reg_date; public Customer() { super(); // TODO Auto-generated constructor stub } public Customer(String customer_id, String pw, String name, String address, String email, String phone, char gender, String birth_date, String reg_date) { super(); this.customer_id = customer_id; this.pw = pw; this.name = name; this.address = address; this.email = email; this.phone = phone; this.gender = gender; this.birth_date = birth_date; this.reg_date = reg_date; } public Customer(String customer_id, String pw) { super(); this.customer_id = customer_id; this.pw = pw; } public Customer(String customer_id) { super(); this.customer_id = customer_id; } public String getCustomer_id() { return customer_id; } public void setCustomer_id(String customer_id) { this.customer_id = customer_id; } public String getPw() { return pw; } public void setPw(String pw) { this.pw = pw; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } public String getBirth_date() { return birth_date; } public void setBirth_date(String birth_date) { this.birth_date = birth_date; } public String getReg_date() { return reg_date; } public void setReg_date(String reg_date) { this.reg_date = reg_date; } } <file_sep>package board.controller; import java.io.IOException; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import board.dao.BoardDao; import board.dto.BoardDTO; /** * Servlet implementation class boardNoticeController */ @WebServlet(name = "noticeList.do", urlPatterns = { "/noticeList.do" }) public class boardNoticeController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public boardNoticeController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // 1. 요청값 받기 BoardDao dao = new BoardDao(); ArrayList<BoardDTO> list = dao.noticeList(); // 2. 모델 데이터 request.setAttribute("nlist", list); HttpSession session = request.getSession(); String id=(String) session.getAttribute("id"); // session id // 3. 뷰단에 넘기기 String page="view\\board\\board_list_notice.jsp"; RequestDispatcher rd = request.getRequestDispatcher(page); rd.forward(request, response); } } <file_sep>package board.dao; public class WriteDao { } <file_sep>package project.vo_mypage; public class Board2 { private int bnum; private Board boardList; public Board2() { super(); // TODO Auto-generated constructor stub } public Board2(int bnum) { super(); this.bnum = bnum; } public Board2(int bnum, Board boardList) { super(); this.bnum = bnum; this.boardList = boardList; } public int getBnum() { return bnum; } public void setBnum(int bnum) { this.bnum = bnum; } public Board getBoardList() { return boardList; } public void setBoardList(Board boardList) { this.boardList = boardList; } }<file_sep>package board.controller; import java.io.IOException; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import board.dao.BoardDao; import board.dto.BoardDTO; import project.vo.login.Member; /** * Servlet implementation class boardListController */ //http://localhost:7080/cosa/boardList.do @WebServlet(name = "boardList.do", urlPatterns = { "/boardList.do" }) public class boardListController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public boardListController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); HttpSession session = request.getSession(false); Member mem = null; String category = request.getParameter("category"); if(category == null || category.equals("")) category = ""; else session.setAttribute("cate", category); String page= ""; if(session != null) { mem = (Member)session.getAttribute("member"); page = "view\\board\\board_list.jsp"; } else page = "main_include.jsp"; BoardDao dao = new BoardDao(); //ArrayList<BoardDTO> list = dao.boardList(); ArrayList<BoardDTO> list = dao.boardList(category); // 2. 모델 데이터 request.setAttribute("dlist", list); // 2. 모델 데이터 String categVal = request.getParameter("category"); if(categVal=="전체") categVal = ""; // 3. 뷰단에 넘기기 RequestDispatcher rd = request.getRequestDispatcher(page); rd.forward(request, response); } }
fbf248809c2b4d87312fdc0291e5103b7a1cb8a7
[ "Java", "SQL" ]
17
Java
dltnals5763/cosamo
0c6aefaa9f33e30fff0ae0e54fad94998321e934
54e46e05b9d54fa122ba1126b00628b9afbc11e4
refs/heads/master
<file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * ShippingRegion * * @ORM\Table(name="shipping_region") * @ORM\Entity */ class ShippingRegion { /** * @var int * * @ORM\Column(name="shipping_region_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $shippingRegionId; /** * @var string * * @ORM\Column(name="shipping_region", type="string", length=100, nullable=false) */ private $shippingRegion; public function getShippingRegionId(): ?int { return $this->shippingRegionId; } public function getShippingRegion(): ?string { return $this->shippingRegion; } public function setShippingRegion(string $shippingRegion): self { $this->shippingRegion = $shippingRegion; return $this; } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * Audit * * @ORM\Table(name="audit", indexes={@ORM\Index(name="idx_audit_order_id", columns={"order_id"})}) * @ORM\Entity */ class Audit { /** * @var int * * @ORM\Column(name="audit_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $auditId; /** * @var int * * @ORM\Column(name="order_id", type="integer", nullable=false) */ private $orderId; /** * @var \DateTime * * @ORM\Column(name="created_on", type="datetime", nullable=false) */ private $createdOn; /** * @var string * * @ORM\Column(name="message", type="text", length=65535, nullable=false) */ private $message; /** * @var int * * @ORM\Column(name="code", type="integer", nullable=false) */ private $code; public function getAuditId(): ?int { return $this->auditId; } public function getOrderId(): ?int { return $this->orderId; } public function setOrderId(int $orderId): self { $this->orderId = $orderId; return $this; } public function getCreatedOn(): ?\DateTimeInterface { return $this->createdOn; } public function setCreatedOn(\DateTimeInterface $createdOn): self { $this->createdOn = $createdOn; return $this; } public function getMessage(): ?string { return $this->message; } public function setMessage(string $message): self { $this->message = $message; return $this; } public function getCode(): ?int { return $this->code; } public function setCode(int $code): self { $this->code = $code; return $this; } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * Customer * * @ORM\Table(name="customer", uniqueConstraints={@ORM\UniqueConstraint(name="idx_customer_email", columns={"email"})}, indexes={@ORM\Index(name="idx_customer_shipping_region_id", columns={"shipping_region_id"})}) * @ORM\Entity * @ORM\Entity(repositoryClass="App\Repository\CustomerRepository") */ class Customer { /** * @var int * * @ORM\Column(name="customer_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $customerId; /** * @var string * * @ORM\Column(name="name", type="string", length=50, nullable=false) */ private $name; /** * @var string * * @ORM\Column(name="email", type="string", length=100, nullable=false) */ private $email; /** * @var string * * @ORM\Column(name="password", type="string", length=50, nullable=false) */ private $password; /** * @var string|null * * @ORM\Column(name="credit_card", type="text", length=65535, nullable=true) */ private $creditCard; /** * @var string|null * * @ORM\Column(name="address_1", type="string", length=100, nullable=true) */ private $address1; /** * @var string|null * * @ORM\Column(name="address_2", type="string", length=100, nullable=true) */ private $address2; /** * @var string|null * * @ORM\Column(name="city", type="string", length=100, nullable=true) */ private $city; /** * @var string|null * * @ORM\Column(name="region", type="string", length=100, nullable=true) */ private $region; /** * @var string|null * * @ORM\Column(name="postal_code", type="string", length=100, nullable=true) */ private $postalCode; /** * @var string|null * * @ORM\Column(name="country", type="string", length=100, nullable=true) */ private $country; /** * @var int * * @ORM\Column(name="shipping_region_id", type="integer", nullable=false, options={"default"="1"}) */ private $shippingRegionId = '1'; /** * @var string|null * * @ORM\Column(name="day_phone", type="string", length=100, nullable=true) */ private $dayPhone; /** * @var string|null * * @ORM\Column(name="eve_phone", type="string", length=100, nullable=true) */ private $evePhone; /** * @var string|null * * @ORM\Column(name="mob_phone", type="string", length=100, nullable=true) */ private $mobPhone; public function getCustomerId(): ?int { return $this->customerId; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getEmail(): ?string { return $this->email; } public function setEmail(string $email): self { $this->email = $email; return $this; } public function getPassword(): ?string { return $this->password; } public function setPassword(string $password): self { $this->password = $password; return $this; } public function getCreditCard(): ?string { return $this->creditCard; } public function setCreditCard(?string $creditCard): self { $this->creditCard = $creditCard; return $this; } public function getAddress1(): ?string { return $this->address1; } public function setAddress1(?string $address1): self { $this->address1 = $address1; return $this; } public function getAddress2(): ?string { return $this->address2; } public function setAddress2(?string $address2): self { $this->address2 = $address2; return $this; } public function getCity(): ?string { return $this->city; } public function setCity(?string $city): self { $this->city = $city; return $this; } public function getRegion(): ?string { return $this->region; } public function setRegion(?string $region): self { $this->region = $region; return $this; } public function getPostalCode(): ?string { return $this->postalCode; } public function setPostalCode(?string $postalCode): self { $this->postalCode = $postalCode; return $this; } public function getCountry(): ?string { return $this->country; } public function setCountry(?string $country): self { $this->country = $country; return $this; } public function getShippingRegionId(): ?int { return $this->shippingRegionId; } public function setShippingRegionId(int $shippingRegionId): self { $this->shippingRegionId = $shippingRegionId; return $this; } public function getDayPhone(): ?string { return $this->dayPhone; } public function setDayPhone(?string $dayPhone): self { $this->dayPhone = $dayPhone; return $this; } public function getEvePhone(): ?string { return $this->evePhone; } public function setEvePhone(?string $evePhone): self { $this->evePhone = $evePhone; return $this; } public function getMobPhone(): ?string { return $this->mobPhone; } public function setMobPhone(?string $mobPhone): self { $this->mobPhone = $mobPhone; return $this; } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * ProductCategory * * @ORM\Table(name="product_category") * @ORM\Entity */ class ProductCategory { /** * @var int * * @ORM\Column(name="product_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $productId; /** * @var int * * @ORM\Column(name="category_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $categoryId; public function getProductId(): ?int { return $this->productId; } public function getCategoryId(): ?int { return $this->categoryId; } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * Review * * @ORM\Table(name="review", indexes={@ORM\Index(name="idx_review_product_id", columns={"product_id"}), @ORM\Index(name="idx_review_customer_id", columns={"customer_id"})}) * @ORM\Entity */ class Review { /** * @var int * * @ORM\Column(name="review_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $reviewId; /** * @var int * * @ORM\Column(name="customer_id", type="integer", nullable=false) */ private $customerId; /** * @var int * * @ORM\Column(name="product_id", type="integer", nullable=false) */ private $productId; /** * @var string * * @ORM\Column(name="review", type="text", length=65535, nullable=false) */ private $review; /** * @var int * * @ORM\Column(name="rating", type="smallint", nullable=false) */ private $rating; /** * @var \DateTime * * @ORM\Column(name="created_on", type="datetime", nullable=false) */ private $createdOn; public function getReviewId(): ?int { return $this->reviewId; } public function getCustomerId(): ?int { return $this->customerId; } public function setCustomerId(int $customerId): self { $this->customerId = $customerId; return $this; } public function getProductId(): ?int { return $this->productId; } public function setProductId(int $productId): self { $this->productId = $productId; return $this; } public function getReview(): ?string { return $this->review; } public function setReview(string $review): self { $this->review = $review; return $this; } public function getRating(): ?int { return $this->rating; } public function setRating(int $rating): self { $this->rating = $rating; return $this; } public function getCreatedOn(): ?\DateTimeInterface { return $this->createdOn; } public function setCreatedOn(\DateTimeInterface $createdOn): self { $this->createdOn = $createdOn; return $this; } } <file_sep><?php namespace App\Controller; use App\Entity\AttributeValue; use App\Form\AttributeValueType; use App\Repository\AttributeValueRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/attribute/value") */ class AttributeValueController extends AbstractController { /** * @Route("/", name="attribute_value_index", methods={"GET"}) */ public function index(AttributeValueRepository $attributeValueRepository): Response { return $this->render('attribute_value/index.html.twig', [ 'attribute_values' => $attributeValueRepository->findAll(), ]); } /** * @Route("/new", name="attribute_value_new", methods={"GET","POST"}) */ public function new(Request $request): Response { $attributeValue = new AttributeValue(); $form = $this->createForm(AttributeValueType::class, $attributeValue); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($attributeValue); $entityManager->flush(); return $this->redirectToRoute('attribute_value_index'); } return $this->render('attribute_value/new.html.twig', [ 'attribute_value' => $attributeValue, 'form' => $form->createView(), ]); } /** * @Route("/{attributeValueId}", name="attribute_value_show", methods={"GET"}) */ public function show(AttributeValue $attributeValue): Response { return $this->render('attribute_value/show.html.twig', [ 'attribute_value' => $attributeValue, ]); } /** * @Route("/{attributeValueId}/edit", name="attribute_value_edit", methods={"GET","POST"}) */ public function edit(Request $request, AttributeValue $attributeValue): Response { $form = $this->createForm(AttributeValueType::class, $attributeValue); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('attribute_value_index', [ 'attributeValueId' => $attributeValue->getAttributeValueId(), ]); } return $this->render('attribute_value/edit.html.twig', [ 'attribute_value' => $attributeValue, 'form' => $form->createView(), ]); } /** * @Route("/{attributeValueId}", name="attribute_value_delete", methods={"DELETE"}) */ public function delete(Request $request, AttributeValue $attributeValue): Response { if ($this->isCsrfTokenValid('delete'.$attributeValue->getAttributeValueId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->remove($attributeValue); $entityManager->flush(); } return $this->redirectToRoute('attribute_value_index'); } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * Orders * * @ORM\Table(name="orders", indexes={@ORM\Index(name="idx_orders_shipping_id", columns={"shipping_id"}), @ORM\Index(name="idx_orders_tax_id", columns={"tax_id"}), @ORM\Index(name="idx_orders_customer_id", columns={"customer_id"})}) * @ORM\Entity */ class Orders { /** * @var int * * @ORM\Column(name="order_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $orderId; /** * @var string * * @ORM\Column(name="total_amount", type="decimal", precision=10, scale=2, nullable=false, options={"default"="0.00"}) */ private $totalAmount = '0.00'; /** * @var \DateTime * * @ORM\Column(name="created_on", type="datetime", nullable=false) */ private $createdOn; /** * @var \DateTime|null * * @ORM\Column(name="shipped_on", type="datetime", nullable=true) */ private $shippedOn; /** * @var int * * @ORM\Column(name="status", type="integer", nullable=false) */ private $status = '0'; /** * @var string|null * * @ORM\Column(name="comments", type="string", length=255, nullable=true) */ private $comments; /** * @var int|null * * @ORM\Column(name="customer_id", type="integer", nullable=true) */ private $customerId; /** * @var string|null * * @ORM\Column(name="auth_code", type="string", length=50, nullable=true) */ private $authCode; /** * @var string|null * * @ORM\Column(name="reference", type="string", length=50, nullable=true) */ private $reference; /** * @var int|null * * @ORM\Column(name="shipping_id", type="integer", nullable=true) */ private $shippingId; /** * @var int|null * * @ORM\Column(name="tax_id", type="integer", nullable=true) */ private $taxId; public function getOrderId(): ?int { return $this->orderId; } public function getTotalAmount() { return $this->totalAmount; } public function setTotalAmount($totalAmount): self { $this->totalAmount = $totalAmount; return $this; } public function getCreatedOn(): ?\DateTimeInterface { return $this->createdOn; } public function setCreatedOn(\DateTimeInterface $createdOn): self { $this->createdOn = $createdOn; return $this; } public function getShippedOn(): ?\DateTimeInterface { return $this->shippedOn; } public function setShippedOn(?\DateTimeInterface $shippedOn): self { $this->shippedOn = $shippedOn; return $this; } public function getStatus(): ?int { return $this->status; } public function setStatus(int $status): self { $this->status = $status; return $this; } public function getComments(): ?string { return $this->comments; } public function setComments(?string $comments): self { $this->comments = $comments; return $this; } public function getCustomerId(): ?int { return $this->customerId; } public function setCustomerId(?int $customerId): self { $this->customerId = $customerId; return $this; } public function getAuthCode(): ?string { return $this->authCode; } public function setAuthCode(?string $authCode): self { $this->authCode = $authCode; return $this; } public function getReference(): ?string { return $this->reference; } public function setReference(?string $reference): self { $this->reference = $reference; return $this; } public function getShippingId(): ?int { return $this->shippingId; } public function setShippingId(?int $shippingId): self { $this->shippingId = $shippingId; return $this; } public function getTaxId(): ?int { return $this->taxId; } public function setTaxId(?int $taxId): self { $this->taxId = $taxId; return $this; } } <file_sep><?php namespace App\Controller; use App\Entity\ShippingRegion; use App\Form\ShippingRegionType; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/shipping/region") */ class ShippingRegionController extends AbstractController { /** * @Route("/", name="shipping_region_index", methods={"GET"}) */ public function index(): Response { $shippingRegions = $this->getDoctrine() ->getRepository(ShippingRegion::class) ->findAll(); return $this->render('shipping_region/index.html.twig', [ 'shipping_regions' => $shippingRegions, ]); } /** * @Route("/new", name="shipping_region_new", methods={"GET","POST"}) */ public function new(Request $request): Response { $shippingRegion = new ShippingRegion(); $form = $this->createForm(ShippingRegionType::class, $shippingRegion); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($shippingRegion); $entityManager->flush(); return $this->redirectToRoute('shipping_region_index'); } return $this->render('shipping_region/new.html.twig', [ 'shipping_region' => $shippingRegion, 'form' => $form->createView(), ]); } /** * @Route("/{shippingRegionId}", name="shipping_region_show", methods={"GET"}) */ public function show(ShippingRegion $shippingRegion): Response { return $this->render('shipping_region/show.html.twig', [ 'shipping_region' => $shippingRegion, ]); } /** * @Route("/{shippingRegionId}/edit", name="shipping_region_edit", methods={"GET","POST"}) */ public function edit(Request $request, ShippingRegion $shippingRegion): Response { $form = $this->createForm(ShippingRegionType::class, $shippingRegion); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('shipping_region_index', [ 'shippingRegionId' => $shippingRegion->getShippingRegionId(), ]); } return $this->render('shipping_region/edit.html.twig', [ 'shipping_region' => $shippingRegion, 'form' => $form->createView(), ]); } /** * @Route("/{shippingRegionId}", name="shipping_region_delete", methods={"DELETE"}) */ public function delete(Request $request, ShippingRegion $shippingRegion): Response { if ($this->isCsrfTokenValid('delete'.$shippingRegion->getShippingRegionId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->remove($shippingRegion); $entityManager->flush(); } return $this->redirectToRoute('shipping_region_index'); } } <file_sep><?php namespace App\Form; use App\Entity\Customer; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class CustomerType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('email') ->add('password') ->add('creditCard') ->add('address1') ->add('address2') ->add('city') ->add('region') ->add('postalCode') ->add('country') ->add('shippingRegionId') ->add('dayPhone') ->add('evePhone') ->add('mobPhone') ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Customer::class, ]); } } <file_sep><?php namespace App\Form; use App\Entity\ShoppingCart; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class ShoppingCartType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('cartId') ->add('productId') ->add('attributes') ->add('quantity') ->add('buyNow') ->add('addedOn') ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => ShoppingCart::class, ]); } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * Shipping * * @ORM\Table(name="shipping", indexes={@ORM\Index(name="idx_shipping_shipping_region_id", columns={"shipping_region_id"})}) * @ORM\Entity */ class Shipping { /** * @var int * * @ORM\Column(name="shipping_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $shippingId; /** * @var string * * @ORM\Column(name="shipping_type", type="string", length=100, nullable=false) */ private $shippingType; /** * @var string * * @ORM\Column(name="shipping_cost", type="decimal", precision=10, scale=2, nullable=false) */ private $shippingCost; /** * @var int * * @ORM\Column(name="shipping_region_id", type="integer", nullable=false) */ private $shippingRegionId; public function getShippingId(): ?int { return $this->shippingId; } public function getShippingType(): ?string { return $this->shippingType; } public function setShippingType(string $shippingType): self { $this->shippingType = $shippingType; return $this; } public function getShippingCost() { return $this->shippingCost; } public function setShippingCost($shippingCost): self { $this->shippingCost = $shippingCost; return $this; } public function getShippingRegionId(): ?int { return $this->shippingRegionId; } public function setShippingRegionId(int $shippingRegionId): self { $this->shippingRegionId = $shippingRegionId; return $this; } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * OrderDetail * * @ORM\Table(name="order_detail", indexes={@ORM\Index(name="idx_order_detail_order_id", columns={"order_id"})}) * @ORM\Entity */ class OrderDetail { /** * @var int * * @ORM\Column(name="item_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $itemId; /** * @var int * * @ORM\Column(name="order_id", type="integer", nullable=false) */ private $orderId; /** * @var int * * @ORM\Column(name="product_id", type="integer", nullable=false) */ private $productId; /** * @var string * * @ORM\Column(name="attributes", type="string", length=1000, nullable=false) */ private $attributes; /** * @var string * * @ORM\Column(name="product_name", type="string", length=100, nullable=false) */ private $productName; /** * @var int * * @ORM\Column(name="quantity", type="integer", nullable=false) */ private $quantity; /** * @var string * * @ORM\Column(name="unit_cost", type="decimal", precision=10, scale=2, nullable=false) */ private $unitCost; public function getItemId(): ?int { return $this->itemId; } public function getOrderId(): ?int { return $this->orderId; } public function setOrderId(int $orderId): self { $this->orderId = $orderId; return $this; } public function getProductId(): ?int { return $this->productId; } public function setProductId(int $productId): self { $this->productId = $productId; return $this; } public function getAttributes(): ?string { return $this->attributes; } public function setAttributes(string $attributes): self { $this->attributes = $attributes; return $this; } public function getProductName(): ?string { return $this->productName; } public function setProductName(string $productName): self { $this->productName = $productName; return $this; } public function getQuantity(): ?int { return $this->quantity; } public function setQuantity(int $quantity): self { $this->quantity = $quantity; return $this; } public function getUnitCost() { return $this->unitCost; } public function setUnitCost($unitCost): self { $this->unitCost = $unitCost; return $this; } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * Product * * @ORM\Table(name="product", indexes={@ORM\Index(name="idx_ft_product_name_description", columns={"name", "description"})}) * @ORM\Entity * @ORM\Entity(repositoryClass="App\Repository\ProductRepository") */ class Product { /** * @var int * * @ORM\Column(name="product_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $productId; /** * @var string * * @ORM\Column(name="name", type="string", length=100, nullable=false) */ private $name; /** * @var string * * @ORM\Column(name="description", type="string", length=1000, nullable=false) */ private $description; /** * @var string * * @ORM\Column(name="price", type="decimal", precision=10, scale=2, nullable=false) */ private $price; /** * @var string * * @ORM\Column(name="discounted_price", type="decimal", precision=10, scale=2, nullable=false, options={"default"="0.00"}) */ private $discountedPrice = '0.00'; /** * @var string|null * * @ORM\Column(name="image", type="string", length=150, nullable=true) */ private $image; /** * @var string|null * * @ORM\Column(name="image_2", type="string", length=150, nullable=true) */ private $image2; /** * @var string|null * * @ORM\Column(name="thumbnail", type="string", length=150, nullable=true) */ private $thumbnail; /** * @var int * * @ORM\Column(name="display", type="smallint", nullable=false) */ private $display = '0'; public function getProductId(): ?int { return $this->productId; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function getPrice() { return $this->price; } public function setPrice($price): self { $this->price = $price; return $this; } public function getDiscountedPrice() { return $this->discountedPrice; } public function setDiscountedPrice($discountedPrice): self { $this->discountedPrice = $discountedPrice; return $this; } public function getImage(): ?string { return $this->image; } public function setImage(?string $image): self { $this->image = $image; return $this; } public function getImage2(): ?string { return $this->image2; } public function setImage2(?string $image2): self { $this->image2 = $image2; return $this; } public function getThumbnail(): ?string { return $this->thumbnail; } public function setThumbnail(?string $thumbnail): self { $this->thumbnail = $thumbnail; return $this; } public function getDisplay(): ?int { return $this->display; } public function setDisplay(int $display): self { $this->display = $display; return $this; } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * ShoppingCart * * @ORM\Table(name="shopping_cart", indexes={@ORM\Index(name="idx_shopping_cart_cart_id", columns={"cart_id"})}) * @ORM\Entity */ class ShoppingCart { /** * @var int * * @ORM\Column(name="item_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $itemId; /** * @var string * * @ORM\Column(name="cart_id", type="string", length=32, nullable=false, options={"fixed"=true}) */ private $cartId; /** * @var int * * @ORM\Column(name="product_id", type="integer", nullable=false) */ private $productId; /** * @var string * * @ORM\Column(name="attributes", type="string", length=1000, nullable=false) */ private $attributes; /** * @var int * * @ORM\Column(name="quantity", type="integer", nullable=false) */ private $quantity; /** * @var bool * * @ORM\Column(name="buy_now", type="boolean", nullable=false, options={"default"="1"}) */ private $buyNow = '1'; /** * @var \DateTime * * @ORM\Column(name="added_on", type="datetime", nullable=false) */ private $addedOn; public function getItemId(): ?int { return $this->itemId; } public function getCartId(): ?string { return $this->cartId; } public function setCartId(string $cartId): self { $this->cartId = $cartId; return $this; } public function getProductId(): ?int { return $this->productId; } public function setProductId(int $productId): self { $this->productId = $productId; return $this; } public function getAttributes(): ?string { return $this->attributes; } public function setAttributes(string $attributes): self { $this->attributes = $attributes; return $this; } public function getQuantity(): ?int { return $this->quantity; } public function setQuantity(int $quantity): self { $this->quantity = $quantity; return $this; } public function getBuyNow(): ?bool { return $this->buyNow; } public function setBuyNow(bool $buyNow): self { $this->buyNow = $buyNow; return $this; } public function getAddedOn(): ?\DateTimeInterface { return $this->addedOn; } public function setAddedOn(\DateTimeInterface $addedOn): self { $this->addedOn = $addedOn; return $this; } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tax * * @ORM\Table(name="tax") * @ORM\Entity */ class Tax { /** * @var int * * @ORM\Column(name="tax_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $taxId; /** * @var string * * @ORM\Column(name="tax_type", type="string", length=100, nullable=false) */ private $taxType; /** * @var string * * @ORM\Column(name="tax_percentage", type="decimal", precision=10, scale=2, nullable=false) */ private $taxPercentage; public function getTaxId(): ?int { return $this->taxId; } public function getTaxType(): ?string { return $this->taxType; } public function setTaxType(string $taxType): self { $this->taxType = $taxType; return $this; } public function getTaxPercentage() { return $this->taxPercentage; } public function setTaxPercentage($taxPercentage): self { $this->taxPercentage = $taxPercentage; return $this; } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * ProductAttribute * * @ORM\Table(name="product_attribute") * @ORM\Entity */ class ProductAttribute { /** * @var int * * @ORM\Column(name="product_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $productId; /** * @var int * * @ORM\Column(name="attribute_value_id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $attributeValueId; public function getProductId(): ?int { return $this->productId; } public function getAttributeValueId(): ?int { return $this->attributeValueId; } }
70040704d9a1f33b122fcc5b17c979c36becde3d
[ "PHP" ]
16
PHP
AmsaluGit/ecomerce
02ed8052e2c38e34005f1294aba4366ca1380816
f389c687f30e22703a8a1ba3364b21fa8eda9b9e
refs/heads/master
<repo_name>ankitmalikg2/golang-aws-sdk-dynamoDB<file_sep>/main.go package main import ( "encoding/json" "io/ioutil" "os" "strconv" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" "github.com/aws/aws-sdk-go/service/dynamodb/expression" "fmt" ) type Item struct { Year int Title string Plot string Rating float64 } func main() { sess := session.Must(session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, })) // Create DynamoDB client svc := dynamodb.New(sess) // dbCreateTable(svc) // dbCreateItem(svc) // dbCreateItemfromJSON(svc) // dbListTables(svc) //getting all dynamoDB table names // dbGetItem(svc) // dbUpdateItem(svc) dbDeleteItem(svc) dbScanTable(svc) } //dbListTables will print all the tables present in aws account func dbListTables(svc *dynamodb.DynamoDB) { //creating input configuration // var limit int64 = 5 input := &dynamodb.ListTablesInput{ Limit: aws.Int64(5), } fmt.Printf("Tables:\n") for { // Get the list of tables result, err := svc.ListTables(input) if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case dynamodb.ErrCodeInternalServerError: fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error()) default: fmt.Println(aerr.Error()) } } else { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) } return } for index, n := range result.TableNames { fmt.Println(index, "-----", *n) } // assign the last read tablename as the start for our next call to the ListTables function // the maximum number of table names returned in a call is 100 (default), which requires us to make // multiple calls to the ListTables function to retrieve all table names input.ExclusiveStartTableName = result.LastEvaluatedTableName if result.LastEvaluatedTableName == nil { break } } } //dbCreateTable it will create a table func dbCreateTable(svc *dynamodb.DynamoDB) { tableName := "Movies" input := &dynamodb.CreateTableInput{ AttributeDefinitions: []*dynamodb.AttributeDefinition{ { AttributeName: aws.String("Year"), AttributeType: aws.String("N"), }, { AttributeName: aws.String("Title"), AttributeType: aws.String("S"), }, }, KeySchema: []*dynamodb.KeySchemaElement{ { AttributeName: aws.String("Year"), KeyType: aws.String("HASH"), }, { AttributeName: aws.String("Title"), KeyType: aws.String("RANGE"), }, }, ProvisionedThroughput: &dynamodb.ProvisionedThroughput{ ReadCapacityUnits: aws.Int64(10), WriteCapacityUnits: aws.Int64(10), }, TableName: aws.String(tableName), } _, err := svc.CreateTable(input) if err != nil { fmt.Println("Got error calling CreateTable:") fmt.Println(err.Error()) os.Exit(1) } fmt.Println("Created the table", tableName) } func dbCreateItem(svc *dynamodb.DynamoDB) { item := Item{ Year: 2015, Title: "The Big New Movie", Plot: "Nothing happens at all.", Rating: 0.0, } av, err := dynamodbattribute.MarshalMap(item) if err != nil { fmt.Println("Got error marshalling new movie item:") fmt.Println(err.Error()) os.Exit(1) } // Create item in table Movies tableName := "Movies" input := &dynamodb.PutItemInput{ Item: av, TableName: aws.String(tableName), } _, err = svc.PutItem(input) if err != nil { fmt.Println("Got error calling PutItem:") fmt.Println(err.Error()) os.Exit(1) } year := strconv.Itoa(item.Year) fmt.Println("Successfully added '" + item.Title + "' (" + year + ") to table " + tableName) } func getItems() []Item { raw, err := ioutil.ReadFile("./movie_data.json") if err != nil { fmt.Println(err.Error()) os.Exit(1) } var items []Item json.Unmarshal(raw, &items) return items } //dbCreateItemfromJSON insert item from JSON file func dbCreateItemfromJSON(svc *dynamodb.DynamoDB) { // snippet-start:[dynamodb.go.load_items.call] // Get table items from movie_data.json items := getItems() // Add each item to Movies table: tableName := "Movies" for _, item := range items { av, err := dynamodbattribute.MarshalMap(item) if err != nil { fmt.Println("Got error marshalling map:") fmt.Println(err.Error()) os.Exit(1) } // Create item in table Movies input := &dynamodb.PutItemInput{ Item: av, TableName: aws.String(tableName), } _, err = svc.PutItem(input) if err != nil { fmt.Println("Got error calling PutItem:") fmt.Println(err.Error()) os.Exit(1) } year := strconv.Itoa(item.Year) fmt.Println("Successfully added '" + item.Title + "' (" + year + ") to table " + tableName) // snippet-end:[dynamodb.go.load_items.call] } } func dbGetItem(svc *dynamodb.DynamoDB) { tableName := "Movies" movieName := "The Big New Movie" movieYear := "2015" result, err := svc.GetItem(&dynamodb.GetItemInput{ TableName: aws.String(tableName), Key: map[string]*dynamodb.AttributeValue{ "Year": { N: aws.String(movieYear), }, "Title": { S: aws.String(movieName), }, }, }) if err != nil { fmt.Println(err.Error()) return } item := Item{} err = dynamodbattribute.UnmarshalMap(result.Item, &item) if err != nil { panic(fmt.Sprintf("Failed to unmarshal Record, %v", err)) } if item.Title == "" { fmt.Println("Could not find '" + movieName + "' (" + movieYear + ")") return } fmt.Println("Found item:") fmt.Println("Year: ", item.Year) fmt.Println("Title: ", item.Title) fmt.Println("Plot: ", item.Plot) fmt.Println("Rating:", item.Rating) } func dbScanTable(svc *dynamodb.DynamoDB) { tableName := "Movies" minRating := 4.0 year := 2014 // Create the Expression to fill the input struct with. // Get all movies in that year; we'll pull out those with a higher rating later filt := expression.Name("Year").GreaterThanEqual(expression.Value(year)) // Or we could get by ratings and pull out those with the right year later // filt := expression.Name("info.rating").GreaterThan(expression.Value(min_rating)) // Get back the title, year, and rating proj := expression.NamesList(expression.Name("Title"), expression.Name("Year"), expression.Name("Rating")) expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build() if err != nil { fmt.Println("Got error building expression:") fmt.Println(err.Error()) os.Exit(1) } params := &dynamodb.ScanInput{ ExpressionAttributeNames: expr.Names(), ExpressionAttributeValues: expr.Values(), FilterExpression: expr.Filter(), ProjectionExpression: expr.Projection(), TableName: aws.String(tableName), } // Make the DynamoDB Query API call result, err := svc.Scan(params) if err != nil { fmt.Println("Query API call failed:") fmt.Println((err.Error())) os.Exit(1) } numItems := 0 for _, i := range result.Items { item := Item{} err = dynamodbattribute.UnmarshalMap(i, &item) if err != nil { fmt.Println("Got error unmarshalling:") fmt.Println(err.Error()) os.Exit(1) } // Which ones had a higher rating than minimum? if item.Rating > minRating { // Or it we had filtered by rating previously: // if item.Year == year { numItems++ fmt.Println("Title: ", item.Title) fmt.Println("Rating:", item.Rating) fmt.Println() } } fmt.Println("Found", numItems, "movie(s) with a rating above", minRating, "in", year) } func dbUpdateItem(svc *dynamodb.DynamoDB) { // Create item in table Movies tableName := "Movies" movieName := "The Big New Movie" movieYear := "2015" movieRating := "2.4" input := &dynamodb.UpdateItemInput{ ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ ":r": { N: aws.String(movieRating), }, }, TableName: aws.String(tableName), Key: map[string]*dynamodb.AttributeValue{ "Year": { N: aws.String(movieYear), }, "Title": { S: aws.String(movieName), }, }, ReturnValues: aws.String("UPDATED_NEW"), UpdateExpression: aws.String("set Rating = :r"), } _, err := svc.UpdateItem(input) if err != nil { fmt.Println(err.Error()) return } fmt.Println("Successfully updated '" + movieName + "' (" + movieYear + ") rating to " + movieRating) } func dbDeleteItem(svc *dynamodb.DynamoDB) { tableName := "Movies" movieName := "The Big New Movie" movieYear := "2015" input := &dynamodb.DeleteItemInput{ Key: map[string]*dynamodb.AttributeValue{ "Year": { N: aws.String(movieYear), }, "Title": { S: aws.String(movieName), }, }, TableName: aws.String(tableName), } _, err := svc.DeleteItem(input) if err != nil { fmt.Println("Got error calling DeleteItem") fmt.Println(err.Error()) return } fmt.Println("Deleted '" + movieName + "' (" + movieYear + ") from table " + tableName) }
c96af9c4cf76e44e2d07505f54ae6b484c482705
[ "Go" ]
1
Go
ankitmalikg2/golang-aws-sdk-dynamoDB
a138788cb364e02bf1d85593ad8b8cf6bf121373
489f11a41bed3bbebc271f1f3903e72a5619ed1e
refs/heads/master
<file_sep>import _connectToChild from './parent/connectToChild'; import _connectToParent from './child/connectToParent'; import { ErrorCode as _ErrorCode } from './enums'; export const connectToChild = _connectToChild; export const connectToParent = _connectToParent; export const ErrorCode = _ErrorCode;
d5aebee0903d3fca876011adf83c870fe3056a6d
[ "TypeScript" ]
1
TypeScript
marlon-tucker/penpal
3e21f45175b7055fe026313a8dbcf82fc0660223
ee4860d0c3410926962763144b7dcaf1b6f4a31a
refs/heads/master
<repo_name>Kappeh/Redstone-Squid<file_sep>/Discord/command.py import Discord.utils as utils class Param(): def __init__(self, name, description, dtype = None, min_val = None, max_val = None, min_len = None, max_len = None, optional = False): self.name = name self.description = description self.dtype = dtype self.min_val = min_val self.max_val = max_val self.min_len = min_len self.max_len = max_len self.optional = optional self.validate_param() def validate_param(self): if (self.min_val or self.min_val) and self.dtype not in ['int', 'num']: raise Exception('Min and max values can only be specified for int and num params.') if self.dtype and self.dtype not in ['int', 'num', 'mention', 'channel_mention', 'str', 'text']: raise Exception('Invalid Param.dtype.') if self.min_val and not isinstance(self.min_val, (float, int)): raise Exception('Param.min_val must be a number.') if self.max_val and not isinstance(self.max_val, (float, int)): raise Exception('Param.max_val must be a number.') if self.min_len and not isinstance(self.min_len, (float, int)): raise Exception('Param.min_len must be a number.') if self.max_len and not isinstance(self.max_len, (float, int)): raise Exception('Param.max_len must be a number.') if not isinstance(self.name, str): raise Exception('Param.name must be a string.') if not isinstance(self.description, str): raise Exception('Param.description must be a string.') class Command(): _brief = None _params = None _meta = {} _perms = None _roles = None _servers = None _perm_role_operator = None def __getitem__(self, i): if i in self._meta: return self._meta[i] return None def get_usage_message(self): if not self._params: return 'No parameters required.' usage_message = 'Parameters:\n' for i in range(len(self._params)): usage_message += '`' + self._params[i].name + '` - ' if self._params[i].optional: usage_message += '_optional_ - ' usage_message += self._params[i].description if i < len(self._params) - 1: usage_message += '\n' return usage_message def validate_params(self): self.params_required = 0 if not self._params: return optional = False text = False for param in self._params: if text: raise Exception('You can only have one text Param and it must be the last.') if not param.optional and optional: raise Exception('You cannot have an optional Param before a non optional Param.') if param.optional: optional = True else: self.params_required += 1 if param.dtype == 'text': text = True def validate_execute_command(self, argv): if not self._params: if argv: return utils.warning_embed('Unexpected parameter.', self.get_usage_message()) return None if len(argv) < self.params_required: return utils.warning_embed('Missing parameter.', self.get_usage_message()) if len(argv) > len(self._params) and self._params[-1].dtype != 'text': return utils.warning_embed('Unexpected parameter.', self.get_usage_message()) for i in range(len(self._params)): if self._params[i].optional and len(argv) < i: break if self._params[i].min_val and float(argv[i]) < self._params[i].min_val: return utils.warning_embed('Parameter out of bounds.', '`{}` must be at least {}.'.format(self._params[i].name, self._params[i].min_val)) if self._params[i].max_val and float(argv[i]) > self._params[i].max_val: return utils.warning_embed('Parameter out of bounds.', '`{}` must be at most {}.'.format(self._params[i].name, self._params[i].max_val)) if self._params[i].min_len and len(argv[i]) < self._params[i].min_len: return utils.warning_embed('Incorrect parameter length.', '`{}` must have length of at least {}.'.format(self._params[i].name, self._params[i].min_len)) if self._params[i].max_len and len(argv[i]) > self._params[i].max_len: return utils.warning_embed('Incorrect parameter length.', '`{}` must have length of at most {}.'.format(self._params[i].name, self._params[i].max_len)) if not self._params[i].dtype: continue if self._params[i].dtype == 'int' and not utils.represents_int(argv[i]): return utils.warning_embed('Incorrect parameter type.', '`{}` must be an integer.'.format(self._params[i].name)) if self._params[i].dtype == 'num' and not utils.represents_float(argv[i]): return utils.warning_embed('Incorrect parameter type.', '`{}` must be a number.'.format(self._params[i].name)) if self._params[i].dtype == 'mention' and not utils.represents_user(argv[i]): return utils.warning_embed('Incorrect parameter type.', '`{}` must be a mention.'.format(self._params[i].name)) if self._params[i].dtype == 'channel_mention' and not utils.represents_channel(argv[i]): return utils.warning_embed('Incorrect parameter type.', '`{}` must be a channel mention.'.format(self._params[i].name)) return None def get_help(self, description = False): if description and self._params: return self._brief + '\n\n' + self.get_usage_message() elif self._brief: return self._brief return utils.error_embed('Error.', 'Could not find command\'s help message.')<file_sep>/Google/interface.py import os import sys import json import gspread from oauth2client.service_account import ServiceAccountCredentials # Establishing connection with google APIs def connect(): scopes = [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive' ] credentials = None if not os.path.isfile('Google/client_secret.json'): # Getting service account credentials from environment variables credentials = os.environ.get('GOOGLE_CREDENTIALS') # Checking environment variables exist if not credentials: raise Exception('Specify google credentials with a client_secret.json or environment variables.') # Formatting credentials credentials = json.loads(credentials) credentials = ServiceAccountCredentials.from_json_keyfile_dict(credentials, scopes) else: # Getting service account credentials from json file credentials = ServiceAccountCredentials.from_json_keyfile_name('Google/client_secret.json', scopes) return credentials, gspread.authorize(credentials) import Discord.utils as utils class Connection: _GC = None _CREDS = None @staticmethod def get(): if not Connection._GC or Connection._CREDS.access_token_expired: Connection._CREDS, Connection._GC = connect() return Connection._GC<file_sep>/Discord/settings/settings.py import discord import Discord.utils as utils from Discord.command import Param from Discord.command_leaf import Command_Leaf from Discord.command_branch import Command_Branch from Discord.permissions import * import Database.server_settings as server_settings # Settings Command Branch ------------------------------------------------------------------------------------------ SETTINGS_COMMANDS = Command_Branch('Allows you to configure the bot for your server.') # Confirm Channel -------------------------------------------------------------------------------------------- channel_settings_roles = ['Admin', 'Moderator'] channel_set_params = [ Param('channel', 'The channel that you want to update this setting to.', dtype = 'channel_mention', optional = False) ] # Returns the channel which has been set to deal with the channel perpose. def get_channel_for(server, channel_perpose): # Getting channel if from database channel_id = server_settings.get_server_setting(server.id, channel_perpose) # If channel is none or cannot be converted to int, return None. if channel_id == None: return None channel_id = str(channel_id) return server.get_channel(channel_id) # Gets all channels def get_all_channels(server): settings = server_settings.get_server_settings(server.id) result = {} for key, val in settings.items(): settings[key] = str(val) result['Smallest'] = server.get_channel(settings['Smallest']) result['Fastest'] = server.get_channel(settings['Fastest']) result['Smallest Observerless'] = server.get_channel(settings['Smallest Observerless']) result['Fastest Observerless'] = server.get_channel(settings['Fastest Observerless']) result['First'] = server.get_channel(settings['First']) return result # Query all settings. async def query_all(client, user_command, message): sent_message = await client.send_message(message.channel, embed = utils.info_embed('Working', 'Getting information...')) channels = get_all_channels(message.server) desc = '' desc += '`smallest channel`: {}\n'.format('_Not set_' if channels['Smallest'] == None else '#' + channels['Smallest'].name) desc += '`fastest channel`: {}\n'.format('_Not set_' if channels['Fastest'] == None else '#' + channels['Fastest'].name) desc += '`smallest observerless channel`: {}\n'.format('_Not set_' if channels['Smallest Observerless'] == None else '#' + channels['Smallest Observerless'].name) desc += '`fastest observerless channel`: {}\n'.format('_Not set_' if channels['Fastest Observerless'] == None else '#' + channels['Fastest Observerless'].name) desc += '`first channel`: {}\n'.format('_Not set_' if channels['First'] == None else '#' + channels['First'].name) em = discord.Embed(title = 'Current Settings', description = desc, colour = utils.discord_green) await client.delete_message(sent_message) await client.send_message(message.channel, embed = em) SETTINGS_COMMANDS.add_command('query_all', Command_Leaf(query_all, 'Queries all settings.', roles = channel_settings_roles)) # Finds which channel is set for a perpose and sends the results to the user. async def query_channel(client, user_command, message, channel_perpose): sent_message = await client.send_message(message.channel, embed = utils.info_embed('Working', 'Getting information...')) result_channel = get_channel_for(message.server, channel_perpose) await client.delete_message(sent_message) if result_channel == None: return utils.info_embed('{} Channel Info'.format(channel_perpose), 'Unset - Use the set command to set a channel.') return utils.info_embed('{} Channel Info'.format(channel_perpose), 'ID: {} \n Name: {}'.format(result_channel.id, result_channel.name)) # Sets the current channel for a perpose. async def set_channel(client, user_command, message, channel_perpose): sent_message = await client.send_message(message.channel, embed = utils.info_embed('Working', 'Updating information...')) channel_id = user_command.split(' ')[3] for c in '<#>': channel_id = str.replace(channel_id, c, '') # Verifying channel exists on server if message.server.get_channel(channel_id) == None: await client.delete_message(sent_message) return utils.error_embed('Error', 'Could not find that channel.') # Updating database server_settings.update_server_setting(message.server.id, channel_perpose, channel_id) # Sending success message await client.delete_message(sent_message) await client.send_message(message.channel, embed = utils.info_embed('Settings updated', '{} channel has successfully been set.'.format(channel_perpose))) # Unsets all channels from having a perpose. async def unset_channel(client, user_command, message, channel_perpose): sent_message = await client.send_message(message.channel, embed = utils.info_embed('Working', 'Updating information...')) server_id = message.server.id server_settings.update_server_setting(server_id, channel_perpose, '') await client.delete_message(sent_message) await client.send_message(message.channel, embed = utils.info_embed('Settings updated', '{} channel has successfully been unset.'.format(channel_perpose))) # Smallest --------------------------------------------------------------------------------------------------- # Creating command branch SMALLEST_CHANNEL_COMMANDS = Command_Branch('Settings for channel to post smallest records to.') # Defining the query, set and unset functions async def query_smallest_channel(client, user_command, message): return await query_channel(client, user_command, message, 'Smallest') async def set_smallest_channel(client, user_command, message): return await set_channel(client, user_command, message, 'Smallest') async def unset_smallest_channel(client, user_command, message): return await unset_channel(client, user_command, message, 'Smallest') # Adding functions to the command branch SMALLEST_CHANNEL_COMMANDS.add_command('query', Command_Leaf(query_smallest_channel, 'Querys which channel is set to post smallest records to.', roles = channel_settings_roles)) SMALLEST_CHANNEL_COMMANDS.add_command('set', Command_Leaf(set_smallest_channel, 'Sets current channel as the channel to post smallest records to.', roles = channel_settings_roles, params = channel_set_params)) SMALLEST_CHANNEL_COMMANDS.add_command('unset', Command_Leaf(unset_smallest_channel, 'Unsets the channel to post smallest records to.', roles = channel_settings_roles)) # Adding command branch to the settings command branch SETTINGS_COMMANDS.add_command('smallest_channel', SMALLEST_CHANNEL_COMMANDS) # Fastest ---------------------------------------------------------------------------------------------------- # Creating command branch FASTEST_CHANNEL_COMMANDS = Command_Branch('Settings for channel to post fastest records to.') # Defining the query, set and unset functions async def query_fastest_channel(client, user_command, message): return await query_channel(client, user_command, message, 'Fastest') async def set_fastest_channel(client, user_command, message): return await set_channel(client, user_command, message, 'Fastest') async def unset_fastest_channel(client, user_command, message): return await unset_channel(client, user_command, message, 'Fastest') # Adding functions to the command branch FASTEST_CHANNEL_COMMANDS.add_command('query', Command_Leaf(query_fastest_channel, 'Querys which channel is set to post fastest records to.', roles = channel_settings_roles)) FASTEST_CHANNEL_COMMANDS.add_command('set', Command_Leaf(set_fastest_channel, 'Sets current channel as the channel to post fastest records to.', roles = channel_settings_roles, params = channel_set_params)) FASTEST_CHANNEL_COMMANDS.add_command('unset', Command_Leaf(unset_fastest_channel, 'Unsets the channel to post fastest records to.', roles = channel_settings_roles)) # Adding command branch to the settings command branch SETTINGS_COMMANDS.add_command('fastest_channel', FASTEST_CHANNEL_COMMANDS) # Smallest Observerless -------------------------------------------------------------------------------------- # Creating command branch SMALLEST_OBSERVERLESS_CHANNEL_COMMANDS = Command_Branch('Settings for channel to post smallest observerless records to.') # Defining the query, set and unset functions async def query_smallest_observerless_channel(client, user_command, message): return await query_channel(client, user_command, message, 'Smallest Observerless') async def set_smallest_observerless_channel(client, user_command, message): return await set_channel(client, user_command, message, 'Smallest Observerless') async def unset_smallest_observerless_channel(client, user_command, message): return await unset_channel(client, user_command, message, 'Smallest Observerless') # Adding functions to the command branch SMALLEST_OBSERVERLESS_CHANNEL_COMMANDS.add_command('query', Command_Leaf(query_smallest_observerless_channel, 'Querys which channel is set to post smallest observerless records to.', roles = channel_settings_roles)) SMALLEST_OBSERVERLESS_CHANNEL_COMMANDS.add_command('set', Command_Leaf(set_smallest_observerless_channel, 'Sets current channel as the channel to post smallest observerless records to.', roles = channel_settings_roles, params = channel_set_params)) SMALLEST_OBSERVERLESS_CHANNEL_COMMANDS.add_command('unset', Command_Leaf(unset_smallest_observerless_channel, 'Unsets the channel to post smallest observerless records to.', roles = channel_settings_roles)) # Adding command branch to the settings command branch SETTINGS_COMMANDS.add_command('smallest_observerless_channel', SMALLEST_OBSERVERLESS_CHANNEL_COMMANDS) # Fastest Observerless --------------------------------------------------------------------------------------- # Creating command branch FASTEST_OBSERVERLESS_CHANNEL_COMMANDS = Command_Branch('Settings for channel to post fastest records to.') # Defining the query, set and unset functions async def query_fastest_observerless_channel(client, user_command, message): return await query_channel(client, user_command, message, 'Fastest Observerless') async def set_fastest_observerless_channel(client, user_command, message): return await set_channel(client, user_command, message, 'Fastest Observerless') async def unset_fastest_observerless_channel(client, user_command, message): return await unset_channel(client, user_command, message, 'Fastest Observerless') # Adding functions to the command branch FASTEST_OBSERVERLESS_CHANNEL_COMMANDS.add_command('query', Command_Leaf(query_fastest_observerless_channel, 'Querys which channel is set to post fastest observerless records to.', roles = channel_settings_roles)) FASTEST_OBSERVERLESS_CHANNEL_COMMANDS.add_command('set', Command_Leaf(set_fastest_observerless_channel, 'Sets current channel as the channel to post fastest observerless records to.', roles = channel_settings_roles, params = channel_set_params)) FASTEST_OBSERVERLESS_CHANNEL_COMMANDS.add_command('unset', Command_Leaf(unset_fastest_observerless_channel, 'Unsets the channel to post fastest observerless records to.', roles = channel_settings_roles)) # Adding command branch to the settings command branch SETTINGS_COMMANDS.add_command('fastest_observerless_channel', FASTEST_OBSERVERLESS_CHANNEL_COMMANDS) # First ------------------------------------------------------------------------------------------------------ # Creating command branch FIRST_CHANNEL_COMMANDS = Command_Branch('Settings for channel to post first records to.') # Defining the query, set and unset functions async def query_first_channel(client, user_command, message): return await query_channel(client, user_command, message, 'First') async def set_first_channel(client, user_command, message): return await set_channel(client, user_command, message, 'First') async def unset_first_channel(client, user_command, message): return await unset_channel(client, user_command, message, 'First') # Adding functions to the command branch FIRST_CHANNEL_COMMANDS.add_command('query', Command_Leaf(query_first_channel, 'Querys which channel is set to post first records to.', roles = channel_settings_roles)) FIRST_CHANNEL_COMMANDS.add_command('set', Command_Leaf(set_first_channel, 'Sets current channel as the channel to post first records to.', roles = channel_settings_roles, params = channel_set_params)) FIRST_CHANNEL_COMMANDS.add_command('unset', Command_Leaf(unset_first_channel, 'Unsets the channel to post first records to.', roles = channel_settings_roles)) # Adding command branch to the settings command branch SETTINGS_COMMANDS.add_command('first_channel', FIRST_CHANNEL_COMMANDS)<file_sep>/Database/submissions.py from datetime import datetime import Database.main as DB from Database.submission import Submission as Submission_Class import Database.global_vars as global_vars import Database.config as config import Google.interface as Google import Database.submission as submission # Moves all records from the form_submissions worksheet to the open submissions worksheet. def open_form_submissions(): # Getting worksheets form_wks = DB.get_form_submissions_worksheet() open_wks = DB.get_open_submissions_worksheet() # Getting submissions from form submissions worksheet submissions = form_wks.get_all_values() if len(submissions) == 1: return # If there are no submissions, return submissions = submissions[1:] # Getting range of cells that need updating submission_count = len(submissions) first_row = open_wks.row_count + 1 last_row = open_wks.row_count + submission_count first_col = 3 last_col = open_wks.col_count # Adding Rows open_wks.add_rows(submission_count) # Updating cells cells_to_update = open_wks.range(first_row, first_col, last_row, last_col) index = 0 for submission in submissions: for element in submission: cells_to_update[index].value = element index += 1 open_wks.update_cells(cells_to_update) # Adding IDs and Last update times to submissions next_id = global_vars.get_next_id() cells_to_update = open_wks.range(first_row, 1, last_row, 2) for i in range(len(cells_to_update) // 2): cells_to_update[i * 2].value = i + next_id cells_to_update[i * 2 + 1].value = datetime.now().strftime('%d-%m-%Y %H:%M:%S') global_vars.add_to_next_id(submission_count) open_wks.update_cells(cells_to_update) # Removing Submissions from form worksheet for _ in range(submission_count): form_wks.delete_row(2) # Returns all submissions that are in the open submissions worksheet. def get_open_submissions_raw(): wks = DB.get_open_submissions_worksheet() return wks.get_all_records() def get_open_submissions(): submissions = get_open_submissions_raw() for index, submission in enumerate(submissions): submissions[index] = Submission_Class.from_dict(submission) return submissions def get_open_submission(submission_id): return get_submission(submission_id, DB.get_open_submissions_worksheet()) # Returns all submissions that are in the confirmed submissions worksheet. def get_confirmed_submissions_raw(): wks = DB.get_confirmed_submissions_worksheet() return wks.get_all_records() def get_confirmed_submissions(): submissions = get_confirmed_submissions_raw() for index, submission in enumerate(submissions): submissions[index] = Submission_Class.from_dict(submission) return submissions def get_confirmed_submission(submissions_id): return get_submission(submission_id, DB.get_confirmed_submissions_worksheet()) # Returns all submissions that are in the denied submissions worksheet. def get_denied_submissions_raw(): wks = DB.get_denied_submissions_worksheet() return wks.get_all_records() def get_denied_submissions(): submissions = get_denied_submissions_raw() for index, submission in enumerate(submissions): submissions[index] = Submission_Class.from_dict(submission) return submissions def get_denied_submission(submissions_id): return get_submission(submission_id, DB.get_denied_submissions_worksheet()) # Returns a Submission object parsed from wks with the submission_id def get_submission(submission_id, wks): submissions = wks.get_all_records() for sub in submissions: if int(sub['Submission ID']) == submission_id: return submission.Submission.from_dict(sub) return None # Moves submission with submission_id from source_wks to destination_wks # Returns if the submission exists in source_wks def move_submission(submission_id, source_wks, destination_wks): # Gets all submission from source submissions = source_wks.get_all_records() # Finds the row number of the submission row_number = None for index, sub in enumerate(submissions): if int(sub['Submission ID']) == submission_id: row_number = index + 2 break # Returns False if no such submission exist if row_number == None: return False # Appends the submission to the destination worksheet destination_wks.append_row(source_wks.row_values(row_number)) # Removes the submission from the source worksheet source_wks.delete_row(row_number) return True # Confirm submission def confirm_submission(submission_id): return move_submission(submission_id, DB.get_open_submissions_worksheet(), DB.get_confirmed_submissions_worksheet()) # Deny submission def deny_submission(submission_id): return move_submission(submission_id, DB.get_open_submissions_worksheet(), DB.get_denied_submissions_worksheet()) <file_sep>/Database/server_settings.py import Database.main as DB import Database.config as config import Google.interface as Google # Adds new server to database. Returns the row index of the new record. def add_new_server(server_id): wks = DB.get_server_settings_worksheet() wks.append_row([server_id]) return wks.row_count + 1 # Gets the row in the database which contains the server settings. def get_server_row_index(server_id): wks = DB.get_server_settings_worksheet() records = wks.get_all_records() # Finding the row which contains the correct server id. for index in range(len(records)): if int(records[index]['Server ID']) == int(server_id): return index + 1 return None def get_server_row_number(server_id): index = get_server_row_index(server_id) return None if index == None else index + 1 # Get a setting for a server. def get_server_setting(server_id, setting_name): settings = get_server_settings(server_id) if settings == None: return None return get_server_settings(server_id)[setting_name] # Gets a list of settings for a server. def get_server_settings(server_id): # Opening the server settings worksheet. wks = DB.get_server_settings_worksheet() records = wks.get_all_records() for server in records: if int(server['Server ID']) == int(server_id): return server return None # Updates a setting for a server. def update_server_setting(server_id, setting_name, value): # Opening the server settings worksheet. wks = DB.get_server_settings_worksheet() row = get_server_row_number(server_id) # Adding server to database if it isnt already present. if row == None: row = add_new_server(server_id) col = DB.get_col_number(wks, setting_name) # Throwing exception if setting doesn't exist. if col == None: raise Exception('No settings called {}.'.format(setting_name)) wks.update_cell(row, col, value) # Updates multiple settings for a server. def update_server_settings(server_id, settings_dict): wks = DB.get_server_settings_worksheet() row_index = get_server_row_number(server_id) # Adding server to database if it isnt already present. if row_index == None: row_index = add_new_server(server_id) row = wks.row_values(row_index) # Making row the correct length length = wks.col_count while len(row) < length: row.append(None) # For each setting, update the setting. for key, value in settings_dict.items(): col = DB.get_col_index(wks, key) if col == None: raise Exception('No settings called {}.'.format(key)) row[col] = value # Writing to cells. cells_to_update = wks.range(row_index, 1, row_index, len(row)) for i, val in enumerate(row): cells_to_update[i].value = val # Updating cells. wks.update_cells(cells_to_update)<file_sep>/Discord/command_branch.py from inspect import iscoroutinefunction from Discord.command import Command from Discord.command_leaf import Command_Leaf import Discord.utils as utils import Discord.permissions as perms class Command_Branch(Command): def __init__(self, brief, function = None, params = None, perms = None, roles = None, servers = None, perm_role_operator = 'And', **kwargs): self._brief = brief self._meta = kwargs self._params = params self._perms = perms self._roles = roles self._servers = servers self._perm_role_operator = perm_role_operator if perm_role_operator != 'And' and perm_role_operator != 'Or': raise Exception('perm_role_operator must be \'And\' or \'Or\'') self._function = function self._commands = {} self.validate_params() def get_command(self, cmd, *argv): if not isinstance(cmd, str): return None, None cmd = cmd.lower() if cmd in self._commands: if len(argv) == 0 or isinstance(self._commands[cmd], Command_Leaf): return self._commands[cmd], argv return self._commands[cmd].get_command(*argv) return None, None def validate_add_command(self, cmd_string, cmd): if not isinstance(cmd_string, str): raise ValueError('Command name must be a string.') if len(cmd_string) == 0: raise ValueError('Command name must have at least length 1.') if self.get_command(cmd_string)[0] != None: raise ValueError('Command already exists.') if not (isinstance(cmd, Command_Leaf) or isinstance(cmd, Command_Branch)): raise ValueError('Command must be a Command Node or Command Branch.') def add_command(self, cmd_string, cmd): self.validate_add_command(cmd_string, cmd) cmd_string = cmd_string.lower() self._commands[cmd_string] = cmd async def execute(self, cmd_to_execute, *argv, **kwargs): cmd_argv = cmd_to_execute.split(' ') cmd, argv_return = self.get_command(*cmd_argv) if cmd == None: return utils.error_embed('Error.', 'Unable to find command.') if cmd._servers and not int(argv[2].server.id) in cmd._servers: return utils.error_embed('Insufficient Permissions.', 'This command can only be executed on certain servers.') roles_validated = perms.validate_roles(argv[2].author.roles, cmd._roles, argv[2].channel.permissions_for(argv[2].author)) permissions_validated = perms.validate_permissions(argv[2].channel.permissions_for(argv[2].author), cmd._perms) if cmd._perm_role_operator == 'And': if not roles_validated: return utils.error_embed('Insufficient Permissions.', 'This command can only be executed by certain roles.') if not permissions_validated: return utils.error_embed('Insufficient Permissions.', 'You do not have the permissions required to execute that command.') else: if not roles_validated and not permissions_validated: return utils.error_embed('Insufficient Permissions.', 'You do not have the permissions required to execute that command.') error = cmd.validate_execute_command(argv_return) if error: return error if cmd._function and callable(cmd._function): if iscoroutinefunction(cmd._function): return await cmd._function(*argv, **kwargs) else: return cmd._function(*argv, **kwargs) return utils.error_embed('Error.', 'could not find a callable in the command object.') def get_help_message(self, *argv): cmd = self if len(argv) != 0: cmd, _ = self.get_command(*argv) if cmd == None: return utils.error_embed('Error.', 'Unable to find command. Use help to get a list of avaliable commands.') if isinstance(cmd, Command_Leaf): return '`{}` - {}\n'.format(' '.join(argv), cmd.get_help(True)) else: result = '{}\n\nCommands:\n'.format(cmd.get_help()) for scmd in cmd._commands.keys(): result += '`{}` - {}\n'.format(scmd, cmd._commands[scmd].get_help()) return result<file_sep>/Discord/command_leaf.py from inspect import iscoroutinefunction from Discord.command import Command import Discord.utils as utils class Command_Leaf(Command): def __init__(self, function, brief, params = None, perms = None, roles = None, servers = None, perm_role_operator = 'And', **kwargs): self._brief = brief self._meta = kwargs self._params = params self._perms = perms self._roles = roles self._servers = servers self._perm_role_operator = perm_role_operator if perm_role_operator != 'And' and perm_role_operator != 'Or': raise Exception('perm_role_operator must be \'And\' or \'Or\'') self._function = function self.validate_params() async def execute(self, argv, kwargs): if callable(self._function): if iscoroutinefunction(self._function): return await self._function(*argv, **kwargs) else: return self._function(*argv, **kwargs) return utils.error_embed('Error.', 'Could not find a callable in the command object.')<file_sep>/Discord/utils.py import re import discord from time import gmtime, strftime discord_red = 0xF04747 discord_yellow = 0xFAA61A discord_green = 0x43B581 def represents_int(s): try: int(s) return True except ValueError: return False def represents_float(s): try: float(s) return True except ValueError: return False def represents_user(s): if re.match('<@!?\d{17,18}>', s) == None: return False return True def represents_channel(s): if re.match('<#\d{18}>', s) == None: return False return True def get_time(): raw_time = strftime("%Y/%m/%d %H:%M:%S", gmtime()) return '[' + raw_time + '] ' def error_embed(title, description): return discord.Embed(title = title, colour = discord_red, description = ':x: ' + description) def warning_embed(title, description): return discord.Embed(title = ':warning: ' + title, colour = discord_yellow, description = description) def info_embed(title, description): return discord.Embed(title = title, colour = discord_green, description = description)<file_sep>/Database/message.py from datetime import datetime import Database.main as DB from Database.submission import Submission as Submission_Class import Database.global_vars as global_vars import Database.config as config import Google.interface as Google import Database.submissions as submissions import Database.submission as submission def get_messages(server_id): # Getting worksheet wks = DB.get_message_worksheet() # Getting all records for server all_records = wks.get_all_records() server_records = [] for index, record in enumerate(all_records): if int(record['Server ID']) == int(server_id): record['Row Number'] = index + 2 server_records.append(record) return server_records def get_message(server_id, submission_id): # Getting worksheet wks = DB.get_message_worksheet() # Getting the record with requested server and submission id all_records = wks.get_all_records() for index, record in enumerate(all_records): if int(record['Server ID']) == int(server_id) and int(record['Submission ID']) == int(submission_id): record['Row Number'] = index + 2 return record return None def add_message(server_id, submission_id, channel_id, message_id): # Getting worksheet wks = DB.get_message_worksheet() # Generating row row_values = [None] * wks.col_count row_values[DB.get_col_index(wks, 'Server ID')] = server_id row_values[DB.get_col_index(wks, 'Submission ID')] = submission_id row_values[DB.get_col_index(wks, 'Channel ID')] = channel_id row_values[DB.get_col_index(wks, 'Message ID')] = message_id row_values[DB.get_col_index(wks, 'Last Updated')] = datetime.now().strftime(r'%d-%m-%Y %H:%M:%S') # Appending row to wks wks.append_row(row_values) def update_message(server_id, submission_id, channel_id, message_id): # Getting worksheet wks = DB.get_message_worksheet() # Getting message message = get_message(server_id, submission_id) # If message isn't yet tracked, add it. if message == None: add_message(server_id, submission_id, channel_id, message_id) return # Generating new row information row_number = message['Row Number'] length = wks.col_count row_values = wks.row_values(row_number) cha_col = DB.get_col_index(wks, 'Channel ID') msg_col = DB.get_col_index(wks, 'Message ID') time_col = DB.get_col_index(wks, 'Last Updated') row_values[msg_col] = message_id row_values[cha_col] = channel_id row_values[time_col] = datetime.now().strftime(r'%d-%m-%Y %H:%M:%S') # Writing to cells cells_to_update = wks.range(row_number, 1, row_number, length) for i, val in enumerate(row_values): cells_to_update[i].value = val # Updating cells wks.update_cells(cells_to_update) def get_outdated_messages(server_id): # Getting messages from database messages = get_messages(server_id) # Getting all submissions confirmed_submissions = submissions.get_confirmed_submissions() # Get list of which ones are out of data outdated = [] for sub in confirmed_submissions: message = None # Getting message if it exists for mes in messages: if int(mes['Submission ID']) == sub.id: message = mes break # If message doesn't exist if message == None: outdated.append((message, sub)) continue # If the message was last edited before the submission's last update if datetime.strptime(message['Last Updated'], r'%d-%m-%Y %H:%M:%S') < sub.last_updated: outdated.append((message, sub)) continue return outdated<file_sep>/Database/submission.py from datetime import datetime import Database.config as config class Submission: def __init__(self): self.id = None self.last_updated = None self.base_category = None self.door_width = None self.door_height = None self.door_pattern = None self.door_type = None self.fo_restrictions = None self.so_restrictions = None self.information = None self.build_width = None self.build_height = None self.build_depth = None self.relative_close_time = None self.relative_open_time = None self.absolute_close_time = None self.absolute_open_time = None self.build_date = None self.creators = None self.locational = None self.directional = None self.versions = None self.image_url = None self.youtube_link = None self.world_download_link = None self.server_ip = None self.coordinates = None self.command = None self.submitted_by = None def get_title(self): # Catagory title = self.base_category + ' ' # Door dimensions if self.door_width and self.door_height: title += '{}x{} '.format(self.door_width, self.door_height) elif self.door_width: title += '{} Wide '.format(self.door_width) elif self.door_height: title += '{} High '.format(self.door_height) # First order restrictions if self.fo_restrictions != None: for restriction in self.fo_restrictions: if restriction != 'None': title += '{} '.format(restriction) # Pattern if self.door_pattern[0] != 'Regular': for pattern in self.door_pattern: title += '{} '.format(pattern) # Door type if self.door_type == None: title += 'Door.' elif self.door_type == 'SKY': title += 'Skydoor.' elif self.door_type == 'TRAP': title += 'Trapdoor.' return title def get_description(self): description = [] # Second order restrictions if self.so_restrictions != None and self.so_restrictions[0] != 'None': description.append(', '.join(self.so_restrictions)) if not config.VERSIONS_LIST[-1] in self.versions: description.append('**Broken** in current version.') if self.locational == 'LOCATIONAL': description.append('**Locational**.') elif self.locational == 'LOCATIONAL_FIX': description.append('**Locational** with known fixes for each location.') if self.directional == 'DIRECTIONAL': description.append('**Directional**.') elif self.directional == 'DIRECTIONAL_FIX': description.append('**Directional** with known fixes for each direction.') if self.information: description.append('\n' + str(self.information)) if len(description) > 0: return '\n'.join(description) else: return None def get_versions_string(self): versions = [] linking = False first_version = None last_version = None for index, version in enumerate(config.VERSIONS_LIST): if version in self.versions: if linking == False: linking = True first_version = version last_version = version else: last_version = version elif linking == True: linking = False if first_version == last_version: versions.append(first_version) else: versions.append('{} - {}'.format(first_version, last_version)) first_version = None last_version = None if index == len(config.VERSIONS_LIST) - 1 and linking == True: if first_version == last_version: versions.append(first_version) else: versions.append('{} - {}'.format(first_version, last_version)) return ', '.join(versions) def get_meta_fields(self): fields = {} fields['Dimensions'] = '{}x{}x{}'.format(self.build_width, self.build_height, self.build_depth) fields['Volume'] = str(self.build_width * self.build_height * self.build_depth) fields['Opening Time'] = str(self.relative_open_time) fields['Closing Time'] = str(self.relative_close_time) if self.absolute_open_time and self.absolute_close_time: fields['Absolute Opening Time'] = self.absolute_open_time fields['Absolute Closing Time'] = self.absolute_close_time fields['Creators'] = ', '.join(sorted(self.creators)) fields['Date Of Completion'] = str(self.build_date) fields['Versions'] = self.get_versions_string() if self.server_ip: fields['Server'] = self.server_ip if self.coordinates: fields['Coordinates'] = self.coordinates if self.command: fields['Command'] = self.command if self.world_download_link: fields['World Download'] = self.world_download_link if self.youtube_link: fields['Video'] = self.youtube_link return fields @staticmethod def from_dict(dict): result = Submission() result.id = int(dict['Submission ID']) result.last_updated = datetime.strptime(dict['Last Update'], r'%d-%m-%Y %H:%M:%S') result.base_category = dict['Record Category'] if dict['Door Width']: result.door_width = int(dict['Door Width']) if dict['Door Height']: result.door_height = int(dict['Door Height']) result.door_pattern = dict['Pattern'].split(', ') if dict['Door Type'] == 'Trapdoor': result.door_type = 'TRAP' if dict['Door Type'] == 'Skydoor': result.door_type = 'SKY' if dict['First Order Restrictions']: result.fo_restrictions = dict['First Order Restrictions'].split(', ') if dict['Second Order Restrictions']: result.so_restrictions = dict['Second Order Restrictions'].split(', ') if dict['Information About Build']: result.information = dict['Information About Build'] result.build_width = int(dict['Width Of Build']) result.build_height = int(dict['Height Of Build']) result.build_depth = int(dict['Depth Of Build']) result.relative_close_time = float(dict['Relative Closing Time']) result.relative_open_time = float(dict['Relative Opening Time']) if dict['Absolute Closing Time']: result.absolute_close_time = float(dict['Absolute Closing Time']) if dict['Absolute Opening Time']: result.absolute_open_time = float(dict['Absolute Opening Time']) if dict['Date Of Creation']: result.build_date = dict['Date Of Creation'] else: result.build_date = dict['Timestamp'] result.creators = dict['In Game Name(s) Of Creator(s)'].split(',') if dict['Locationality'] == 'Locational with known fixes for each location': result.locational = 'LOCATIONAL_FIX' elif dict['Locationality'] == 'Locational without known fixes for each location': result.locational = 'LOCATIONAL' if dict['Directionality'] == 'Directional with known fixes for each direction': result.directional = 'DIRECTIONAL_FIX' elif dict['Directionality'] == 'Directional without known fixes for each direction': result.directional = 'DIRECTIONAL' result.versions = str(dict['Versions Which Submission Works In']).split(', ') if dict['Link To Image']: result.image_url = dict['Link To Image'] if dict['Link To YouTube Video']: result.youtube_link = dict['Link To YouTube Video'] if dict['Link To World Download']: result.world_download_link = dict['Link To World Download'] if dict['Server IP']: result.server_ip = dict['Server IP'] if dict['Coordinates']: result.coordinates = dict['Coordinates'] if dict['Command To Get To Build/Plot']: result.command = dict['Command To Get To Build/Plot'] result.submitted_by = dict['Your IGN / Discord Handle'] return result def to_string(self): string = '' string += 'ID: {}\n'.format(self.id) string += 'Base Catagory: {}\n'.format(self.base_category) if self.door_width: string += 'Door Width: {}\n'.format(self.door_width) if self.door_height: string += 'Door Height: {}\n'.format(self.door_height) string += 'Pattern: {}\n'.format(' '.join(self.door_pattern)) string += 'Door Type: {}\n'.format(self.door_type) if self.fo_restrictions: string += 'First Order Restrictions: {}\n'.format(', '.join(self.fo_restrictions)) if self.so_restrictions: string += 'Second Order Restrictions: {}\n'.format(', '.join(self.so_restrictions)) if self.information: string += 'Information: {}\n'.format(self.information) string += 'Build Width: {}\n'.format(self.build_width) string += 'Build Height: {}\n'.format(self.build_height) string += 'Build Depth: {}\n'.format(self.build_depth) string += 'Relative Closing Time: {}\n'.format(self.relative_close_time) string += 'Relative Opening Time: {}\n'.format(self.relative_open_time) if self.absolute_close_time: string += 'Absolute Closing Time: {}\n'.format(self.absolute_close_time) if self.absolute_open_time: string += 'Absolute Opening Time: {}\n'.format(self.absolute_open_time) string += 'Date Of Creation: {}\n'.format(self.build_date) string += 'Creators: {}\n'.format(', '.join(self.creators)) if self.locational: string += 'Locationality Tag: {}\n'.format(self.locational) if self.directional: string += 'Directionality Tag: {}\n'.format(self.directional) string += 'Versions: {}\n'.format(', '.join(self.versions)) if self.image_url: string += 'Image URL: {}\n'.format(self.image_url) if self.youtube_link: string += 'YouTube Link: {}\n'.format(self.youtube_link) if self.world_download_link: string += 'World Download: {}\n'.format(self.world_download_link) if self.server_ip: string += 'Server IP: {}\n'.format(self.server_ip) if self.coordinates: string += 'Coordinates: {}\n'.format(self.coordinates) if self.command: string += 'Command: {}\n'.format(self.command) string += 'Submitted By: {}\n'.format(self.submitted_by) return string<file_sep>/Discord/submission/submissions.py import os import discord import Discord.utils as utils from Discord.command import Param from Discord.command_leaf import Command_Leaf from Discord.command_branch import Command_Branch from Discord.permissions import * import Discord.config as config import Discord.submission.post as post import Database.submissions as submissions import Database.message as msg # Submissions Command Branch ----------------------------------------------------------------------------- SUBMISSIONS_COMMANDS = Command_Branch('View, confirm and deny submissions.') submission_roles = ['Admin', 'Moderator'] submission_perms = [ADMINISTRATOR] # Open --------------------------------------------------------------------------------------------------- async def open_function(client, user_command, message): # Sending working message. sent_message = await client.send_message(message.channel, embed = utils.info_embed('Working', 'Getting information...')) # Updating open worksheet to contain all submitted from google form. submissions.open_form_submissions() # Creating list of submissions open_submissions = submissions.get_open_submissions() desc = None if len(open_submissions) == 0: desc = 'No open submissions.' else: desc = [] for sub in open_submissions: desc.append('**{}** - {}\n_by {}_ - _submitted by {}_'.format(sub.id, sub.get_title(), ', '.join(sorted(sub.creators)), sub.submitted_by)) desc = '\n\n'.join(desc) # Creating embed em = discord.Embed(title = 'Open Records', description = desc, colour = utils.discord_green) # Sending embed await client.delete_message(sent_message) return em SUBMISSIONS_COMMANDS.add_command('open', Command_Leaf(open_function, 'Shows an overview of all submissions open for review.', roles = submission_roles)) # View --------------------------------------------------------------------------------------------------- async def view_function(client, user_command, message): # Sending working message. sent_message = await client.send_message(message.channel, embed = utils.info_embed('Working', 'Getting information...')) index = int(user_command.split(' ')[2]) open_submissions = submissions.get_open_submissions() result = None for sub in open_submissions: if sub.id == index: result = sub break await client.delete_message(sent_message) if result == None: return utils.error_embed('Error', 'No open submission with that ID.') return post.generate_embed(result) view_params = [ Param('index', 'The id of the submission you wish to view.', dtype = 'int') ] SUBMISSIONS_COMMANDS.add_command('view', Command_Leaf(view_function, 'Displays an open submission.', roles = submission_roles, params = view_params)) # Confirm ------------------------------------------------------------------------------------------------ async def confirm_submission(client, user_command, message): # Sending working message. sent_message = await client.send_message(message.channel, embed = utils.info_embed('Working', 'Please wait...')) submission_id = int(user_command.split(' ')[2]) sub = submissions.get_open_submission(submission_id) if sub == None: await client.delete_message(sent_message) await client.send_message(message.channel, embed = utils.error_embed('Error', 'No open submission with that ID.')) return await post.post_submission(client, sub) submissions.confirm_submission(sub.id) await client.delete_message(sent_message) await client.send_message(message.channel, embed = utils.info_embed('Success', 'Submission has successfully been confirmed.')) confirm_params = [ Param('index', 'The id of the submission you wish to confirm.', dtype = 'int') ] SUBMISSIONS_COMMANDS.add_command('confirm', Command_Leaf(confirm_submission, 'Marks a submission as confirmed.', roles = submission_roles, servers = [config.OWNER_SERVER_ID], params = confirm_params)) # Deny --------------------------------------------------------------------------------------------------- async def deny_submission(client, user_command, message): # Sending working message. sent_message = await client.send_message(message.channel, embed = utils.info_embed('Working', 'Please wait...')) submission_id = int(user_command.split(' ')[2]) sub = submissions.get_open_submission(submission_id) if sub == None: await client.delete_message(sent_message) await client.send_message(message.channel, embed = utils.error_embed('Error', 'No open submission with that ID.')) return submissions.deny_submission(sub.id) await client.delete_message(sent_message) await client.send_message(message.channel, embed = utils.info_embed('Success', 'Submission has successfully been denied.')) deny_params = [ Param('index', 'The id of the submission you wish to deny.', dtype = 'int') ] SUBMISSIONS_COMMANDS.add_command('deny', Command_Leaf(deny_submission, 'Marks a submission as denied.', roles = submission_roles, servers = [config.OWNER_SERVER_ID], params = deny_params)) # Outdated ----------------------------------------------------------------------------------------------- async def outdated_function(client, user_command, message): # Sending working message. sent_message = await client.send_message(message.channel, embed = utils.info_embed('Working', 'Getting information...')) # Creating list of submissions outdated_submissions = msg.get_outdated_messages(message.server.id) desc = None if len(outdated_submissions) == 0: desc = 'No outdated submissions.' else: desc = [] for sub in outdated_submissions: sub_obj = sub[1] desc.append('**{}** - {}\n_by {}_ - _submitted by {}_'.format(sub_obj.id, sub_obj.get_title(), ', '.join(sorted(sub_obj.creators)), sub_obj.submitted_by)) desc = '\n\n'.join(desc) # Creating embed em = discord.Embed(title = 'Outdated Records', description = desc, colour = utils.discord_green) # Sending embed await client.delete_message(sent_message) return em SUBMISSIONS_COMMANDS.add_command('outdated', Command_Leaf(outdated_function, 'Shows an overview of all discord posts that are require updating.', perms = submission_perms, roles = submission_roles, perm_role_operator = 'Or')) # Update ------------------------------------------------------------------------------------------------- async def update_function(client, user_command, message): # Sending working message. sent_message = await client.send_message(message.channel, embed = utils.info_embed('Working', 'Updating information...')) submission_id = int(user_command.split(' ')[2]) outdated_submissions = msg.get_outdated_messages(message.server.id) sub = None for outdated_sub in outdated_submissions: if outdated_sub[1].id == submission_id: sub = outdated_sub break if sub == None: await client.delete_message(sent_message) await client.send_message(message.channel, embed = utils.error_embed('Error', 'No outdated submissions with that ID.')) return if sub[0] == None: await post.post_submission_to_server(client, sub[1], message.server.id) else: await post.edit_post(client, message.server, sub[0]['Channel ID'], sub[0]['Message ID'], sub[1]) await client.delete_message(sent_message) await client.send_message(message.channel, embed = utils.info_embed('Success', 'Post has successfully been updated.')) update_params = [ Param('index', 'The id of the submission you wish to deny.', dtype = 'int') ] SUBMISSIONS_COMMANDS.add_command('update', Command_Leaf(update_function, 'Updated an outdate discord post.', perms = submission_perms, params = update_params, roles = submission_roles, perm_role_operator = 'Or')) # Update All --------------------------------------------------------------------------------------------- async def update_all_function(client, user_command, message): # Sending working message. sent_message = await client.send_message(message.channel, embed = utils.info_embed('Working', 'Updating information...')) outdated_submissions = msg.get_outdated_messages(message.server.id) for sub in outdated_submissions: if sub[0] == None: await post.post_submission_to_server(client, sub[1], message.server.id) else: await post.edit_post(client, message.server, sub[0]['Channel ID'], sub[0]['Message ID'], sub[1]) await client.delete_message(sent_message) await client.send_message(message.channel, embed = utils.info_embed('Success', 'All posts have been successfully updated.')) SUBMISSIONS_COMMANDS.add_command('update_all', Command_Leaf(update_all_function, 'Updates all outdated discord posts.', perms = submission_perms, roles = submission_roles, perm_role_operator = 'Or'))<file_sep>/Discord/permissions.py CREATE_INSTANT_INVITE = 0x00000001 KICK_MEMBERS = 0x00000002 BAN_MEMBERS = 0x00000004 ADMINISTRATOR = 0x00000008 MANAGE_CHANNELS = 0x00000010 ADD_REACTIONS = 0x00000040 VIEW_AUDIT_LOG = 0x00000080 SEND_MESSAGES = 0x00000800 SEND_TTS_MESSAGES = 0x00001000 MANAGE_MESSAGES = 0x00002000 EMBED_LINKS = 0x00004000 ATTACH_FILES = 0x00008000 READ_MESSAGE_HISTORY = 0x00010000 MENTION_EVERYONE = 0x00020000 USE_EXTERNAL_EMOJIS = 0x00040000 CONNECT = 0x00100000 SPEAK = 0x00200000 MUTE_MEMBERS = 0x00400000 DEAFEN_MEMBERS = 0x00800000 MOVE_MEMBERS = 0x01000000 USE_VAD = 0x02000000 CHANGE_NICKNAME = 0x04000000 MANAGE_NICKNAMES = 0x08000000 MANAGE_ROLES = 0x10000000 MANAGE_WEBHOOKS = 0x20000000 MANAGE_EMOJIS = 0x40000000 def validate_permissions(user_perms, cmd_perms): if not cmd_perms: return True for perm in cmd_perms: if perm == CREATE_INSTANT_INVITE and not user_perms.create_instant_invite: return False if perm == KICK_MEMBERS and not user_perms.kick_members: return False if perm == BAN_MEMBERS and not user_perms.ban_members: return False if perm == ADMINISTRATOR and not user_perms.administrator: return False if perm == MANAGE_CHANNELS and not user_perms.manage_channels: return False if perm == ADD_REACTIONS and not user_perms.add_reactions: return False if perm == VIEW_AUDIT_LOG and not user_perms.view_audit_logs: return False if perm == SEND_MESSAGES and not user_perms.send_messages: return False if perm == SEND_TTS_MESSAGES and not user_perms.send_tts_messages: return False if perm == MANAGE_MESSAGES and not user_perms.manage_messages: return False if perm == EMBED_LINKS and not user_perms.embed_links: return False if perm == ATTACH_FILES and not user_perms.attach_files: return False if perm == READ_MESSAGE_HISTORY and not user_perms.read_message_history: return False if perm == MENTION_EVERYONE and not user_perms.mention_everyone: return False if perm == USE_EXTERNAL_EMOJIS and not user_perms.external_emojis: return False if perm == CONNECT and not user_perms.connect: return False if perm == SPEAK and not user_perms.speak: return False if perm == MUTE_MEMBERS and not user_perms.mute_members: return False if perm == DEAFEN_MEMBERS and not user_perms.deafen_members: return False if perm == MOVE_MEMBERS and not user_perms.move_members: return False if perm == USE_VAD and not user_perms.use_voice_activation: return False if perm == CHANGE_NICKNAME and not user_perms.change_nickname: return False if perm == MANAGE_NICKNAMES and not user_perms.manage_nicknames: return False if perm == MANAGE_ROLES and not user_perms.manage_roles: return False if perm == MANAGE_WEBHOOKS and not user_perms.manage_webhooks: return False if perm == MANAGE_EMOJIS and not user_perms.manage_emojis: return False return True def validate_roles(user_roles, cmd_role_names, user_perms): if cmd_role_names == None: return True # Administrator permission override if user_perms.administrator: return True if isinstance(cmd_role_names, str): for user_role in user_roles: if user_role.name == cmd_role_names: return True return False if len(cmd_role_names) == 0: return True for cmd_role_name in cmd_role_names: for user_role in user_roles: if user_role.name == cmd_role_name: return True return False<file_sep>/Database/global_vars.py import Database.main as DB import Database.config as config import Google.interface as Google def get_next_id(): wks = DB.get_globals_worksheet() return int(wks.get_all_records()[0]['Next ID']) def update_next_id(new_next_id): wks = DB.get_globals_worksheet() col_num = DB.get_col_number(wks, 'Next ID') wks.update_cell(2, col_num, new_next_id) def add_to_next_id(count): wks = DB.get_globals_worksheet() next_id = int(wks.get_all_records()[0]['Next ID']) + count col_num = DB.get_col_number(wks, 'Next ID') wks.update_cell(2, col_num, next_id)<file_sep>/Discord/commands.py import os import discord import Discord.utils as utils from Discord.command import Param from Discord.command_leaf import Command_Leaf from Discord.command_branch import Command_Branch from Discord.permissions import * import Discord.config as config import Discord.settings.settings as settings import Discord.submission.submissions as submissions # Main Command Branch -------------------------------------------------------------------------------------------- BOT_NAME = 'Redstone Squid' BOT_VERSION = '1.0' SOURCE_CODE_URL = 'https://github.com/Kappeh/Redstone-Squid' FORM_LINK = 'https://goo.gl/forms/35mjuQHId4sgCnZ82' COMMANDS = Command_Branch(BOT_NAME + ' v' + BOT_VERSION) # Invite Link ---------------------------------------------------------------------------------------------------- async def invite_link(client, user_command, message): await client.send_message(message.channel, 'https://discordapp.com/oauth2/authorize?client_id=' + str(client.user.id) + '&scope=bot&permissions=8') COMMANDS.add_command('invite_link', Command_Leaf(invite_link, 'Invite me to your other servers!')) # Source code ---------------------------------------------------------------------------------------------------- async def source_code(client, user_command, message): await client.send_message(message.channel, 'Source code can be found at: {}.'.format(SOURCE_CODE_URL)) COMMANDS.add_command('source_code', Command_Leaf(source_code, 'Link to {}\'s source code.'.format(BOT_NAME))) # Submit record -------------------------------------------------------------------------------------------------- async def submit_record(client, user_command, message): em = discord.Embed(title = 'Submission form.', description = 'You can submit new records with ease via our google form: {}'.format(FORM_LINK), colour = utils.discord_green) em.set_image(url = 'https://i.imgur.com/AqYEd1o.png') await client.send_message(message.channel, embed = em) COMMANDS.add_command('submit_record', Command_Leaf(submit_record, 'Links you to our record submission form.')) # Option --------------------------------------------------------------------------------------------------------- COMMANDS.add_command('settings', settings.SETTINGS_COMMANDS) # Submissions ---------------------------------------------------------------------------------------------------- COMMANDS.add_command('submissions', submissions.SUBMISSIONS_COMMANDS) # Help ----------------------------------------------------------------------------------------------------------- async def help_func(client, user_command, message): argv = user_command.split(' ')[1:] help_message = COMMANDS.get_help_message(*argv) if isinstance(help_message, discord.Embed): return help_message help_message += '\nUse `{}help <command>` to get more information.\n'.format(config.PREFIX) em = discord.Embed(title = 'Help', description = help_message, colour = 0x43B581) await client.send_message(message.channel, embed = em) help_func_params = [ Param('cmd', 'The command which you need help with.', dtype = 'text', optional = True) ] COMMANDS.add_command('help', Command_Leaf(help_func, 'Shows help messages.', params = help_func_params))<file_sep>/README.md # Redstone Squid This is a discord bot designed to make the process of submitting, confirming and denying submissions easier. In addition to this, it manages a database of records automatically. ## Discord Set Up ### Adding Bot To Servers If you wish to invite the bot to your Discord server, click [here](https://discordapp.com/oauth2/authorize?client_id=528946065668308992&scope=bot&permissions=8). It is recommended to give the bot administrator permissions but is not required for it's functionality. ### Setting Up Channels Before the bot can post any records to your server, you must tell it here to post each category. Multiple categories can be set to a single channel. As an example, let's pretend you want to set all categories to post to a channel called `#records`. Within the discord server you would run: ``` !settings smallest_channel set #records !settings fastest_channel set #records !settings smallest_observerless_channel set #records !settings fastest_observerless_channel set #records !settings first_channel set #records ``` Whenever a submission is confirmed by the bot's admins, it will be posted in the respective channel. You can unset a channel by either setting it to another channel or running the unset command e.g. ``` !settings smallest_channel unset ``` In addition to this, you can check which channel a setting is currently set to via the query command e.g. ``` !settings fastest_channel query ``` If you want to query all settings at once, you can run: ``` !settings query_all ``` ## Other Commands This list of commands is subject to change due to improvements and new features. `!invite_link` gives the user a link which they can use to add the bot to their servers. `!source_code` links a user to this GitHub repository. `!submit_record` provides a user to the Google Form which is used for collecting record submissions. `!settings` has been discussed above. `!submissions` is a server specific, role specific set of commands used to view, confirm and deny submissions. _This will be discussed below._ `!help <command>` provides a user with a help message. If a command is provided, a help message for that command will be provided. ### Submissions Commands `!submissions open` provides an overview submissions that are open for review. `!submissions view <index>` displays the full submission with a given index. `!submission confirm <index>` confirms a submission and posts it to the correct channels. `!submissions deny <index>` denies a submission. ## Contributing Please read [CODE_OF_CONDUCT.md](https://github.com/Kappeh/Redstone-Squid/blob/master/CODE_OF_CONDUCT.md) for details on our code of conduct, and the process for submitting pull requests to us. ## Authors * **<NAME>** - *Initial work* - [Kappeh](https://github.com/Kappeh) ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details ## Acknowledgements - Thanks to the technical Minecraft community for having me. - Discord and Google are awesome. Thanks for great APIs and documentation. - Thanks to all of the people on StackOverflow for the help and support. <file_sep>/Database/config.py # Workbook name for database WORKBOOK_NAME = 'RecordBotDB' # Globals sheet GLOBALS_SHEET_INDEX = 0 # Server settings sheet SERVER_SETTINGS_SHEET_INDEX = 1 # Submission database sheets FORM_SUBMISSIONS_SHEET_INDEX = 2 OPEN_SUBMISSIONS_SHEET_INDEX = 3 CONFIRMED_SUBMISSIONS_SHEET_INDEX = 4 DENIED_SUBMISSIONS_SHEET_INDEX = 5 # Submission posts database sheets MESSAGE_SHEET_INDEX = 6 # List of versions for version string parser VERSIONS_LIST = ['Pre 1.5', '1.5', '1.6', '1.7', '1.8', '1.9', '1.10', '1.11', '1.12', '1.13', '1.13.1 / 1.13.2', '1.14', '1.14.1']<file_sep>/Database/main.py import Database.config as config import Google.interface as Google # Gets the workbook which contains the Bot's database. def get_workbook(): return Google.Connection.get().open(config.WORKBOOK_NAME) # Gets the worksheet which contains the global variables. def get_globals_worksheet(): return get_workbook().get_worksheet(config.GLOBALS_SHEET_INDEX) # Get the worksheet which contains the server settings. def get_server_settings_worksheet(): return get_workbook().get_worksheet(config.SERVER_SETTINGS_SHEET_INDEX) # Gets the worksheet which contains the submissions from the google form. def get_form_submissions_worksheet(): return get_workbook().get_worksheet(config.FORM_SUBMISSIONS_SHEET_INDEX) # Gets the worksheet which contains the open submissions. def get_open_submissions_worksheet(): return get_workbook().get_worksheet(config.OPEN_SUBMISSIONS_SHEET_INDEX) # Gets the worksheet which contains the confirmed submissions. def get_confirmed_submissions_worksheet(): return get_workbook().get_worksheet(config.CONFIRMED_SUBMISSIONS_SHEET_INDEX) # Gets the worksheet which contains the denied submissions. def get_denied_submissions_worksheet(): return get_workbook().get_worksheet(config.DENIED_SUBMISSIONS_SHEET_INDEX) # Gets the worksheet which contains the message ids of posted submissions def get_message_worksheet(): return get_workbook().get_worksheet(config.MESSAGE_SHEET_INDEX) # Returns a list of possible settings. def header_list(wks): return wks.row_values(1) # Returns the amount of settings a server can have. def header_count(wks): return len(header_list(wks)) # Gets the column in the database which contains the setting. def get_col_index(wks, header_name): # Makes a list of headers. headers = wks.row_values(1) # Finding the column which contains the correct setting name. try: return headers.index(header_name) except ValueError: return None def get_col_number(wks, header_name): index = get_col_index(wks, header_name) return None if index == None else index + 1<file_sep>/requirements.txt aiohttp>=1.0.5 asn1crypto>=0.24.0 async-timeout>=3.0.1 certifi>=2018.11.29 cffi>=1.11.5 chardet>=3.0.4 cryptography>=2.4.2 discord==0.0.2 discord.py==0.16.12 gspread>=3.1.0 httplib2>=0.12.0 idna>=2.8 multidict>=4.5.2 oauth2client>=4.1.3 pyasn1>=0.4.5 pyasn1-modules>=0.2.2 pycparser>=2.19 pyOpenSSL>=18.0.0 requests>=2.21.0 rsa>=4.0 six>=1.12.0 urllib3>=1.24.1 websockets>=3.4 <file_sep>/Discord/config.py OWNER = 'Kappeh#9375' OWNER_SERVER_ID = 433618741528625152 PREFIX = '!'<file_sep>/app.py # RecordBot version 1.0 # Made by Kappeh # https://github.com/Kappeh/RecordBot import Google.interface as google import Discord.interface as discord<file_sep>/Discord/interface.py import os import re import sys import discord import configparser import Discord.utils as utils from Discord.config import * from Discord.commands import COMMANDS # Establishing connection with discord TOKEN = os.environ.get('DISCORD_TOKEN') if not TOKEN: if os.path.isfile('Discord/auth.ini'): config = configparser.ConfigParser() config.read('Discord/auth.ini') TOKEN = config.get('discord', 'token') else: raise Exception('Specify discord token either with an auth.ini or a DISCORD_TOKEN environment variable.') CLIENT = discord.Client() LOG_USER = {'name': OWNER} # Log function def log(msg, first_log = False): timestamp_msg = utils.get_time() + msg print(timestamp_msg) if first_log: timestamp_msg = '-' * 90 + '\n' + timestamp_msg if 'member' in LOG_USER: return CLIENT.send_message(LOG_USER['member'], timestamp_msg) @CLIENT.event async def on_ready(): for member in CLIENT.get_all_members(): if str(member) == LOG_USER['name']: LOG_USER['member'] = member await log('Bot logged in with name: {} and id: {}.'.format(CLIENT.user.name, CLIENT.user.id), first_log = True) # Message event @CLIENT.event async def on_message(message): user_command = '' if message.content.startswith(PREFIX): user_command = message.content.replace(PREFIX, '', 1) elif not message.server: user_command = message.content if CLIENT.user.id != message.author.id and user_command: log_message = str(message.author) + ' ran: "' + user_command + '"' if message.server: log_message += ' in server: {}.'.format(message.server.name) else: log_message += ' in a private message.' log_routine = log(log_message) if LOG_USER['name'] != str(message.author) or message.server: await log_routine output = await COMMANDS.execute(user_command, CLIENT, user_command, message) if isinstance(output, str): await CLIENT.send_message(message.channel, output) if isinstance(output, discord.Embed): await CLIENT.send_message(message.channel, embed = output) # Running the application CLIENT.run(TOKEN)<file_sep>/Discord/submission/post.py import discord import Discord.utils as utils from Discord.command import Param from Discord.command_leaf import Command_Leaf from Discord.command_branch import Command_Branch from Discord.permissions import * import Discord.settings.settings as settings import Database.submission as submission import Database.server_settings as server_settings import Database.message as msg def generate_embed(submission_obj): # Title ------------------------------------------------------------------------------- # Catagory title = submission_obj.get_title() # Description ------------------------------------------------------------------------- description = submission_obj.get_description() # Embed ------------------------------------------------------------------------------- em = None if description is None: em = discord.Embed(title = title, colour = utils.discord_green) else: em = discord.Embed(title = title, description = description, colour = utils.discord_green) fields = submission_obj.get_meta_fields() for key, val in fields.items(): em.add_field(name = key, value = val, inline = True) if submission_obj.image_url: em.set_image(url = submission_obj.image_url) em.set_footer(text = 'Submission ID: {}.'.format(submission_obj.id)) return em # Get the channels ['smallest', 'fastest', 'smallest_observerless', 'fastest_observerless'] to post record to def get_channel_type_to_post_to(submission_obj): if submission_obj.base_category == 'First': return 'First' if submission_obj.base_category == 'Fastest' or submission_obj.base_category == 'Fastest Smallest': if submission_obj.so_restrictions is None: return 'Fastest' elif 'Observerless' in submission_obj.so_restrictions: return 'Fastest Observerless' else: return 'Fastest' elif submission_obj.base_category == 'Smallest' or submission_obj.base_category == 'Smallest Fastest': if submission_obj.so_restrictions is None: return 'Smallest' elif 'Observerless' in submission_obj.so_restrictions: return 'Smallest Observerless' else: return 'Smallest' return None # Gets all channels which a submission should be posted to def get_channels_to_post_to(client, submission_obj): # Get channel type to post submission to channel_type = get_channel_type_to_post_to(submission_obj) channels = [] # For each server the bot can see for server in client.servers: # Find the channel (if set) that is set for this post to go to channel = settings.get_channel_for(server, channel_type) if not channel: continue channels.append(channel) return channels # Posts submission to each server in the channel the server settings worksheet async def post_submission(client, submission_obj): channels = get_channels_to_post_to(client, submission_obj) em = generate_embed(submission_obj) for channel in channels: message = await client.send_message(channel, embed = em) msg.update_message(channel.server.id, submission_obj.id, message.channel.id, message.id) async def post_submission_to_server(client, submission_obj, server_id): channels = get_channels_to_post_to(client, submission_obj) em = generate_embed(submission_obj) for channel in channels: if channel.server.id == server_id: message = await client.send_message(channel, embed = em) msg.update_message(channel.server.id, submission_obj.id, message.channel.id, message.id) # Updates post to conform to the submission obj async def edit_post(client, server, channel_id, message_id, submission_obj): em = generate_embed(submission_obj) channel = client.get_channel(str(channel_id)) message = await client.get_message(channel, int(message_id)) updated_message = await client.edit_message(message, embed = em) msg.update_message(server.id, submission_obj.id, str(channel_id), updated_message.id)
0e4034991cf58e7ad2c0ceab996b1f4b7942891c
[ "Markdown", "Python", "Text" ]
22
Python
Kappeh/Redstone-Squid
05848415761bf885551dcc215bec44468ef775b3
3d84e268432c9dc367109ca8772710b18e1c8f54
refs/heads/master
<repo_name>mreskini/FoodApp<file_sep>/src/components/hero-section.jsx import ComponentWrapper from "./component-wrapper" import wavesImage from "../assets/img/waves.png" import sandwichImage from "../assets/img/sandwich.png" import googlePlay from "../assets/img/google-play.png" import appStore from "../assets/img/app-store.png" import Navigation from "./navigation" const Hero = () => { return ( <> <div className="py-5 col-12"> <div className="mb-5"> <Navigation /> </div> <div className="row"> <div className="col-lg-7"> <div className="display-1 font-weight-600 hero-main-title"> Always choose happy food </div> <img src={wavesImage} alt="Waves" className="my-5 img-fluid" /> <p className="text-white font-karla font-weight-500 fs-20"> These tasty certified USDA Organic eggs come from farms that have been pesticide-free for at least three years and from free range flocks that receive no antibiotics </p> <div className="mt-5"> <img src={appStore} alt="App Store" className="img-fluid mr-3" /> <img src={googlePlay} alt="Google Play" className="img-fluid" /> </div> </div> <div className="col-lg-5"> <img src={sandwichImage} alt="Sandwich" className="img-fluid float-right" /> </div> </div> </div> </> ) } const HeroSection = ComponentWrapper(Hero, "hero-section-bg") export default HeroSection <file_sep>/src/components/how-to-section.jsx import ComponentWrapper from "./component-wrapper" import { BsSearch, BsLayoutTextSidebar, BsReplyAll } from "react-icons/bs" const HowTo = () => { return ( <div className="padding-bottom-150 padding-top-200"> <div className="py-5 my-5"> <div className="h1 font-weight-600 text-center"> <span className="how-to-section-title">How it works</span> </div> <div className="my-5 py-5"> <div className="row pb-5 mb-5"> <div className="col-lg-4 text-center px-5"> <BsSearch className="display-2 mb-4" /> <h1 className="how-to-section-title h3 font-weight-600 text-center my-4"> Search Resturant </h1> <p className="text-white text-center font-karla"> Each time a digital asset is purchased or sold, Sequoir donates a percentage of the fees back </p> </div> <div className="col-lg-4 text-center px-5"> <BsLayoutTextSidebar className="display-2 mb-4" /> <h1 className="how-to-section-title h3 font-weight-600 text-center my-4"> Order Food </h1> <p className="text-white text-center font-karla"> Each time a digital asset is purchased or sold, Sequoir donates a percentage of the fees back </p> </div> <div className="col-lg-4 text-center px-5"> <BsReplyAll className="display-2 mb-4" /> <h1 className="how-to-section-title h3 font-weight-600 text-center my-4"> Deliver to You </h1> <p className="text-white text-center font-karla"> Each time a digital asset is purchased or sold, Sequoir donates a percentage of the fees back </p> </div> </div> </div> </div> </div> ) } const HowToSection = ComponentWrapper(HowTo, "how-to-section-bg") export default HowToSection <file_sep>/src/components/order-section.jsx import ComponentWrapper from "./component-wrapper" import orderImage from "../assets/img/order-bg.png" import { BsCheckCircle } from "react-icons/bs" const Order = () => { return ( <div className="py-5 my-5"> <div className="row py-5"> <div className="col-lg-6 my-auto"> <p className="theme-content-color font-weight-500"> What is this? </p> <h4 className="theme-title-color h1 font-weight-600 my-3"> Online Ordering Systems & Mobile Apps for Restaurant </h4> <p className="theme-content-color font-weight-500"> Each time a digital asset is purchased or sold, Sequoir donates a percentage of the fees back into the development </p> <ul className="list-inline"> <li className="theme-content-color font-weight-500 mb-2"> <BsCheckCircle className="theme-orange-color h5 my-auto mr-3" /> Each time a digital asset is purchased or sold </li> <li className="theme-content-color font-weight-500 mb-2"> <BsCheckCircle className="theme-orange-color h5 my-auto mr-3" /> Each time a digital asset is purchased or sold </li> <li className="theme-content-color font-weight-500 mb-2"> <BsCheckCircle className="theme-orange-color h5 my-auto mr-3" /> Each time a digital asset is purchased or sold </li> </ul> </div> <div className="col-lg-6 text-right"> <img src={orderImage} className="img-fluid" alt="Delivery Boy" /> </div> </div> </div> ) } const OrderSection = ComponentWrapper(Order, "") export default OrderSection <file_sep>/src/components/component-wrapper.jsx const ComponentWrapper = (WrappedComponent, backgroundColorCssClassName) => { return (props) => { return ( <div className="container-fluid"> <div className={`row ${backgroundColorCssClassName}`}> <div className="col-10 mx-auto px-5"> <WrappedComponent {...props} /> </div> </div> </div> ) } } export default ComponentWrapper<file_sep>/src/components/navigation.jsx import { Container, Nav, Navbar } from "react-bootstrap" import logoWhite from "../assets/img/logo-white.png" export default function Navigation() { return ( <Navbar expand="lg" className="p-0" id="navigation"> <Container className="mx-0 col-12"> <Navbar.Brand href="#" className="ml-auto"> <img src={logoWhite} alt="Logo White" className="img-fluid" /> </Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="mx-auto"> <Nav.Link href="#" className="navigation-bar-item active-section"> Home </Nav.Link> <Nav.Link href="#" className="navigation-bar-item"> Pages </Nav.Link> <Nav.Link href="#" className="navigation-bar-item"> About Us </Nav.Link> <Nav.Link href="#" className="navigation-bar-item"> How? </Nav.Link> <Nav.Link href="#" className="navigation-bar-item"> Overview </Nav.Link> </Nav> <div className="btn btn-theme-orange ml-auto"> Get Started </div> </Navbar.Collapse> </Container> </Navbar> ) }
272ee26d1ae6367d10c35e08d2749aef0df63ed0
[ "JavaScript" ]
5
JavaScript
mreskini/FoodApp
ca98f1134f6a485bb9e4ba4af24fbf611b7fbf2a
6fa0728656951c62a7e7e43f613b8f18d3c2b1e2
refs/heads/master
<repo_name>fableh/sap-cp-cf-iot-ae-route<file_sep>/README.md # sap-cp-cf-iot-ae-route<file_sep>/sycor/webapp/controller/Main.controller.js sap.ui.define([ "sap/ui/core/mvc/Controller", "sycor/model/model" ], function(Controller, Model) { "use strict"; return Controller.extend("sycor.controller.Main", { onInit : function(){ //getting the data from Model.js var routesModel = Model.getTripsModel(); //setting routesModel to the view this.getView().setModel(routesModel,"routesModel"); } }); });
3a517571d17841ee263a6ea2b52a389c61f97701
[ "Markdown", "JavaScript" ]
2
Markdown
fableh/sap-cp-cf-iot-ae-route
ab61af1d81db0f3b559ac9d03a1381e421e82d5d
33e0017bfdebd974739af1f19539711b0dedcb03
refs/heads/master
<repo_name>oldNoakes/g5-test<file_sep>/extract.rb require 'highline/import' require 'platform-api' require 'rendezvous' require 'erb' require 'logger' class HerokuInfoExtractor def initialize(auth_token) @heroku = PlatformAPI.connect_oauth(auth_token) @log = Logger.new(STDOUT) end def extract(appname_array) apps_to_extract_from = appname_array.empty? ? get_all_apps : appname_array apps_to_extract_from.inject({}) do |result, app| @log.info "Querying application #{app}" result.merge(get_client_location_web_themes(app)) end end def report(appname_array) @results = extract(appname_array) template = ERB.new(File.read('./report.erb'), nil, '-') puts template.result(binding) end private def extraction_command 'NEWRELIC_AGENT_ENABLED=false rails runner "puts({ Client.first.name => Location.all.inject({}) { |result, location| result.update(location.name => location.website.web_templates.all.find{ |temp| temp.web_theme }.web_theme.name) } }.to_json)" 2>/dev/null' end def get_client_location_web_themes(application_name) response = @heroku.dyno.create(application_name, {'attach' => true, 'command' => extraction_command}) rz = Rendezvous.new({input:StringIO.new, output:StringIO.new, url: response['attach_url'], activity_timeout:300}) rz.start JSON.parse(rz.output.string) end def get_all_apps @log.info "No apps provided, getting all apps attached to this account" # This could be expensive if you have 100 apps on the account - could limit it @heroku.app.list.map { |app| app["name"] } end end auth = ask( "Please provide your heroku oauth token: " ) { |auth_token| auth_token.echo = false } apps_input = ask( "Please provide apps in CSV format (empty will default to all apps available to oauth token): ") apps = apps_input.split(',').map(&:strip) extractor = HerokuInfoExtractor.new(auth) puts extractor.report(apps) <file_sep>/README.md # g5-test Example code for pulling out specific information from rails console for Heroku. ### Usage ~~~ ruby extract.rb ~~~ Will prompt for: * [Heroku OAuth token](https://devcenter.heroku.com/articles/platform-api-quickstart#authentication) * A comma separate list of apps you want to query * if you do not enter any, it will simply query heroku for ALL apps that the OAuth token has access to and use that Example: ~~~ ruby extract.rb Please provide your heroku oauth token: Please provide apps in CSV format (empty will default to all apps available to oauth token): g5-cms-1t9dz1wn-jm-real-estate ~~~ ### Implementation The code connects to the heroku plaform api and does the following: 1. Spin up a dyno against each app that runs a specific command to dump the requested info in JSON format to stdout on the heroku host 2. Captures the rendezvous attachment URL from each API call and connects to it to grab the output into a StringIO object 3. Parases the return JSON string back into a Hash object on the client side and merge is with any other existing hashes of info 4. Wrote a very basic reporting mechanism - both the reporting mechanism and the extraction are public on the class since I think the raw data is likely more useful - the reporting was just put in to make it look nice on the command line Implemented using: * [Heroku platform-api gem](https://github.com/heroku/platform-api) * [Heroku Rendezvous gem](https://github.com/heroku/rendezvous.rb) Inspiration drawn from innumerable sources but big ones were: * [This github issue](https://github.com/heroku/heroku/issues/617) which showed me it was possible to run command line via the API * Referenced this version of the Rakefile from the stringer codebase: https://github.com/swanson/stringer/commit/f0e18622cada3c30acffc430a2f117ff55ef182a#diff-52c976fc38ed2b4e3b1192f8a8e24cff which gave me the api target * [Heroku platform API](https://devcenter.heroku.com/articles/platform-api-reference#app) - this caused me to start going down the path of implementing this using the rest-client gem (was testing using curl on command line so seemed the logical move) before finding the platform-api gem Wish I had more interim commits to show prior to this but a great deal of work was spent: * Initially on the command line with curl figuring out the API * Then in IRB sorting out how to do what I had found with curl via the ruby API * Once I had nailed the commmand that had to be run, the API endpoint that could execute it for me and the method to grab the output from that execution - just put it all together ### Concerns * No unit tests - typically would try to TDD this kind of work but I treated it more like a spike due to my unfamiliarity with the Heroku interface * There are numerous places that it would be good to put in some tests and some validations to verify that data is always available * In the example apps that you provided me, the only wrinkle that came up was that not all web_templates had web_themes so had to find the one that had it attached -> e.g. ~~~ Location.first.website.web_templates.first.web_theme => nil Location.first.website.web_templates.all.find{ |temp| temp.web_theme }.web_theme.name => Ivy ~~~ * Speed - running this against 2 apps with Benchmark enabled took 26 seconds - not sure how scalable this is to hundreds of apps * Each call creates a one-off dyno on the app - not sure if this would impact cost or the application performance * To try and ensure that only get the data requested gets returned in the output capture, I switched off new relic via an ENV variable on the command and redirected stderr to /dev/null -> this means we lose any valuable error info if the command fails on a specific host ### Improvements * Not doing anything useful with the output other than dumping into a very basic report * Currently, if this process gets through 99% of the apps and then fails, you lose everything AND don't get any useful capture from the command failure -> should be hardened to cope with failures on individual apps and potentially capture the stderr from the remote box * Could potentially fork or thread this to improve performance <file_sep>/Gemfile source 'https://rubygems.org' gem 'rest-client' gem 'highline' gem 'platform-api' gem 'rendezvous'
c11f08b0dafbecb05c3bbbcca823344a6580c8ff
[ "Markdown", "Ruby" ]
3
Ruby
oldNoakes/g5-test
5ab5552c7e4afab4e92bce84f90f617ce7bf073d
d640eeabc93c506d255ecd3b82a307c98634d3a6
refs/heads/master
<repo_name>jperezaguila/ejemplo<file_sep>/ejemplo/fuciones.js var saludo = function (texto){ alert ("Hola " + texto); } function saludando(texto) { alert("HOLA " + texto.target.outerText); } document.getElementById("btn1").onclick = saludo; //document.getElementById("btn2").onclick = saludando; //document.getElementById("btn1").onclick = function (e) { // alert("Hola " + e.target.outerText); //} //document.getElementById("btn2").onclick = function () { // saludando("Hola mundo es el boton2"); //} //ejemplo de sintaxis de funcion auto invocada// (function () { document.getElementById("btn2").onclick = function () { saludando("Hola mundo es el boton2"); }; })(); <file_sep>/ejemplo/funcionescalculadora.js var numero1 = parseInt var numero2= parseInt("num2"); function operacion() { //var n = document.getElementById(); document.getElementById("btsum").onclick; if document.getElementById("btnsum").onclick= function sumar(); } function sumar (){ for (document.getElementById) = ("btntot"); var resultado = ("numero1")+("numero2"); document.write=("resultado"); }
43dd2ef1e556a9fbc044174cf154f4b3025f0f15
[ "JavaScript" ]
2
JavaScript
jperezaguila/ejemplo
b0990580b924bdb07a7ea757498d83f2b9ab3539
a115fcb1f6ae5400d5d4b213c8c1fa2a37b2e819
refs/heads/master
<file_sep>import router from "../router"; import { accountService } from '../_services' const user = JSON.parse(localStorage.getItem("user")); const state = user ? { status: { loggedIn: true }, user } : { status: {}, user: null } const actions = { // register a user action register({ dispatch, commit }, user){ commit('registerRequest', user); accountService.register(user) .then((user) => { commit('registerSuccess', user); router.push('./login'); setTimeout(() => { // display success message after route change completes dispatch('alert/success', `Registration successful, follow the confirmation link at [${user.email}] to verify your account`, { root: true }); }) }).catch((error) => { commit('registerFailed', error); dispatch('alert/info', error, { root: true }); }); }, // Login user action login({ dispatch, commit }, { email, password }){ commit('loginRequest', { email }); accountService.login(email, password) .then((user) => { commit('loginSuccess', user); router.push('/'); }).catch((error) => { commit('loginFailed', error); dispatch('alert/error', error, { root: true }); }); }, // Logout user action logout({ commit }){ accountService.logout(); commit('logout'); router.push('./login'); }, // Verify email account verifyEmail({ commit }, token ){ commit('verifyEmailRequest'); accountService.verifyEmail(token) .then((data) => { commit('verifyEmailSuccess', data); }).catch((error) => { commit('verifyEmailFailed', error); }); }, // Forgot Password recovery action forgotPassword({ dispatch, commit }, email){ commit('forgotPasswordRequest'); accountService.forgotPassword(email) .then((user) => { commit('forgotPasswordSuccess', email); router.push('./login'); setTimeout(() => { // display success message after route change completes dispatch('alert/success', `Please, follow the link at [${user.email}] to reset your new password`, { root: true }); }); }).catch((error) => { commit('forgotPasswordFailed', error); dispatch('alert/error', error, { root: true }); }); }, // Verify email and token for reset password verifyResetToken({ dispatch, commit }, { email, token }){ accountService.verifyResetToken(email, token) .then(() => { // do nothing because verification returns ok response }).catch((error) => { router.push('./login'); setTimeout(() => { // display success message after route change completes dispatch('alert/warn', error, { root: true }); }); }); }, // Reset new password action resetPassword({ dispatch, commit }, { email, token, password }){ commit('resetPasswordRequest'); accountService.resetPassword(email, token, password) .then((data) => { commit('resetPasswordSuccess'); router.push('./login'); setTimeout(() => { // display success message after route change completes dispatch('alert/success', data, { root: true }); }); }).catch((error) => { commit('resetPasswordFailed'); dispatch('alert/error', error, { root: true }); }); } }; const mutations = { // Registration mutation logic registerRequest(state){ state.status = { registering: true }; }, registerSuccess(state){ state.status = {}; }, registerFailed(state){ state.status = {}; }, // Login mutation logic loginRequest(state, user){ state.status = { loggingIn: true }, state.user = user; }, loginSuccess(state, user){ state.status = { loggedIn: true }; state.user = user; }, loginFailed(state){ state.status = {}; state.user = null; }, // Logout mutation logic logout(state){ state.status = {}; state.user = null; }, // Verify email account mutation logic verifyEmailRequest(state){ state.status = { verifying: true }; }, verifyEmailSuccess(state, data){ state.status = { verified: true, data }; }, verifyEmailFailed(state, error){ state.status = { verificationFailed: true, error }; }, // Forgot Password mutation logic forgotPasswordRequest(state){ state.status = { requesting: true }; }, forgotPasswordSuccess(state){ state.status = {}; }, forgotPasswordFailed(state){ state.status = {}; }, // Reset Password mutation logic resetPasswordRequest(state){ state.status = { requesting: true }; }, resetPasswordSuccess(state){ state.status = {}; }, resetPasswordFailed(state){ state.status = {}; }, }; export const account = { namespaced: true, state, actions, mutations }<file_sep># Vue.js + Vuex User Registration and JWT Authentication Boilerplate App ## Project setup ``` npm install ``` ### Compiles and hot-reloads for development ``` npm run serve ``` ### Compiles and minifies for production ``` npm run build ``` ### Lints and fixes files ``` npm run lint ``` ### Backend Node.js API for this app See [Node.js + PostgreSQL with JWT Authentication API](https://github.com/joshuaoweipadei/Node.js-PostgreSQL-JWT-Authentication-API)<file_sep>import { handleResponse, authHeader } from '../_helpers'; import router from "../router"; export const accountService = { register, login, logout, verifyEmail, getAll, deleteUser, forgotPassword, verifyResetToken, resetPassword } function register(user){ const requestOptions = { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(user), } return fetch(`${process.env.VUE_APP_ROOT_API}/account/register`, requestOptions).then(handleResponse); } function login(email, password){ const requestOptions = { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ email, password }), } return fetch(`${process.env.VUE_APP_ROOT_API}/account/login`, requestOptions).then(handleResponse) .then((user) => { if(user.token){ localStorage.setItem("user", JSON.stringify(user)); } return user; }); } function logout() { // remove user from local storage to log user out localStorage.removeItem("user"); } function verifyEmail(token){ const requestOptions = { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ token }), } return fetch(`${process.env.VUE_APP_ROOT_API}/account/verify-email`, requestOptions).then(handleResponse); } function getAll(){ const requestOptions = { methdo: "GET", headers: {...authHeader()} } return fetch(`${process.env.VUE_APP_ROOT_API}/account/users`, requestOptions).then(handleResponse); } function deleteUser(id){ const requestOptions = { method: 'DELETE', headers: authHeader() }; return fetch(`${process.env.VUE_APP_ROOT_API}/account/${id}`, requestOptions).then(handleResponse) .then(() => { let user = JSON.parse(localStorage.getItem("user")); if(id === user.id){ logout(); router.push('./login'); } return id; }); } function forgotPassword(email){ const requestOptions = { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ email }), } return fetch(`${process.env.VUE_APP_ROOT_API}/account/forgot-password`, requestOptions).then(handleResponse); } function verifyResetToken(email, token){ const requestOptions = { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ email, token }), } return fetch(`${process.env.VUE_APP_ROOT_API}/account/verify-reset-password-email-token`, requestOptions).then(handleResponse); } function resetPassword(email, token, password){ const requestOptions = { method: "PUT", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ email, token, password }), } return fetch(`${process.env.VUE_APP_ROOT_API}/account/reset-password`, requestOptions).then(handleResponse); }<file_sep>import Vue from "vue"; import VueRouter from "vue-router"; import Home from "../views/Home.vue"; import Registration from "../views/Registration.vue"; import Login from "../views/Login.vue"; import ForgotPassword from "../views/ForgotPassword.vue"; import ResetPassword from "../views/ResetPassword.vue"; import VerifyEmail from "../views/VerifyEmail.vue"; import NotFound from "../views/NotFound.vue"; Vue.use(VueRouter); const routes = [ { path: "/", name: "Home", component: Home, meta: { requiresAuth: true } }, { path: "/register", name: "Registration", component: Registration, meta: { guest: true } }, { path: "/login", name: "Login", component: Login, meta: { guest: true } }, { path: "/forgot-password", name: "Forgot Password", component: ForgotPassword, meta: { guest: true } }, { path: "/reset-password", name: "Reset Password", component: ResetPassword, meta: { guest: true } }, { path: "/verify-email", name: "Email Verification", component: VerifyEmail, meta: { guest: true } }, { path: "*", name: "Not Found", component: NotFound, } ]; const router = new VueRouter({ mode: "history", base: process.env.BASE_URL, routes }); router.beforeEach((to, from, next) => { if(to.matched.some(record => record.meta.requiresAuth)){ if(localStorage.getItem("user") == null){ next({ path: "/login" }) } else{ next() } } else if(to.matched.some(record => record.meta.guest)){ if(localStorage.getItem("user") == null){ next() } else{ next("/") } } else{ next() } }) export default router;
778141c79e0e86e9bb3dcac669d3639c1de88a4c
[ "JavaScript", "Markdown" ]
4
JavaScript
fernandineho/Vue.js-Vuex-User-JWT-Authentication-Boilerplate-App
1a63aa0be72e73bf6f7b7d09c9d15ad7bbc79062
b76682afccea1b9f905ae9cb29243c2c01e69cbd
refs/heads/master
<file_sep><?php namespace PatrickRose\Invoices\Config; use PatrickRose\Invoices\Exceptions\UnknownConfigKeyException; /** * Base interface for configuration * * @package PatrickRose\Invoices */ interface ConfigInterface { /** * Whether the given key has been set * * @param string $key The key to check * @return bool True if set, false if not */ public function has(string $key) : bool; /** * Get the value of the given key * * @param string $key The key to get the value of * @return mixed The value of the key * @throws UnknownConfigKeyException If the config value is not set */ public function get(string $key); /** * Set the value of the given key to the given value * * @param string $key The key to set * @param mixed $value The value to set to */ public function set(string $key, $value) : void; /** * Get the value of the given key, returning the default if not set * * @param string $key The key to get the value of * @param mixed $default The default value * @return mixed The value of the key, or the default if not set */ public function getDefault(string $key, $default); } <file_sep><?php namespace PatrickRose\Invoices\Tests\Config; use PatrickRose\Invoices\Exceptions\UnknownConfigKeyException; use PatrickRose\Invoices\Config\ConfigInterface; use PHPUnit\Framework\TestCase; abstract class ConfigInterfaceTestCase extends TestCase { protected function setUp() { parent::setUp(); } public function testGet() { $config = $this->getConfigUnderTest([ 'existing-key' => 'some-value' ]); $this->assertEquals('some-value', $config->get('existing-key')); } /** * @expectedException \PatrickRose\Invoices\Exceptions\UnknownConfigKeyException */ public function testGetNonExistingKey() { $config = $this->getConfigUnderTest([]); $config->get('12345'); } public function testGetDefault() { $config = $this->getConfigUnderTest([ 'existing-key' => 'some-value', ]); $this->assertEquals('non-existing-key', $config->getDefault('non-existing-key', 'non-existing-key')); $this->assertEquals('some-value', $config->getDefault('existing-key', 'different')); } public function testHas() { $config = $this->getConfigUnderTest([ 'existing-key' => 'some-value', ]); $this->assertTrue($config->has('existing-key')); $this->assertFalse($config->has('non-existing-key')); } public function testSet() { $config = $this->getConfigUnderTest(); $this->assertFalse($config->has('key-to-set')); $config->set('key-to-set', 'value'); $this->assertTrue($config->has('key-to-set')); $this->assertEquals('value', $config->get('key-to-set')); } /** * Get the config implementation under test * * @param array $existingConfig The existing configuration * @return ConfigInterface */ abstract protected function getConfigUnderTest(array $existingConfig = []): ConfigInterface; } <file_sep><?php namespace PatrickRose\Invoices\Repositories; use PatrickRose\Invoices\Invoice; interface InvoiceRepositoryInterface { /** * Add an invoice to the repository * * @param Invoice $invoice The invoice the add * @return bool True if add was successful */ public function add(Invoice $invoice): bool; /** * Get all invoices from this repository * * @return Invoice[] */ public function getAll(): array; /** * Instantiate this repository based on the given * * @param array $config * @return InvoiceRepositoryInterface */ public static function instantiate(array $config): InvoiceRepositoryInterface; } <file_sep># Invoices - Core # The core classes for the invoice implementation <file_sep><?php namespace PatrickRose\Invoices; use Twig\TemplateWrapper; class Invoice { /** * @var string */ private $reference; /** * @var string */ private $payee; /** * @var string */ private $date; /** * @var array */ private $fees; /** * @var array */ private $expenses; /** * @var Twig_TemplateWrapper */ private $template; public function __construct( string $reference, string $payee, string $date, array $fees, array $expenses = [] ) { $this->reference = $reference; $this->payee = $payee; $this->date = $date; $this->fees = $fees; $this->expenses = $expenses; } public function getReference() { return $this->reference; } public function getTotalFees() { return array_sum($this->fees); } public function getExpenses() { return $this->expenses; } /** * @return string */ public function getPayee(): string { return $this->payee; } /** * @return string */ public function getDate(): string { return $this->date; } /** * @return array */ public function getFees(): array { return $this->fees; } public function toArray(): array { return [ 'reference' => $this->getReference(), 'payee' => $this->getPayee(), 'date' => $this->getDate(), 'fees' => $this->getFees(), 'expenses' => $this->getExpenses() ]; } } <file_sep><?php namespace PatrickRose\Invoices\Conversion; use PatrickRose\Invoices\Invoice; use PatrickRose\Invoices\MasterInvoice; /** * Interface for converting Invoices into PDFs */ interface ConverterInterface { /** * Convert an invoice into a new format * * @param Invoice $invoice The invoice to convert to a file * @param string $filePath The file path to store the invoice in * @return bool Whether the conversion was successful */ public function convertInvoice(Invoice $invoice, string $filePath): bool; /** * Convert a master invoice into a new form * * @param MasterInvoice $invoice The invoice to convert to a file * @param string $filePath The file path to store the invoice in * @return bool Whether the conversion was successful * @return string */ public function convertMasterInvoice(MasterInvoice $invoice, string $filePath): bool; /** * Check if this converter is available * * @return bool */ public static function isAvailable(): bool; /** * Instantiate a copy of this class with the given config * * @return ConverterInterface */ public static function instantiate($config): ConverterInterface; } <file_sep><?php namespace PatrickRose\Invoices\Exceptions; class RuntimeException extends \RuntimeException { } <file_sep><?php namespace PatrickRose\Invoices; class MasterInvoice { private $fees; private $expenses; private $template; public function addInvoice(Invoice $invoice) { $this->fees[$invoice->getReference()] = $invoice->getTotalFees(); $this->expenses[$invoice->getReference()] = $invoice->getExpenses(); } /** * @return array */ public function getFees() { return $this->fees; } /** * @return array */ public function getExpenses() { return $this->expenses; } } <file_sep><?php namespace PatrickRose\Invoices\Exceptions; class LockException extends RuntimeException { } <file_sep><?php namespace PatrickRose\Invoices\Tests\Conversion; use PatrickRose\Invoices\Conversion\ConverterInterface; use PHPUnit\Framework\TestCase; abstract class ConverterInterfaceTestCase extends TestCase { /** * @var ConverterInterface */ protected $converter; protected function setUp() { parent::setUp(); $this->converter = $this->getClassUnderTest(); if (!$this->converter::isAvailable()) { $this->markTestSkipped(get_class($this->converter) . ' is not available'); } } protected function tearDown() { $this->converter = null; parent::tearDown(); } abstract protected function getClassUnderTest(): ConverterInterface; } <file_sep><?php namespace PatrickRose\Invoices\Exceptions; class UnknownConfigKeyException extends RuntimeException { } <file_sep><?php namespace PatrickRose\Invoices\Tests\Repositories; use PatrickRose\Invoices\Invoice; use PatrickRose\Invoices\Repositories\InvoiceRepositoryInterface; use PHPUnit\Framework\TestCase; abstract class InvoiceRepositoryTestCase extends TestCase { public function testCanGetAllInvoices() { $invoices = [ new Invoice('1234', 'Test payee', 'Some date', ['fee' => 123], ['expense' => 123]), new Invoice('4321', 'Test payee', 'Some date', ['fee' => 123], ['expense' => 123]), ]; $repository = $this->getRepositoryUnderTest($invoices); $this->assertEquals($invoices, $repository->getAll()); } public function testCanAddANewInvoice() { $invoice = new Invoice('1234', 'Test payee', 'Some date', ['fee' => 123], ['expense' => 123]); $repository = $this->getRepositoryUnderTest(); $this->assertTrue($repository->add($invoice)); $this->assertEquals([$invoice], $repository->getAll()); } public function testCanAddANewInvoiceToAnExistingList() { $baseInvoice = new Invoice('1234-1234', 'Test payee', 'Some date', ['fee' => 123], ['expense' => 123]); $invoice = new Invoice('1234', 'Test payee', 'Some date', ['fee' => 123], ['expense' => 123]); $repository = $this->getRepositoryUnderTest([$baseInvoice]); $this->assertTrue($repository->add($invoice)); $this->assertEquals([$baseInvoice, $invoice], $repository->getAll()); } /** * @param Invoice[] $invoices * @return InvoiceRepositoryInterface */ abstract protected function getRepositoryUnderTest(array $invoices = []): InvoiceRepositoryInterface; public function testInstantiate() { $class = get_class($this->getRepositoryUnderTest([])); $returnedClass = $class::instantiate($this->getInstantiateConfiguration()); static::assertInstanceOf($class, $returnedClass, 'Did not get the correct class'); } /** * Get the instantiate configuration * * @see self::testInstantiate */ abstract protected function getInstantiateConfiguration(): array; }
8764006c442507057cad485bfd75320575d8b93b
[ "Markdown", "PHP" ]
12
PHP
patrickrose-invoices/core
dbe52dac197279329845345bdfcaf7f6fe192910
2383c737bb168e0074293d50e1f9b274f898acab
refs/heads/master
<repo_name>mz8023yt/python.demo<file_sep>/2018-05-19-factory-sesnor-value-process/data_process.py import os import sys import subprocess import time import csv def file_name(file_dir): i = 0 for root, dirs, files in os.walk(file_dir): return files def main(): files = file_name('D:\data') data = [] output_data = [] output = open("D:\\result.txt","w") i = 0 row = 0 for file in files: path = 'D:\data\%s' %file data.append(file.split('.')[0]) fd = open(path, "r") lines = fd.readlines() for str in lines: data.append(str.split(':')[0]) temp = str.split(':')[1] temp = temp.split('\n')[0] data.append(temp) for item in data: raw = i / 15; if((i%15) == 0): output_data.append([]) output_data[int(raw)].append(item) i = i + 1 num = len(output_data) with open('D:\\example.csv', 'w') as f: writer = csv.writer(f) for i in range(num): writer.writerow(output_data[i]) if __name__ == "__main__": main()<file_sep>/2018-05-19-factory-sesnor-value-process/readme.md ### 工厂校准数据处理脚本 工厂回来的数据居然是一个个 txt 格式的文本文件,很尴尬,一个一个看,不利于统计分析,要是可以整合成一张表就好了,因此这个脚本就应运而生了。 A306C842000001.txt 文件内容: ``` LsensorValue:2339 PsensorValue:243 Psensor3cmValue:287 Psensor5cmValue:252 GsensorXValue:-10580 GsensorYValue:-14473 GsensorZValue:30749 ``` ### 使用方法 1. 将 data 文件夹放到 D 盘目录下。 2. 执行数据处理脚本。 ``` C:\Users\wangbing>d: D:\>python data_process.py ```
dab23b061b2863c1cfd2b57a49db203904418a02
[ "Markdown", "Python" ]
2
Python
mz8023yt/python.demo
f4d26f55d7ee15d421bd5ae4b2899b494ceee117
cccf08aeb76c116bfc2dbd14cf74cb97cd3a818c
refs/heads/master
<repo_name>dave-a-fox/maze_gen<file_sep>/maze_runner.py from structures.stack.arraystack import ArrayStack from structures.list.linkedlist import LinkedList from maze import Maze from time import sleep import random import os if __name__ == '__main__': """ Uses Maze class and ArrayStack class and generates a randomized path """ # clear console screen clear = lambda: os.system('cls') # asks user for amount of rows, amount of columns, and the speed at which the maze will generate rows = input("How many rows will the maze contain? ") columns = input("How many columns will the maze contain? ") speed = input("How fast should the maze go? ") # initialize stack, list, and maze stack = ArrayStack() neighbors = LinkedList() maze = Maze(int(rows), int(columns)) # sets window size to appropriate length and width os.system('mode con: cols={} lines={}'.format(maze.columns * 4 + 2, maze.rows * 2 + 4)) # choose initial cell, mark visited, and push onto stack cursor = maze.cursor stack.push(cursor) while not stack.isEmpty(): neighbors.clear() # the current cell/cursor position maze.cursor = stack.pop() # if the cell in the direction of the currently selected cell exists and if it has not been visited if maze.up()[0] >= 0 and not maze.visited(maze.up()): neighbors.add(maze.up()) if maze.down()[0] < maze.rows and not maze.visited(maze.down()): neighbors.add(maze.down()) if maze.left()[1] >= 0 and not maze.visited(maze.left()): neighbors.add(maze.left()) if maze.right()[1] < maze.columns and not maze.visited(maze.right()): neighbors.add(maze.right()) if len(neighbors) > 0: # push the current cell back to the stack stack.push(maze.cursor) # select random neighbor neighbor = neighbors[random.randint(0, len(neighbors) - 1)] if maze.up() == neighbor: maze.move_up() elif maze.down() == neighbor: maze.move_down() elif maze.right() == neighbor: maze.move_right() elif maze.left() == neighbor: maze.move_left() stack.push(neighbor) # draw the current frame of the maze to the screen and pause for a fraction of a second sleep(.01 / float(speed)) clear() print(maze) # opens walls for each end of the maze maze.cells[0][0].ceil = "+ " maze.cells[maze.rows - 1][maze.columns - 1].floor = "+ +" maze.cells[maze.rows - 1][maze.columns - 1].center = " " clear() print(maze) input("\nMaze complete!") <file_sep>/maze.py class Maze(object): # Cell class to be populated into maze array class Cell(object): def __init__(self, ceil="+---", lwall="|", rwall="", floor="", center=" ? "): self.ceil = ceil self.lwall = lwall self.rwall = rwall self.floor = floor self.center = center def __init__(self, rows, columns): self.rows = rows self.columns = columns self.cells = [[self.Cell() for column in range(self.columns + 1)] for row in range(self.rows + 1)] self.cursor = [0, 0] self.build() # Sets [0, 0] as visited self.cells[self.cursor[0]][self.cursor[1]].center = " " def __str__(self): output = "" for row in range(self.rows): for line in range(3): if line == 0: for column in range(self.columns): output += self.cells[row][column].ceil output += "\n" elif line == 1: for column in range(self.columns): output += self.cells[row][column].lwall + self.cells[row][column].center \ + self.cells[row][column].rwall output += "\n" elif line == 2: for column in range(self.columns): output += self.cells[row][column].floor return output # Initializes cell matrix to include proper floors, ceilings, and right-walls def build(self): for row in range(self.rows): for column in range(self.columns): if column != self.columns - 1: if row == self.rows - 1: self.cells[row][column] = self.Cell(floor="+---") else: if row != self.rows - 1: self.cells[row][column] = self.Cell(ceil="+---+", rwall="|") else: self.cells[row][column] = self.Cell(ceil="+---+", floor="+---+", rwall="|") # Breaks the wall between the cursor's current position and the parameter cell's position # Note: Breaks the wall closest to the destination/parameter cell, and can break multiple walls def break_wall(self, cell_pos): try: # Break the ceiling of the cell below the cell at cell_pos # We can only break the ceilings because floors are strictly used for the bottom of the maze if cell_pos[0] < self.cursor[0]: self.cells[cell_pos[0] + 1][cell_pos[1]].ceil = "+ " if cell_pos[1] == self.columns - 1: self.cells[cell_pos[0] + 1][cell_pos[1]].ceil = "+ +" # Break the ceiling of the cell at cell_pos if cell_pos[0] > self.cursor[0]: self.cells[cell_pos[0]][cell_pos[1]].ceil = "+ " if cell_pos[1] == self.columns - 1: self.cells[cell_pos[0]][cell_pos[1]].ceil = "+ +" # Break the left wall of the cell to the right of the cell at cell_pos # We can only break left walls because right walls are strictly used for the rightmost side of the maze if cell_pos[1] < self.cursor[1]: self.cells[cell_pos[0]][cell_pos[1] + 1].lwall = " " # Break the left wall of the cell at cell_pos if cell_pos[1] > self.cursor[1]: self.cells[cell_pos[0]][cell_pos[1]].lwall = " " except TypeError: print("ERROR: Invalid coordinate given for break_wall function.") # Shifts the cursor to a new [x, y] coordinate position # Returns True if the cursor location has been changed and False otherwise def shift_cursor(self, new_pos): try: if self.shift_check(new_pos): # Check to make sure new_pos is not out of bounds self.cursor = new_pos self.cells[self.cursor[0]][self.cursor[1]].center = " " except ValueError: print("ERROR: Invalid coordinate given for shift_cursor function.") def shift_check(self, new_pos): if new_pos[0] < 0 or new_pos[0] > self.rows or new_pos[1] < 0 or new_pos[1] > self.columns: return False return True # Directional functions that return the coordinate position relative to the cursor def up(self): return [self.cursor[0] - 1, self.cursor[1]] def down(self): return [self.cursor[0] + 1, self.cursor[1]] def left(self): return [self.cursor[0], self.cursor[1] - 1] def right(self): return [self.cursor[0], self.cursor[1] + 1] # Convenience functions that break the wall in the chosen direction and shift the cursor without having to declare # each on separate lines def move_up(self): if self.shift_check(self.up()): self.break_wall(self.up()) self.shift_cursor(self.up()) def move_down(self): if self.shift_check(self.down()): self.break_wall(self.down()) self.shift_cursor(self.down()) def move_left(self): if self.shift_check(self.left()): self.break_wall(self.left()) self.shift_cursor(self.left()) def move_right(self): if self.shift_check(self.right()): self.break_wall(self.right()) self.shift_cursor(self.right()) # Returns true if the given cell position has been visited by the cursor and false otherwise def visited(self, cell_pos): if self.shift_check(cell_pos) and self.cells[cell_pos[0]][cell_pos[1]].center != " ? ": return True return False if __name__ == '__main__': newMaze = Maze(6, 8) newMaze.move_right() print(str(newMaze.cursor)) if newMaze.cells[-1][0] is not None: print("Cell exists at -1, 0") print(newMaze) print("\nHas cell [0, 0] been visited? " + str(newMaze.visited([0, 0]))) print("Has cell [5, 5] been visited? " + str(newMaze.visited([5, 5]))) <file_sep>/README.md # maze_gen This is a program that uses stack and linked list data structures to create a randomized maze. The user is prompted for a row and column size and a speed at which each step of the maze is displayed in seconds. The maze is generated step by step using an [iteration algorithm](https://en.wikipedia.org/wiki/Maze_generation_algorithm). The data structures used are by <NAME>.
b27d0d3cecdff5753a5df89a80bf48f4311ca16e
[ "Markdown", "Python" ]
3
Python
dave-a-fox/maze_gen
a69d119b6eef0f79d11032a78642365b3b2fa4f9
917cc01c363d19a3103968d11be57dc4cd413ee6
refs/heads/master
<file_sep>import javax.mail.MessagingException; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Scanner; public class Admin extends User implements SendingEmail { private Library lib; public Admin(String email, String password) { this.email = email; this.password = <PASSWORD>; lib = new Library(); } public Admin() { lib = new Library(); } public void addBook() throws IOException, MessagingException { Book book = getBook(); Path path = Paths.get(lib.getUSER_INFO_PATH()); Scanner scanner = new Scanner(path); boolean isClient = false; while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] elements = line.split("-|\\n"); String to = ""; for (String elem : elements) { if (elem.contains("@")) { to = elem; } if (elem.equals("false")) { isClient = true; } } if (isClient) sendEmail("<EMAIL>", to, "********", book.toString()); isClient = false; } lib.addBook(book); } public void read() throws IOException { lib.show(); } public Book searchFromFile() throws IOException { Book book = getBook(); return lib.searchFromFile(book); } public void delete() throws IOException { Book book = getBook(); lib.delete(book); } } <file_sep>import java.util.Scanner; public abstract class User { protected String email; protected String password; public String getEmail() { return email; } public String getPassword() { return password; } protected Book getBook(){ Scanner input = new Scanner(System.in);//TODO in func that returns Book String author = input.nextLine(); String name = input.nextLine(); return new Book(author, name); } } <file_sep>import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public interface SendingEmail { private void setProperties(Properties properties) { properties.setProperty("mail.transoprt.protocol", "smpt"); properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.auth", "true"); properties.setProperty("mail.smtp.host", "smtp.gmail.com"); properties.setProperty("mail.smtp.port", "587"); properties.setProperty("mail.smtp.user", "<EMAIL>"); } default void sendEmail(String from, String to, String password, String msg) throws MessagingException { Properties properties = new Properties(); setProperties(properties); Session mailSession = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("New book"); message.setText(msg); Transport.send(message, from, password); } }
329c2f34727c2ed9239db5b701a28769c559c79d
[ "Java" ]
3
Java
DeniskaRedisska/Libriary
58fcc4f0eb8f457bb38021c6137401c7e43c9649
169fcbe3f2dba5917b704753686051fbd062e3eb
refs/heads/master
<repo_name>kablanfatih/GitHubApi<file_sep>/src/component/ReposInfo.js import React, {Component} from 'react'; class ReposInfo extends Component { showRepoInfo(repos) { this.refs.repoDiv.innerHTML = ""; repos.forEach(repo => { this.refs.repoDiv.innerHTML += ` <div class="mb-2 card-body"> <div class="row"> <div class="col-md-2"> <a class="btn btn-danger" href="${repo.html_url}" target = "_blank" id = "repoName">${repo.name}</a> </div> <div class="col-md-6"> <button class="btn btn-secondary"> Starlar <span class="badge badge-light" id="repoStar">${repo.stargazers_count}</span> </button> <button class="btn btn-info"> Forklar <span class="badge badge-light" id ="repoFork">${repo.forks_count}</span> </button> </div> </div> </div>` }) } render() { const repoInfo = this.props.username; if (repoInfo !== undefined) { this.showRepoInfo(repoInfo) } return ( <div ref="repoDiv"> </div> ); } } export default ReposInfo;<file_sep>/src/component/UserInfo.js import React, {Component} from 'react'; import axios from "axios"; import ReposInfo from "./ReposInfo"; import companyPng from "../images/company.png"; import locationPng from "../images/location.png"; import mailPng from "../images/mail.png"; class UserInfo extends Component { state = { login: "", htmlUrl: "", avatarUrl: "", bio: "", public_repos: "", company: "", location: "", email: "", followers: "", following: "", error: false, isVisible: false }; getUser = async username => { const responseUser = await axios.get(`https://api.github.com/users/${username}`); const {login, html_url, avatar_url, bio, public_repos, company, location, email, followers, following} = responseUser.data; this.setState({ login, html_url, avatar_url, bio, public_repos, company, location, email, followers, following }); }; getRepoInfo = async username => { const repoInfos = await axios.get(`https://api.github.com/users/${username}/repos`); const repoInfosData = repoInfos.data; this.setState({repoInfosData}); }; validateForm = (username) => { return !(username === ""); }; async handleSubmit(e) { e.preventDefault(); const username = this.refs.username.value; if (!this.validateForm(username)) { this.setState({error: true}); setTimeout(() => { this.setState({ error: false }); }, 2000); return; } await this.getUser(username) .then(() => { this.setState({ isVisible: true }) }) .catch(() => alert("Lütfen Girdiğiniz Bilgileri Kontrol Ediniz.")); await this.getRepoInfo(username); } render() { const {login, html_url, avatar_url, bio, public_repos, company, location, email, followers, following, repoInfosData, error, isVisible} = this.state; return ( <div className="container"> <div className="search card card-body"> <h3>Github Kullanıcılarını Arayın</h3> <p className="lead"> Bir kullanıcı adı girin ve kullanıcının bilgilerine ulaşın! </p> { error ? <div className="alert alert-danger">Lütfen Kullanıcı Adını Giriniz</div> : null } <form onSubmit={e => this.handleSubmit(e)}> <input ref='username' type="text" name="username" className="form-control" placeholder="<NAME> adı"/> <br/> <button type="submit" className="btn btn-dark">Ara</button> </form> </div> {isVisible ? <div> <div className="card card-body mb-3"> <div className="row"> <div className="col-md-4"> <a href={html_url} target="_blank" rel="noopener noreferrer"> <img className="img-fluid mb-2" src={avatar_url} alt=""/> </a> <hr/> <div id="fullName"><strong>{login}</strong></div> <hr/> <div id="bio">{bio}</div> </div> <div className="col-md-8 pt-5"> <button className="btn btn-secondary"> Takipçi <span className="badge badge-light">{followers}</span> </button> <button className="btn btn-info"> Takip Edilen <span className="badge badge-light">{following}</span> </button> <button className="btn btn-danger"> Repolar <span className="badge badge-light">{public_repos}</span> </button> <hr/> <li className="list-group"/> <li className="list-group-item borderzero"> <img src={companyPng} width="30px" alt=""/> <span id="company">{company}</span> </li> <li className="list-group-item borderzero"> <img src={locationPng} width="30px" alt=""/> <span id="location">{location}</span> </li> <li className="list-group-item borderzero"> <img src={mailPng} width="30px" alt=""/> <span id="company">{email} </span> </li> </div> </div> </div> <h3>Repositoriler</h3> </div> : null} <ReposInfo username={repoInfosData}/> </div> ); } } export default UserInfo;
fdc5e5b81ddb42de79ed6ad9fbf1a5a43bb752e4
[ "JavaScript" ]
2
JavaScript
kablanfatih/GitHubApi
02b56f3b56af5743790c1c9565e5cc5b27476d03
6f33a2e0da334bc83673bc1414c0e599bd1d109b
refs/heads/master
<file_sep>#include "Framework.h" #include "Input.h" std::function<LRESULT(HWND, const uint&, const WPARAM&, const LPARAM&)> Input::MouseProc = nullptr; Input::Input(const std::shared_ptr<Context>& context) : ISubsystem(context) , mousePosition(0) , wheelStatus(0) , wheelOldStatus(0) , wheelMoveValue(0) { MouseProc = std::bind // 함수호출을 미리 정의해놓음 ( &Input::MsgProc, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4 // 메시지가 아직 없으므로 공간을 미리 받아서 가지고있음. ); EventSystem::Get().Subscribe(EventType::Event_Update, EVENT_HANDLER(Update)); } // 헤더파일에 써놓음 LRESULT Input::MsgProc(HWND handle, const uint & message, const WPARAM & wParam, const LPARAM & lParam) { if (message == WM_LBUTTONDOWN || message == WM_MOUSEMOVE) // 좌클릭 또는 마우스 이동시 { mousePosition.x = static_cast<float>(LOWORD(lParam)); mousePosition.y = static_cast<float>(HIWORD(lParam)); } if (message == WM_MOUSEWHEEL) // 휠이 굴러갈 시 { short tWheelValue = static_cast<short>(HIWORD(wParam)); wheelOldStatus.z = wheelStatus.z; wheelStatus.z += static_cast<float>(tWheelValue); } return TRUE; } const bool Input::Initialize() { // 배열 0으로 초기화 ZeroMemory(keyState, sizeof(keyState)); ZeroMemory(keyOldState, sizeof(keyOldState)); ZeroMemory(keyMap, sizeof(keyMap)); ZeroMemory(buttonStatus, sizeof(byte) * MAX_INPUT_MOUSE); ZeroMemory(buttonOldStatus, sizeof(byte) * MAX_INPUT_MOUSE); ZeroMemory(buttonMap, sizeof(byte) * MAX_INPUT_MOUSE); ZeroMemory(startDblClk, sizeof(ulong) * MAX_INPUT_MOUSE); ZeroMemory(buttonCount, sizeof(int) * MAX_INPUT_MOUSE); // 더블클릭 체크 시 첫클릭-두번째 클릭까지 제한시간 timeDblClk = GetDoubleClickTime(); startDblClk[0] = GetTickCount(); for (int i = 1; i < MAX_INPUT_MOUSE; i++) startDblClk[i] = startDblClk[0]; ulong tLine = 0; // 시스템 전역의 파라미터를 가져옴. 여기서는 휠굴림 감지에 사용 SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &tLine, 0); return true; } void Input::Update() { memcpy(keyOldState, keyState, sizeof(keyOldState)); ZeroMemory(keyState, sizeof(keyState)); ZeroMemory(keyMap, sizeof(keyMap)); GetKeyboardState(keyState); // 키보드 롱탭인지, 단순 입력인지 확인 for (ulong i = 0; i < MAX_INPUT_KEY; i++) { byte key = keyState[i] & 0x80; keyState[i] = key ? 1 : 0; int oldState = keyOldState[i]; int state = keyState[i]; if (oldState == 0 && state == 1) keyMap[i] = static_cast<uint>(KeyStatus::KEY_INPUT_STATUS_DOWN); // 이전 0, 현재 1 - KeyDown else if (oldState == 1 && state == 0) keyMap[i] = static_cast<uint>(KeyStatus::KEY_INPUT_STATUS_UP); // 이전 1, 현재 0 - KeyUp else if (oldState == 1 && state == 1) keyMap[i] = static_cast<uint>(KeyStatus::KEY_INPUT_STATUS_PRESS); // 이전 1, 현재 1 - KeyPress else keyMap[i] = static_cast<uint>(KeyStatus::KEY_INPUT_STATUS_NONE); // 이전 0, 현재 0 } // 255개의 값 모두 복사 (currentStatus to oldStatus) memcpy(buttonOldStatus, buttonStatus, sizeof(byte) * MAX_INPUT_MOUSE); //currentStatus 0으로 초기화. ZeroMemory(buttonStatus, sizeof(byte) * MAX_INPUT_MOUSE); ZeroMemory(buttonMap, sizeof(byte) * MAX_INPUT_MOUSE); // 눌린 상태라면 1, 안눌린 상태라면 0 buttonStatus[0] = GetAsyncKeyState(VK_LBUTTON) & 0x8000 ? 1 : 0; // 좌클릭 buttonStatus[1] = GetAsyncKeyState(VK_RBUTTON) & 0x8000 ? 1 : 0; // 우클릭 buttonStatus[2] = GetAsyncKeyState(VK_MBUTTON) & 0x8000 ? 1 : 0; // 휠클릭 // 드래그인지 클릭인지 확인 for (ulong i = 0; i < MAX_INPUT_MOUSE; i++) { int tOldStatus = buttonOldStatus[i]; int tStatus = buttonStatus[i]; if (tOldStatus == 0 && tStatus == 1) buttonMap[i] = static_cast<uint>(ButtonStatus::BUTTON_INPUT_STATUS_DOWN); // 이전 0, 현재 1 - KeyDown else if (tOldStatus == 1 && tStatus == 0) buttonMap[i] = static_cast<uint>(ButtonStatus::BUTTON_INPUT_STATUS_UP); // 이전 1, 현재 0 - KeyUp else if (tOldStatus == 1 && tStatus == 1) buttonMap[i] = static_cast<uint>(ButtonStatus::BUTTON_INPUT_STATUS_PRESS); // 이전 1, 현재 1 - KeyPress (Drag) else buttonMap[i] = static_cast<uint>(ButtonStatus::BUTTON_INPUT_STATUS_NONE); // 이전 0, 현재 0 } /*************************마우스 보여줌*************************/ POINT point = { 0, 0 }; GetCursorPos(&point); ScreenToClient(Settings::Get().GetWindowHandle(), &point); /**************************마우스이동***************************/ wheelOldStatus.x = wheelStatus.x; wheelOldStatus.y = wheelStatus.y; wheelStatus.x = static_cast<float>(point.x); wheelStatus.y = static_cast<float>(point.y); wheelMoveValue = wheelStatus - wheelOldStatus; // 마우스 이동 값 저장 wheelOldStatus.z = wheelStatus.z; // 휠굴림 값 /**************************더블클릭 체크************************/ ulong tButtonStatus = GetTickCount(); for (ulong i = 0; i < MAX_INPUT_MOUSE; i++) { if (buttonMap[i] == static_cast<uint>(ButtonStatus::BUTTON_INPUT_STATUS_DOWN)) // 버튼 DOWN이면 { if (buttonCount[i] == 1) { // 현재 누른 시간과 이전에 누른 시간의 차가 일정 시간을 넘길 경우 count 초기화 if ((tButtonStatus - startDblClk[i]) >= timeDblClk) buttonCount[i] = 0; } buttonCount[i]++; // 아니면 클릭횟수 1 증가 if (buttonCount[i] == 1) startDblClk[i] = tButtonStatus; } if (buttonMap[i] == static_cast<uint>(ButtonStatus::BUTTON_INPUT_STATUS_UP)) // 버튼 UP상태이면 { if (buttonCount[i] == 1) { if ((tButtonStatus - startDblClk[i]) >= timeDblClk) // 현재 누른 시간과 이전에 누른 시간의 차가 일정 시간을 넘길 경우 count 초기화 buttonCount[i] = 0; // DOWN에서 증가시켰으므로 UP에서는 증가시키진 않음. } else if (buttonCount[i] == 2) { if ((tButtonStatus - startDblClk[i]) <= timeDblClk) // 일정 시간 이내에 두번째 클릭이 이뤄졌을 경우 buttonMap[i] = static_cast<uint>(ButtonStatus::BUTTON_INPUT_STATUS_DBLCLK); // 얘 더블클릭(더블탭) 했다! buttonCount[i] = 0; // count 0으로 초기화. 하지 않으면 한번 더블클릭 하면 더이상 더블클릭 안됨. } }//if }//for(i) }
ac7bc4ccd71ac74ed658ec90720833c761ea01ae
[ "C++" ]
1
C++
punch5545/hw-20190411
360589676a7f09626d5f0a4bb36a348349ce567c
7efecd770eb02c3af9939134fd1c2fb9c0b60be1
refs/heads/master
<file_sep>package double_loop; /* 1 2 3 4 5 6 7 8 9 10 */ public class Assignment4 { private void method() { int k=1; for (int i = 1; i <= 4; i++) { for (int j = 1; j <= i; j++) { System.out.print(k+" "); k++; } System.out.println(); } } public static void main(String[] args) { Assignment4 a4 = new Assignment4(); a4.method(); } } <file_sep>package double_loop; /* * *** ***** ******* ********* */ public class Assignment5 { private void method() { int k = 0; for (int i = 5; i >= 1; i--, k++) { for (int j = 1; j <= 5+k; j++) { if (i<=j) { System.out.print("*"); } else { System.out.print(" "); } } System.out.println(); } } public static void main(String[] args) { Assignment5 a5 = new Assignment5(); a5.method(); } } <file_sep>package may9thAssignment; public class Assinment6 { private void fibo() { int a=0; int b=1; for (int c = 0; a < 50; ) { c= a+b; System.out.println(a); a=b; b=c; } } public static void main(String[] args) { Assinment6 a6 = new Assinment6(); a6.fibo(); } } <file_sep>package double_loop; /* ***** **** *** ** * */ public class Assignment2 { private void method() { for (int i = 5; i > 0; i--) { for (int j = i; j >0; j--) { System.out.print("*"); } System.out.println(); } } public static void main(String[] args) { Assignment2 a2 = new Assignment2(); a2.method(); } } <file_sep>package may9thAssignment; import java.util.Scanner; public class Assinment4 { private void armstrong() { Scanner s = new Scanner(System.in); System.out.println("Enter the number "); int digit1 = s.nextInt(); int digit = digit1; int original_number=digit1; int count = 0; while (digit !=0) { digit = digit/10; count++; } int result; for (result = 0; digit1 >0 ; digit1 = digit1/10) { int remainder = digit1%10; remainder = (int) Math.pow(remainder, count); result = result + remainder; } //System.out.println(result); if (original_number==result) { System.out.println( original_number + " is an Armstrong number"); } else { System.out.println( original_number + " is not an Armstrong number"); } } public static void main(String[] args) { Assinment4 a4 = new Assinment4(); a4.armstrong(); } } <file_sep>package may9thAssignment; import java.util.Scanner; public class Assinment1 { public void swap(int a, int b, int c) { c=a; a=b; b = c; System.out.println("New value in A = " +a); System.out.println("New value in B = " +b); } public static void main(String[] args) { Assinment1 a1 = new Assinment1(); Scanner s = new Scanner(System.in); System.out.println("Enter the Value of A"); int x =s.nextInt(); System.out.println("Enter the Value of B"); int y = s.nextInt(); a1.swap(x, y, 0); } }
c48fa13dcc661e7b5e9897085b76119a59d4669c
[ "Java" ]
6
Java
neeraj-it-26/Practice1
5627e74d92714a942f90748aa92d8bf18cd3ed27
a43b7354e98a23bef50bf78a35597d20651aadc8
refs/heads/master
<repo_name>15760464098/demo<file_sep>/demo.sh mkdir new cd new touch new.txt echo welcome to banyuan>new.txt cd .. mkdir newother cd newother mkdir sub cd .. cp new/new.txt newother/sub mv new/new.txt new/new1.txt mv newother/sub new2 rm -r new*<file_sep>/markdown.md # 一级标题 ## 二级标题 *斜体文字* **加粗文字** ***粗斜体*** ~~删除线文字~~ >单行代码引用 下标:H<sub>2</sub>O 上标:n<sup>2</sup> <br> ## 换行 这里是第一行 <br> 这里是第二行 ## 有序列表 1. 衣服 2. 裤子 3. 鞋子 ## 无序列表 - 衣服 - 裤子 - 鞋子 ## 多层级列表 -衣服 -大衣 -加绒 -加厚 -衬衣 -裤子 -牛仔裤 -西裤 -鞋子 ## 表格 |姓名(左对齐)|职业(居中)|年龄(右对齐)| |:--- |:--: |---: | |张三 |屠夫 |28 | |李四 |马夫 |28 | |王二 |车夫 |28 | <file_sep>/practice.sh mkdir example mv ex01.c example cd example mv ex01.c example.c cd .. mkdir practice mv ex02.c practice cd practice mv ex02 practice.c cd .. rm -rf ex03.c touch README.md vi README.md ## example/example.c 判断是奇数还是偶数 ## practice/practice.c 比较两个数大小
4b778f6fd70f4918922e9d9e6b0c98b3be6c6d47
[ "Markdown", "Shell" ]
3
Shell
15760464098/demo
44efe3b57f6d3bd2bfd9a02c9ec403c362b08684
730c3875cc56ab145fda41c75f383e63107f04a0