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># /etc/bash.bashrc
#
# This file is sourced by all *interactive* bash shells on startup,
# including some apparently interactive shells such as scp and rcp
# that can't tolerate any output. So make sure this doesn't display
# anything or bad things will happen !
# Test for an interactive shell. There is no need to set anything
# past this point for scp and rcp, and it's important to refrain from
# outputting anything in those cases.
if [[ $- != *i* ]] ; then
# Shell is non-interactive. Be done now!
return
fi
# Bash won't get SIGWINCH if another process is in the foreground.
# Enable checkwinsize so that bash will check the terminal size when
# it regains control. #65623
# http://cnswww.cns.cwru.edu/~chet/bash/FAQ (E11)
shopt -s checkwinsize
# Enable history appending instead of overwriting. #139609
shopt -s histappend
use_color=false
# Set colorful PS1 only on colorful terminals.
# dircolors --print-database uses its own built-in database
# instead of using /etc/DIR_COLORS. Try to use the external file
# first to take advantage of user additions. Use internal bash
# globbing instead of external grep binary.
safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
match_lhs=""
[[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
[[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
[[ -z ${match_lhs} ]] \
&& type -P dircolors >/dev/null \
&& match_lhs=$(dircolors --print-database)
[[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
if ${use_color} ; then
# Enable colors for ls, etc. Prefer ~/.dir_colors #64489
if type -P dircolors >/dev/null ; then
if [[ -f ~/.dir_colors ]] ; then
eval $(dircolors -b ~/.dir_colors)
elif [[ -f /etc/DIR_COLORS ]] ; then
eval $(dircolors -b /etc/DIR_COLORS)
fi
fi
if [[ ${EUID} == 0 ]] ; then
PS1='\[\033[01;31m\]\h\[\033[01;34m\] \W \$\[\033[00m\] '
else
PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \W \$\[\033[00m\] '
fi
alias ls='ls --color=auto'
alias grep='grep --colour=auto'
else
if [[ ${EUID} == 0 ]] ; then
# show root@ when we don't have colors
PS1='\u@\h \W \$ '
else
PS1='\u@\h \w \$ '
fi
fi
# Try to keep environment pollution down, EPA loves us.
unset use_color safe_term match_lhs
# Set up the default editor
export EDITOR=emacs
# Set up bashmarks (https://github.com/twerth/bashmarks)
# source /usr/local/bin/bashmarks.sh
# ---------------------- Configure ssh-agent ---------------------------
source ~/.keychain/$HOSTNAME-sh
# ------------------- Configure xterm transparency ---------------------
[ -n "$XTERM_VERSION" ] && transset-df -a 0.6 >/dev/null
# -------------------------- Fix up $PATH ------------------------------
# Remove path to MKS make
oldpath=$PATH
rmpath=":/cygdrive/c/MKS/mksnt"
PATH=${oldpath//"$rmpath"/}
# Fix paths for Octave
oldpath=$PATH
addpath="/usr/lib/lapack"
PATH="$oldpath"":$addpath"
# Add path for poole (static websites)
oldpath=$PATH
addpath="/usr/share/obensonne-poole-625d57a5d07a"
PATH="$oldpath"":$addpath"
# Add path for evince
oldpath=$PATH
addpath="/cygdrive/c/Program Files (x86)/Evince-2.32.0.145/bin"
PATH="$oldpath"":$addpath"
# Add path for WinAVR
oldpath=$PATH
addpath="/cygdrive/c/WinAVR-20100110/bin"
PATH="$oldpath"":$addpath"
# Increase priority of /usr/bin
oldpath=$PATH
rmpath=":/usr/bin"
PATH=${oldpath//"$rmpath"/}
oldpath=$PATH
PATH="$rmpath"":""$oldpath"
# Add /usr/local/bin
oldpath=$PATH
newpath=":/usr/local/bin"
PATH="$oldpath""$newpath"
# Increase priority of Windows Python
oldpath=$PATH
rmpath="/cygdrive/c/Python27"
PATH=${oldpath//":$rmpath"/}
oldpath=$PATH
PATH=":$rmpath""$oldpath"
# Add windows python scripts path
oldpath=$PATH
addpath="/cygdrive/c/Python27/Scripts"
PATH=":$addpath""$oldpath"
# Add inkscape path
oldpath=$PATH
addpath="/cygdrive/c/Program Files (x86)/Inkscape"
PATH=":$addpath""$oldpath"
# Add path for dotfiles
oldpath=$PATH
addpath=$HOME/.dotfiles/bin
PATH="$oldpath"":$addpath"
# Set DISPLAY
export DISPLAY=:0
<file_sep># To the extent possible under law, the author(s) have dedicated all
# copyright and related and neighboring rights to this software to the
# public domain worldwide. This software is distributed without any warranty.
# You should have received a copy of the CC0 Public Domain Dedication along
# with this software.
# If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
# base-files version 4.1-1
# ~/.bash_profile: executed by bash(1) for login shells.
# The latest version as installed by the Cygwin Setup program can
# always be found at /etc/defaults/etc/skel/.bash_profile
# Modifying /etc/skel/.bash_profile directly will prevent
# setup from updating it.
# The copy in your home directory (~/.bash_profile) is yours, please
# feel free to customise it to create a shell
# environment to your liking. If you feel a change
# would be benifitial to all, please feel free to send
# a patch to the cygwin mailing list.
# User dependent .bash_profile file
# Check to see if ssh-agent is already running
if [ -z "$(pgrep ssh-agent)" ]
then
echo "Did not find ssh-agent"
# keychain --stop others ~/.ssh/id_rsa
keychain ~/.ssh/id_rsa
else
echo "Found ssh-agent"
source ~/.keychain/$HOSTNAME-sh
fi
# source the users bashrc if it exists
if [ -f "${HOME}/.bashrc" ] ; then
source "${HOME}/.bashrc"
fi
| f0dc42f9fb44b8fb859587326bf6262481c20381 | [
"Shell"
] | 2 | Shell | johnpeck/dotfiles | d51ff658783ad24efa152a4ec701246100c07129 | 2412aeb42bad7e65a4071bcae1d43d25d0c34456 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MatrixVerifyer;
namespace Matrix
{
partial class Program
{
static void Main(string[] args)
{
/*
* Där finns tester tillgängliga genom att skriva
* MatrixChecker.CheckAddition
* MatrixChecker.CheckMultiplication
* MatrixChecker.CheckRotationMatrix
*
* Observera att testerna inte är noga testade.
*
* De tar emot argument enligt följande standard:
* CheckAddition tar emot alla Matris-värden 00, 01, 10, 11 för matris A
* och alla Matris-värden 00, 01, 10, 11 för matris B, och den sista är
* då det uträknade resultatet av A + B, som då är en matris 00, 01, 10, 11
*
* CheckMultiplication liknar CheckAddition, den tar emot tre matriser,
* A, B och sedan resultatet av A * B. Sen kommer den att jämföra och se
* ifall matrisen har blivit rätt
*
* CheckRotationMatrix tar emot antalet radianer du roterat en matris av,
* och sedan en rotationsmatris som du har skapat. Den jämför sedan värden
* för att se ifall matriserna stämmer överens.
*/
/*
* Där finns ett inbyggt verktyg för att rita ut matriser i två format.
* Den första tar emot alla matrisvärden, 00, 01, 10, 11 och den andra
* tar emot en float[,] (en float 2D-array) och skriver sedan ut matrisen
* formaterat, och endast med 2 decimaler.
*/
// De fyra första siffrorna = Matris A, de nästa fyra siffrorna = Matris B, de sista fyra siffrorna = resultatet av A + B
// Exempel: MatrixChecker.CheckAddition(1, 2, 3, 4, 1, 2, 3, 4, 2, 4, 6, 8);
// De fyra första siffrorna = Matris A, de nästa fyra siffrorna = Matris B, de sista fyra siffrorna = resultatet av A * B
// Exempel: MatrixChecker.CheckMultiplication(1, 2, 3, 4, 1, 2, 3, 4, 7, 10, 15, 22);
// Byt ut detta anropet med dina matrisvärden, så kommer programmet att rita ut dem istället :)
float a00=1, a01=2, a10=3, a11=4, b00=5, b01=6, b10=7, b11=8, c00 = a00 + b00, c01 = a01 + b01, c10 = a10 + b10, c11 = a11 + b11;
Draw2x2Matrix(a00, a01, a10, a11);
Console.WriteLine("\n+");
Draw2x2Matrix(b00, b01, b10, b11);
Console.WriteLine("\n=");
Draw2x2Matrix(c00, c01, c10, c11);
Console.WriteLine();
MatrixChecker.CheckAddition(a00, a01, a10, a11, b00, b01, b10, b11, c00, c01, c10, c11);
//
float radians = 3.14f;
double dm00 = radians;
double dm01 = radians;
dm00 = Math.Cos(dm00);
dm01 = Math.Sin(dm01);
float m00 = (float)dm00;
float m01 = (float)dm01;
float m10 = (float)-dm01;
float m11 = (float)dm00;
Draw2x2Matrix(m00, m01, m10, m11);
Console.WriteLine();
MatrixChecker.CheckRotationMatrix(radians, m00, m01, m10, m11);
//
c00 = a00 * b00 + a01 * b10; c01 = a00 * b01 + a01 * b11; c10 = a10 * b00 + a11 * b10; c11 = a10 * b01 + a11 * b11;
Draw2x2Matrix(a00, a01, a10, a11);
Console.WriteLine("\n*");
Draw2x2Matrix(b00, b01, b10, b11);
Console.WriteLine("\n=");
Draw2x2Matrix(c00, c01, c10, c11);
Console.WriteLine();
MatrixChecker.CheckAddition(a00, a01, a10, a11, b00, b01, b10, b11, c00, c01, c10, c11);
//
Console.WriteLine("set your own matris");
string sa00, sa01, sa10, sa11, sb00, sb01, sb10, sb11;
sa00 = Console.ReadLine(); sa01 = Console.ReadLine(); sa10 = Console.ReadLine(); sa11 = Console.ReadLine(); sb00 = Console.ReadLine(); sb01 = Console.ReadLine(); sb10 = Console.ReadLine(); sb11 = Console.ReadLine();
a00 = float.Parse(sa00); a01 = float.Parse(sa01); a10 = float.Parse(sa10); a11 = float.Parse(sa11); b00 = float.Parse(sb00); b01 = float.Parse(sb01); b10 = float.Parse(sb10); b11 = float.Parse(sb11);
c00 = a00 * b00 + a01 * b10; c01 = a00 * b01 + a01 * b11; c10 = a10 * b00 + a11 * b10; c11 = a10 * b01 + a11 * b11;
Draw2x2Matrix(a00, a01, a10, a11);
Console.WriteLine("\n*");
Draw2x2Matrix(b00, b01, b10, b11);
Console.WriteLine("\n=");
Draw2x2Matrix(c00, c01, c10, c11);
Console.WriteLine();
MatrixChecker.CheckAddition(a00, a01, a10, a11, b00, b01, b10, b11, c00, c01, c10, c11);
Console.ReadKey();
}
}
}
| 9a0f93d8a9bfb2b72f8a63ae53db795e50c17838 | [
"C#"
] | 1 | C# | Daniel1316/matris_profildag | e0f82875e9c8f1b7cf168fd16dea66da89f3957e | 307e6b2d7cb70aae9dee5f775bd1df94d0be0a1e |
refs/heads/main | <repo_name>JerryYINJIATENG/Coordinated-train-timetabling-Models-Construction-Test-Instance<file_sep>/Test2.cpp
// CPLEX code and Decomposition approaches
// By <NAME> at <NAME>
#include "stdafx.h"
#include <stdlib.h>
#include "CSVParser.h"
#include "network.h"
#include <stdio.h>
#include <iostream>
#include <ilcplex/ilocplex.h>
#include <cstdlib>
#include <process.h>
#include <math.h>
#include <cmath>
#include <time.h>
#include <ctime>
#include <numeric>
#include <algorithm> // std::max
typedef IloArray<IloNumVarArray> NumVarMatrix;
typedef IloArray<NumVarMatrix> NumVar3Matrix;
typedef IloArray<NumVar3Matrix> NumVar4Matrix;
ILOSTLBEGIN
#define _MAX_TIME 300
#define _MAX_PATH 100
#define TRAIN_CAPACITY 3000
#define _MAX_SERVICE 1000
#define number_of_lines 2
NetworkForSP* g_pNetworkForSP = NULL;
std::vector<CNode> g_node_vector;
std::vector<CLink> g_link_vector;
std::vector<CPath> g_path_vector;
std::vector<timetable> planned_timetable;
std::vector<train> Trains;
std::map<int, int> g_internal_node_seq_no_map;
std::map<int, CLink*> g_pLink_map; // link seq no
std::map<int, vector<float>> g_path_link_volume_mapping;
std::map<int, vector<float>> g_path_link_cost_mapping;
///////////////////////////// Parameters
// Construct the space time network by connected graph
// Use CPLEX TO SOLVE THE ORIGINAL MODEL
// Original subproblem: MIP¡¢
float g_demand_array[_MAX_ZONE][_MAX_ZONE][_MAX_TIME] = { 0.0 };
float g_demand_waiting[_MAX_ZONE][2][_MAX_TIME] = { 0.0 }; // From Line a to Line b
float g_demand_array_line_arriving[_MAX_ZONE][2][_MAX_TIME] = { 0.0 };
float g_demand_path_arriving[_MAX_PATH][_MAX_TIME] = { 0.0 };
float g_demand_path_current[_MAX_PATH][_MAX_TIME] = { 0.0 };
float g_boarding[_MAX_ZONE][_MAX_ZONE] = { 0,0 };
float cplex_boarding[_MAX_PATH][_MAX_TIME] = { 0.0 };
// float timetable[_MAX_ZONE][_MAX_ZONE][_MAX_TIME] = { 0.0 };
float r_vehicle_data[_MAX_SERVICE][_MAX_ZONE][_MAX_TIME]; // vehicle_id & destination & time
float r_station_data[_MAX_ZONE][_MAX_ZONE][_MAX_TIME]; // station_id & destination & time
// Small-case
int g_number_of_nodes = 0;
int g_number_of_links = 0; // initialize the counter to 0
int g_number_of_services = 2;
int number_of_transfer_paths = 2;
int h_min = 5;
int t_cycle = 44; // 4*9+8*1
int rolling_stock[number_of_lines] = { 7,6 };
clock_t startTime, endTime;
// LVNS parameters
// 1 Creat the struct of solutions.
// (1) Best_solution: the best solution until current iteration
// (2) solution_pool: vecotr of serached solutions
// (3) tem_solution: a temporal solution
// (4) current_solution
typedef struct Solution
{
int x_lt[number_of_lines][_MAX_TIME];
float cost;
}SOLUTION;
SOLUTION best_solution;
vector<Solution> solution_pool;
SOLUTION current_solution;
vector<Solution> neighbor_solution;
int destroy_operator = 4;
int samples_generated = 30;
int repair_operator = 2;
int ExchangeOperator = 0;
// int right_move_length[number_of_lines] = { 1,1 };
int right_move_length[number_of_lines] = { 1,1 };
float linear_rate(int t)
{
float rate;
if (t<_MAX_TIME / 2)
{
rate = 4.0 / (double)_MAX_TIME*t;
}
else
{
rate = -4.0 / (double)_MAX_TIME*t + 4.0;
}
return rate;
}
ILOMIPINFOCALLBACK5(boundlimitCallback,
IloCplex, cplex,
IloBool, aborted,
IloNum, boundBest,
IloNum, timeLimit,
IloNum, acceptableGap)
{
if (!aborted && hasIncumbent()) {
IloNum boundBest = cplex.getBestObjValue();
//IloNum timeUsed = cplex.getCplexTime() - timeStart;
if (boundBest>=best_solution.cost) {
getEnv().out()<< "Good enough solution"<<endl;
aborted = IloTrue;
abort();
}
}
}
void g_ReadInputData(void)
{
int internal_node_seq_no = 0;
double x, y;
// step 1: read node file
CCSVParser parser;
if (parser.OpenCSVFile("input_node.csv", true))
{
std::map<int, int> node_id_map;
while (parser.ReadRecord()) // if this line contains [] mark, then we will also read field headers.
{
string name;
int node_type;
int node_id;
if (parser.GetValueByFieldName("node_id", node_id) == false)
continue;
if (g_internal_node_seq_no_map.find(node_id) != g_internal_node_seq_no_map.end())
{
continue; //has been defined
}
g_internal_node_seq_no_map[node_id] = internal_node_seq_no;
parser.GetValueByFieldName("x", x, false);
parser.GetValueByFieldName("y", y, false);
CNode node; // create a node object
node.node_id = node_id;
node.node_seq_no = internal_node_seq_no;
parser.GetValueByFieldName("zone_id", node.zone_id);
//g_zoneid_to_zone_seq_no_mapping[212] = 212;
node.x = x;
node.y = y;
internal_node_seq_no++;
g_node_vector.push_back(node); // push it to the global node vector
g_number_of_nodes++;
if (g_number_of_nodes % 1000 == 0)
cout << "reading " << g_number_of_nodes << " nodes.. " << endl;
}
cout << "number of nodes = " << g_number_of_nodes << endl;
parser.CloseCSVFile();
}
// step 2: read link file
CCSVParser parser_link;
if (parser_link.OpenCSVFile("input_link.csv", true))
{
while (parser_link.ReadRecord()) // if this line contains [] mark, then we will also read field headers.
{
int from_node_id = 0;
int to_node_id = 0;
if (parser_link.GetValueByFieldName("from_node_id", from_node_id) == false)
continue;
if (parser_link.GetValueByFieldName("to_node_id", to_node_id) == false)
continue;
// add the to node id into the outbound (adjacent) node list
// Test Jiateng cout << "Test here " << from_node_id<< endl;
int internal_from_node_seq_no = g_internal_node_seq_no_map[from_node_id]; // map external node number to internal node seq no.
int internal_to_node_seq_no = g_internal_node_seq_no_map[to_node_id];
// Test Jiateng cout << "Test here: after transform " << internal_from_node_seq_no << endl;
CLink link; // create a link object
link.from_node_seq_no = internal_from_node_seq_no;
link.to_node_seq_no = internal_to_node_seq_no;
link.link_seq_no = g_number_of_links;
link.to_node_seq_no = internal_to_node_seq_no;
parser_link.GetValueByFieldName("link_type", link.type);
float length = 1.0; // km or mile
float speed_limit = 1.0;
parser_link.GetValueByFieldName("length", length);
parser_link.GetValueByFieldName("speed_limit", speed_limit);
parser_link.GetValueByFieldName("BPR_alpha_term", link.BRP_alpha);
parser_link.GetValueByFieldName("BPR_beta_term", link.BRP_beta);
int number_of_lanes = 1;
float lane_cap = 1000;
parser_link.GetValueByFieldName("number_of_lanes", number_of_lanes);
parser_link.GetValueByFieldName("lane_cap", lane_cap);
//link.m_OutflowNumLanes = number_of_lanes;//visum lane_cap is actually link_cap
//link.link_capacity = lane_cap* number_of_lanes; //not for visum
link.link_capacity = lane_cap;
link.free_flow_travel_time_in_min = length / speed_limit * 60.0;
link.length = length;
link.cost = length / speed_limit * 60;
// min // calculate link cost based length and speed limit // later we should also read link_capacity, calculate delay
g_node_vector[internal_from_node_seq_no].m_outgoing_link_vector.push_back(link); // add this link to the corresponding node as part of outgoing node/link
g_node_vector[internal_to_node_seq_no].m_incoming_link_seq_no_vector.push_back(link.link_seq_no); // add this link to the corresponding node as part of outgoing node/link
g_link_vector.push_back(link);
g_pLink_map[link.link_seq_no] = &(g_link_vector[g_link_vector.size() - 1]); // record the pointer to this link according to its link_seq_no
g_number_of_links++;
if (g_number_of_links % 10000 == 0)
cout << "reading " << g_number_of_links << " links.. " << endl;
}
}
// we now know the number of links
cout << "number of links = " << g_number_of_links << endl;
parser_link.CloseCSVFile();
// step 3: read demand file
CCSVParser parser_demand;
if (parser_demand.OpenCSVFile("input_demand.csv", true))
{
while (parser_demand.ReadRecord())
{
int from_zone_id = 0;
int to_zone_id = 0;
int time = 0;
if (parser_demand.GetValueByFieldName("from_zone_id", from_zone_id) == false)
continue;
if (parser_demand.GetValueByFieldName("to_zone_id", to_zone_id) == false)
continue;
if (parser_demand.GetValueByFieldName("time", time) == false)
continue;
float number_of_passengers = 0.0;
int origin_demand = g_internal_node_seq_no_map[from_zone_id];
int destin_demand = g_internal_node_seq_no_map[to_zone_id];
parser_demand.GetValueByFieldName("number_of_passengers", number_of_passengers);
g_demand_array[origin_demand][destin_demand][time] = number_of_passengers;
}
}
// None transfer paths
for (int l = 0; l<2; l++)
{
for (int i = 0; i<_MAX_ZONE; i++)
{
for (int j = 0; j<_MAX_ZONE; j++)
{
if ((i<_MAX_ZONE / 2 && j<_MAX_ZONE / 2 && i<j) || (i >= _MAX_ZONE / 2 && j >= _MAX_ZONE / 2 && i<j))
{
CPath path;
path.column_node_vector.push_back(i);
path.column_node_line_vector.push_back(l);
path.column_node_vector.push_back(j);
path.column_node_line_vector.push_back(l);
g_path_vector.push_back(path);
}
}
}
}
// Path 1: 1(0) --> 1(1)
// Path 2: 0(0) --> 3(1)
for (int i = 0; i<2; i++)
{
if (i == 0)
{
CPath path;
// One transfer has eight feasible paths
path.column_node_vector.push_back(1);
path.column_node_line_vector.push_back(0);
path.column_node_vector.push_back(2);
path.column_node_line_vector.push_back(0);
path.column_node_vector.push_back(1);
path.column_node_line_vector.push_back(1);
path.column_node_vector.push_back(3);
path.column_node_line_vector.push_back(1);
g_path_vector.push_back(path);
}
else
{
CPath path;
path.column_node_vector.push_back(0);
path.column_node_line_vector.push_back(0);
path.column_node_vector.push_back(2);
path.column_node_line_vector.push_back(0);
path.column_node_vector.push_back(1);
path.column_node_line_vector.push_back(1);
path.column_node_vector.push_back(3);
path.column_node_line_vector.push_back(1);
g_path_vector.push_back(path);
}
}
}
void passenger_demand_initilization(void)
{
// define g_demand_path_arriving
for (int t = 0; t<_MAX_TIME - 20; t++)
{
for (int p = 0; p<g_path_vector.size(); p++)
{
g_demand_path_arriving[p][t] = (int)20 * linear_rate(t);
if (g_path_vector[p].column_node_vector[0]>_MAX_ZONE / 2 - 1)
{
if (t<20)
{
g_demand_path_arriving[p][t] = g_demand_path_arriving[p][t] = (int)g_demand_path_arriving[p][t] / 6;
}
else
{
g_demand_path_arriving[p][t] = (int)g_demand_path_arriving[p][t] / 2;
}
}
if (g_path_vector[p].column_node_line_vector[0] == 0)
{
g_demand_path_arriving[p][t] = (int)g_demand_path_arriving[p][t]*4/5;
}
if (p == 40)
{
g_demand_path_arriving[p][t] = (int)g_demand_path_arriving[p][t] * 2;
}
if (p == 41)
{
g_demand_path_arriving[p][t] = (int)g_demand_path_arriving[p][t] * 2;
}
//g_demand_path_arriving[g_path_vector.size()-1][t]=50;
g_demand_array_line_arriving[g_path_vector[p].column_node_vector[0]][g_path_vector[p].column_node_line_vector[0]][t] += g_demand_path_arriving[p][t];
}
}
float total_demand = 0;
for (int p = 0; p<g_path_vector.size(); p++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
total_demand += g_demand_path_arriving[p][t];
g_demand_path_current[p][t] = 0;
for (int tau = 0; tau <= t; tau++)
{
g_demand_path_current[p][t] += g_demand_path_arriving[p][tau];
}
}
}
cout << "Test the total demand = " << total_demand << endl;
}
void new_cplex_model(void)
{
int t_dwell = 1;
int t_running = 4;
int t_transfer = 2;
int t_r[2] = {0};
for (int i = 0; i<number_of_transfer_paths; i++)
{
int p_order = g_path_vector.size() - number_of_transfer_paths + i;
if (g_path_vector[p_order].column_node_vector.size() <= 2)
{
cout << "Error happens" << endl;
abort();
}
else
{
int segment_traveled = 0;
int station_dwelled = 0;
segment_traveled = g_path_vector[p_order].column_node_vector[1] - g_path_vector[p_order].column_node_vector[0];
station_dwelled = segment_traveled - 1;
t_r[i] = t_transfer + segment_traveled*t_running + t_dwell*station_dwelled;
}
}
// for (int i = 0; i<number_of_transfer_paths; i++)
// {
// cout << "Travelling time of path " << i + g_path_vector.size() - number_of_transfer_paths << " = " << t_r[i] << endl;
// }
// Define variables
IloEnv env;
IloModel model(env);
NumVarMatrix x_lt(env, 2);
for (int i = 0; i<2; i++)
{
x_lt[i] = IloNumVarArray(env, _MAX_TIME);
for (int t = 0; t<_MAX_TIME; t++)
{
x_lt[i][t] = IloNumVar(env, 0.0, 1.0, ILOINT);
}
}
NumVar3Matrix n_lit(env, 2);
for (int i = 0; i<2; i++)
{
n_lit[i] = NumVarMatrix(env, _MAX_ZONE);
for (int j = 0; j<_MAX_ZONE; j++)
{
n_lit[i][j] = IloNumVarArray(env, _MAX_TIME);
for (int t = 0; t<_MAX_TIME; t++)
{
n_lit[i][j][t] = IloNumVar(env, 0, IloInfinity, ILOFLOAT);
}
}
}
NumVarMatrix p_pt(env, g_path_vector.size());
for (int i = 0; i<g_path_vector.size(); i++)
{
p_pt[i] = IloNumVarArray(env, _MAX_TIME);
for (int t = 0; t<_MAX_TIME; t++)
{
p_pt[i][t] = IloNumVar(env, 0, IloInfinity, ILOFLOAT);
}
}
NumVarMatrix transfer_boarding(env, 2);
for (int i = 0; i<number_of_transfer_paths; i++)
{
transfer_boarding[i] = IloNumVarArray(env, _MAX_TIME);
for (int t = 0; t<_MAX_TIME; t++)
{
transfer_boarding[i][t] = IloNumVar(env, 0, IloInfinity, ILOFLOAT);
}
}
IloNumVar max_waiting(env, 0, IloInfinity, ILOFLOAT);
IloRangeArray constraints(env);
// Add constriants
if (ExchangeOperator == 1)
{
for (int i = 0; i<1; i++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
constraints.add(x_lt[i][t] - best_solution.x_lt[i][t] == 0);
}
}
}
else if (ExchangeOperator == 2)
{
for (int i = 1; i<2; i++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
constraints.add(x_lt[i][t] - best_solution.x_lt[i][t] == 0);
}
}
}
//C1
for (int i = 0; i<2; i++)
{
for (int j = 0; j<_MAX_ZONE; j++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
IloExpr station_waiting(env);
for (int tau = 0; tau<t; tau++)
{
// Arriving passengers and Boarding passengers
station_waiting += g_demand_array_line_arriving[j][i][tau];
if (i == 1 && j == 1)
{
for (int qq = 0; qq<number_of_transfer_paths; qq++)
{
station_waiting -= transfer_boarding[qq][tau];
}
}
int path_id = 0;
while (path_id<g_path_vector.size())
{
if (g_path_vector[path_id].column_node_vector[0] == j && g_path_vector[path_id].column_node_line_vector[0] == i)
{
station_waiting -= p_pt[path_id][tau];
}
else if (g_path_vector[path_id].column_node_vector.size()>2) // this path has transfers
{
for (int q = 1; q<g_path_vector[path_id].column_node_vector.size() / 2; q++)// Arrive at the current line
{
if (g_path_vector[path_id].column_node_vector[2 * q] == j && g_path_vector[path_id].column_node_line_vector[2 * q] == i)
{
if (tau - t_r[path_id - 40] >= 0)
{
station_waiting += p_pt[path_id][tau - t_r[path_id - 40]];
}
}
}
}
path_id++;
}
}
constraints.add(max_waiting - station_waiting >= 0);
constraints.add(n_lit[i][j][t] - station_waiting == 0);
}
}
}
// C2
for (int l = 0; l<2; l++)
{
for (int i = 0; i<_MAX_ZONE; i++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
IloExpr in_vehicle_passengers(env); // Number of passengers that arrive at time t and station i
IloExpr train_arrive_indicator(env);
IloExpr passenger_board_indicator(env);
int indicator = 0;
if (t - i*(t_dwell + t_running) >= 0)
{
for (int p = 0; p<g_path_vector.size(); p++)
{
if (g_path_vector[p].column_node_line_vector[0] == l&&
g_path_vector[p].column_node_seq[0]<i&&
g_path_vector[p].column_node_seq[1] >= i)
{
in_vehicle_passengers += p_pt[p][t - (t_dwell + t_running)*(i - g_path_vector[p].column_node_seq[0])];
}
}
for (int p = g_path_vector.size() - number_of_transfer_paths; p<g_path_vector.size(); p++)
{
//if(l==1 && g_path_vector[p].column_node_vector[g_path_vector[p].column_node_vector.size()-1]>=i
// //&&t-(i-g_path_vector[p].column_node_seq[g_path_vector[p].column_node_seq.size()-2])*((t_dwell+t_running))>=0) //
// &&t-(i-1)*((t_dwell+t_running))>=0) //
if (l == 1 && i >= 1 && t - (i - 1)*((t_dwell + t_running)) >= 0) //
{
in_vehicle_passengers += transfer_boarding[p - g_path_vector.size() + number_of_transfer_paths][t - (i - 1)*((t_dwell + t_running))];
}
}
}
while (indicator<g_path_vector.size())
{
if (g_path_vector[indicator].column_node_line_vector[0] == l&&
g_path_vector[indicator].column_node_vector[0] == i)
{
passenger_board_indicator += p_pt[indicator][t];
}
indicator++;
}
// Transfer passengers
if (l == 1 && i == 1)
{
for (int qq = 0; qq<number_of_transfer_paths; qq++)
{
passenger_board_indicator += transfer_boarding[qq][t];
}
}
//indicator=0;
//while(indicator<t_dwell&&t-i*(t_dwell+t_running)-indicator>=0)
//{
// train_arrive_indicator += x_lt[l][t-i*(t_dwell+t_running)-indicator];
// indicator++;
//}
if (t - i*(t_dwell + t_running) >= 0)
{
constraints.add(passenger_board_indicator - TRAIN_CAPACITY*x_lt[l][t - i*(t_dwell + t_running)] <= 0);
constraints.add(passenger_board_indicator + in_vehicle_passengers <= TRAIN_CAPACITY);
}
else
{
constraints.add(passenger_board_indicator == 0);
}
// constraints.add(passenger_board_indicator==0);
}
}
}
// C3
for (int l = 0; l<2; l++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
IloExpr trains_num(env);
int tau = t;
while (tau<_MAX_TIME && tau<t + h_min)
{
trains_num += x_lt[l][tau];
tau++;
}
constraints.add(trains_num <= 1);
}
for (int t = 0; t<_MAX_TIME; t++)
{
if (t + t_cycle<_MAX_TIME)
{
IloExpr DepartTrains(env);
for (int tau = t; tau<t + t_cycle; tau++)
{
DepartTrains += x_lt[l][tau];
}
constraints.add(DepartTrains <= rolling_stock[l]);
}
}
}
// C4
for (int p = 0; p<g_path_vector.size(); p++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
IloExpr b_board_now(env);
int tau = 0;
while (tau <= t)
{
b_board_now += p_pt[p][tau];
tau++;
}
constraints.add(b_board_now <= g_demand_path_current[p][t]);
//constraints.add(b_board_now<=20000);
}
}
for (int t = 0; t<_MAX_TIME; t++)
{
IloExpr b_board_now(env);
IloExpr b_arrive_now(env);
int tau = 0;
while (tau <= t)
{
for (int qq = 0; qq<number_of_transfer_paths; qq++) // A set of constraints for each path
{
if (tau - t_r[qq] >= 0)
{
b_arrive_now += p_pt[g_path_vector.size() - number_of_transfer_paths + qq][tau - t_r[qq]];
}
b_board_now += transfer_boarding[qq][tau];
tau++;
}
constraints.add(b_board_now - b_arrive_now <= 0);
}
}
// Train capacity constraints
model.add(constraints);
//IloExpr expr1(env);
//for(int t=0;t<_MAX_TIME;t++)
//{
// expr1 += transfer_boarding[t];
//}
//IloExpr expr(env);
//for(int l=0;l<2;l++)
// for(int t=0;t<_MAX_TIME;t++)
// expr += (t+1)*x_lt[l][t];
//for(int l=0;l<2;l++)
// for(int i=0;i<_MAX_ZONE;i++)
// for(int t=0;t<_MAX_TIME;t++)
// expr += (_MAX_TIME-t)*n_lit[l][i][t];
//IloObjective model_obj = IloMaximize (env, expr1);
IloObjective model_obj = IloMinimize(env, max_waiting);
model.add(model_obj);
IloCplex newcc(model);
// newcc.setOut(env.getNullStream());
//newcc.setAnyProperty(IloCplex::Param::Benders::Strategy);
//newcc.setParam(IloCplex::Param::TimeLimit, 3600);
newcc.use(boundlimitCallback(env, newcc, IloFalse, newcc.getBestObjValue(), 1.0, 10000.0));
newcc.solve();
cout << "Solution status = " << newcc.getCplexStatus() << endl;
//if (newcc.getCplexStatus() == CPX_STAT_OPTIMAL || newcc.getCplexStatus() == CPXMIP_OPTIMAL_TOL)
{
//cout << "Objective value =" << newcc.getObjValue() << endl;
int out = 0;
for (int l = 0; l<2; l++)
{
cout << "Line " << l << " : ";
for (int t = 0; t<_MAX_TIME; t++)
{
best_solution.x_lt[l][t] = newcc.getIntValue(x_lt[l][t]);
//best_solution.x_lt[l][t] = newcc.getValue(x_lt[l][t]);
//cout << newcc.getValue(x_lt[l][t]) << ", ";
if (newcc.getValue(x_lt[l][t]) == 1)
{
cout << t << ", ";
}
}
cout << endl;
}
cout << "12345" << endl;
cout << "%%%%%%%%%%%" << endl;
float total_passenger = 0;
for (int i = 0; i<g_path_vector.size(); i++)
{
//cout<<"Path "<<i<<":";
for (int t = 0; t<_MAX_TIME; t++)
{
total_passenger += newcc.getValue(p_pt[i][t]);
cplex_boarding[i][t] = newcc.getValue(p_pt[i][t]);
}
}
cout << "The total demand is " << total_passenger << endl;
for (int t = 0; t<_MAX_TIME; t++)
{
for (int l = 0; l<2; l++)
for (int i = 0; i<_MAX_ZONE; i++)
g_demand_waiting[i][l][t] = newcc.getValue(n_lit[l][i][t]);
}
cout << "Transfer passengers" << endl;
for (int t = 0; t<_MAX_TIME; t++)
{
cout << newcc.getValue(transfer_boarding[0][t]) << ", ";
}
}
}
float cost_calculation(SOLUTION & solution)
{
float cost = 0;
//SOLUTION solution_now = solution;
int t_dwell = 1;
int t_running = 4;
int t_transfer = 2;
int t_r[2] = {0};
for (int i = 0; i<number_of_transfer_paths; i++)
{
int p_order = g_path_vector.size() - number_of_transfer_paths + i;
if (g_path_vector[p_order].column_node_vector.size() <= 2)
{
cout << "Error happens" << endl;
//abort();
}
else
{
int segment_traveled = 0;
int station_dwelled = 0;
segment_traveled = g_path_vector[p_order].column_node_vector[1] - g_path_vector[p_order].column_node_vector[0];
station_dwelled = segment_traveled - 1;
t_r[i] = t_transfer + segment_traveled*t_running + t_dwell*station_dwelled;
}
}
//for (int i = 0; i<number_of_transfer_paths; i++)
//{
// cout << "Travelling time of path " << i + g_path_vector.size() - number_of_transfer_paths << " = " << t_r[i] << endl;
//}
// Define variables
IloEnv env;
IloModel model(env);
NumVar3Matrix n_lit(env, 2);
for (int i = 0; i<2; i++)
{
n_lit[i] = NumVarMatrix(env, _MAX_ZONE);
for (int j = 0; j<_MAX_ZONE; j++)
{
n_lit[i][j] = IloNumVarArray(env, _MAX_TIME);
for (int t = 0; t<_MAX_TIME; t++)
{
n_lit[i][j][t] = IloNumVar(env, 0, IloInfinity, ILOFLOAT);
}
}
}
NumVarMatrix p_pt(env, g_path_vector.size());
for (int i = 0; i<g_path_vector.size(); i++)
{
p_pt[i] = IloNumVarArray(env, _MAX_TIME);
for (int t = 0; t<_MAX_TIME; t++)
{
p_pt[i][t] = IloNumVar(env, 0, IloInfinity, ILOFLOAT);
}
}
NumVarMatrix transfer_boarding(env, 2);
for (int i = 0; i<number_of_transfer_paths; i++)
{
transfer_boarding[i] = IloNumVarArray(env, _MAX_TIME);
for (int t = 0; t<_MAX_TIME; t++)
{
transfer_boarding[i][t] = IloNumVar(env, 0, IloInfinity, ILOFLOAT);
}
}
IloNumVar max_waiting(env, 0, IloInfinity, ILOFLOAT);
IloRangeArray constraints(env);
//C1
for (int i = 0; i<2; i++)
{
for (int j = 0; j<_MAX_ZONE; j++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
IloExpr station_waiting(env);
for (int tau = 0; tau<t; tau++)
{
// Arriving passengers and Boarding passengers
station_waiting += g_demand_array_line_arriving[j][i][tau];
if (i == 1 && j == 1)
{
for (int qq = 0; qq<number_of_transfer_paths; qq++)
{
station_waiting -= transfer_boarding[qq][tau];
}
}
int path_id = 0;
while (path_id<g_path_vector.size())
{
if (g_path_vector[path_id].column_node_vector[0] == j && g_path_vector[path_id].column_node_line_vector[0] == i)
{
station_waiting -= p_pt[path_id][tau];
}
else if (g_path_vector[path_id].column_node_vector.size()>2) // this path has transfers
{
for (int q = 1; q<g_path_vector[path_id].column_node_vector.size() / 2; q++)// Arrive at the current line
{
if (g_path_vector[path_id].column_node_vector[2 * q] == j && g_path_vector[path_id].column_node_line_vector[2 * q] == i)
{
if (tau - t_r[path_id-40] >= 0)
{
//cout << path_id <<" "<<","<<t<<";"<< tau - t_r[path_id - 40]<< endl;
//station_waiting += 100000000* p_pt[path_id][tau - t_r[path_id - 40]];
station_waiting += p_pt[path_id][tau - t_r[path_id - 40]];
}
}
}
}
path_id++;
}
}
constraints.add(max_waiting - station_waiting >= 0);
constraints.add(n_lit[i][j][t] - station_waiting == 0);
}
}
}
// C2
for (int l = 0; l<2; l++)
{
for (int i = 0; i<_MAX_ZONE; i++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
IloExpr in_vehicle_passengers(env); // Number of passengers that arrive at time t and station i
IloExpr train_arrive_indicator(env);
IloExpr passenger_board_indicator(env);
int indicator = 0;
if (t - i*(t_dwell + t_running) >= 0)
{
for (int p = 0; p<g_path_vector.size(); p++)
{
if (g_path_vector[p].column_node_line_vector[0] == l&&
g_path_vector[p].column_node_seq[0]<i&&
g_path_vector[p].column_node_seq[1] >= i)
{
in_vehicle_passengers += p_pt[p][t - (t_dwell + t_running)*(i - g_path_vector[p].column_node_seq[0])];
}
}
for (int p = g_path_vector.size() - number_of_transfer_paths; p<g_path_vector.size(); p++)
{
//if(l==1 && g_path_vector[p].column_node_vector[g_path_vector[p].column_node_vector.size()-1]>=i
// //&&t-(i-g_path_vector[p].column_node_seq[g_path_vector[p].column_node_seq.size()-2])*((t_dwell+t_running))>=0) //
// &&t-(i-1)*((t_dwell+t_running))>=0) //
if (l == 1 && i >= 1 && t - (i - 1)*((t_dwell + t_running)) >= 0) //
{
in_vehicle_passengers += transfer_boarding[p - g_path_vector.size() + number_of_transfer_paths][t - (i - 1)*((t_dwell + t_running))];
}
}
}
while (indicator<g_path_vector.size())
{
if (g_path_vector[indicator].column_node_line_vector[0] == l&&
g_path_vector[indicator].column_node_vector[0] == i)
{
passenger_board_indicator += p_pt[indicator][t];
}
indicator++;
}
// Transfer passengers
if (l == 1 && i == 1)
{
for (int qq = 0; qq<number_of_transfer_paths; qq++)
{
passenger_board_indicator += transfer_boarding[qq][t];
}
}
//indicator=0;
//while(indicator<t_dwell&&t-i*(t_dwell+t_running)-indicator>=0)
//{
// train_arrive_indicator += x_lt[l][t-i*(t_dwell+t_running)-indicator];
// indicator++;
//}
if (t - i*(t_dwell + t_running) >= 0)
{
constraints.add(passenger_board_indicator - TRAIN_CAPACITY*solution.x_lt[l][t - i*(t_dwell + t_running)] <= 0);
constraints.add(passenger_board_indicator + in_vehicle_passengers <= TRAIN_CAPACITY);
}
else
{
constraints.add(passenger_board_indicator == 0);
}
// constraints.add(passenger_board_indicator==0);
}
}
}
// C4
for (int p = 0; p<g_path_vector.size(); p++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
IloExpr b_board_now(env);
int tau = 0;
while (tau <= t)
{
b_board_now += p_pt[p][tau];
tau++;
}
constraints.add(b_board_now <= g_demand_path_current[p][t]);
//constraints.add(b_board_now<=20000);
}
}
for (int t = 0; t<_MAX_TIME; t++)
{
IloExpr b_board_now(env);
IloExpr b_arrive_now(env);
int tau = 0;
while (tau <= t)
{
for (int qq = 0; qq<number_of_transfer_paths; qq++) // A set of constraints for each path
{
if (tau - t_r[qq] >= 0)
{
b_arrive_now += p_pt[g_path_vector.size() - number_of_transfer_paths + qq][tau - t_r[qq]];
}
b_board_now += transfer_boarding[qq][tau];
tau++;
}
constraints.add(b_board_now - b_arrive_now <= 0);
}
}
// Train capacity constraints
model.add(constraints);
//IloExpr expr1(env);
//for(int t=0;t<_MAX_TIME;t++)
//{
// expr1 += transfer_boarding[t];
//}
//IloExpr expr(env);
//for(int l=0;l<2;l++)
// for(int t=0;t<_MAX_TIME;t++)
// expr += (t+1)*x_lt[l][t];
//for(int l=0;l<2;l++)
// for(int i=0;i<_MAX_ZONE;i++)
// for(int t=0;t<_MAX_TIME;t++)
// expr += (_MAX_TIME-t)*n_lit[l][i][t];
//IloObjective model_obj = IloMaximize (env, expr1);
IloObjective model_obj = IloMinimize(env, max_waiting);
model.add(model_obj);
IloCplex newcc(model);
newcc.setOut(env.getNullStream());
newcc.use(boundlimitCallback(env, newcc, IloFalse, newcc.getBestObjValue(), 1.0, 10.0));
//newcc.setAnyProperty(IloCplex::Param::Benders::Strategy);
//newcc.setParam(IloCplex::Param::TimeLimit, 3000);
newcc.solve();
//newcc.solve();
cout<<"Solution status = "<<newcc.getCplexStatus()<<endl;
if (newcc.getCplexStatus() == CPX_STAT_OPTIMAL || newcc.getCplexStatus() == CPXMIP_OPTIMAL_TOL)
{
cost = newcc.getObjValue();
cout<<"Objective value ="<<newcc.getObjValue()<<endl;
}
else
{
cout << "ERROR OCCURED!" << endl;
}
//delete[]t_r;
float total_passenger = 0;
for (int i = 0; i<g_path_vector.size(); i++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
total_passenger += newcc.getValue(p_pt[i][t]);
cplex_boarding[i][t] = newcc.getValue(p_pt[i][t]);
}
}
for (int t = 0; t<_MAX_TIME; t++)
{
for (int l = 0; l<2; l++)
for (int i = 0; i<_MAX_ZONE; i++)
g_demand_waiting[i][l][t] = newcc.getValue(n_lit[l][i][t]);
}
env.end();
//newcc.clear();
return cost;
}
bool feasibility_check(SOLUTION & solution)
{
bool feasible = true;
for (int i = 0; i<number_of_lines; i++)
{
for (int t = 0; t + h_min<_MAX_TIME; t++)
{
int check_headway = 0;
for (int tau = t; tau<t + h_min; tau++)
{
check_headway += solution.x_lt[i][tau];
}
if (check_headway>1)
{
return false;
}
}
for (int t = 0; t<_MAX_TIME; t++)
{
int check_rolling_stock = 0;
if (t + t_cycle<_MAX_TIME)
{
for (int tau = t; tau<t + t_cycle; tau++)
{
check_rolling_stock += solution.x_lt[i][tau];
}
}
if (check_rolling_stock > rolling_stock[i])
{
return false;
}
}
}
return feasible;
}
void initialization(void)
{
timetable *tb = new timetable();
int service_num = g_number_of_services;
int origin_time = 0;
int headway = 20;
for (int i = 0; i<service_num; i++)
{
for (int j = 0; j<g_number_of_nodes; j++)
{
if (j == 0)
{
tb->Arrive[j] = origin_time;
}
else
{
tb->Arrive[j] = tb->Depart[j - 1] + 10;
}
tb->Depart[j] = tb->Arrive[j] + 3;
}
origin_time += headway;
planned_timetable.push_back(*tb);
}
for (int i = 0; i<g_node_vector.size(); i++)
{
for (int j = 0; j<g_number_of_nodes; j++)
{
if (j>i)
g_node_vector[i].passenger_waiting.push_back(g_demand_array[i][j][0]);
else
g_node_vector[i].passenger_waiting.push_back(0);
}
}
for (int i = 0; i<g_number_of_services; i++)
for (int j = 0; j<g_number_of_nodes; j++)
for (int t = 0; t<_MAX_TIME; t++)
r_vehicle_data[i][j][t] = 0;
for (int i = 0; i<g_number_of_nodes; i++)
for (int j = 0; j<g_number_of_nodes; j++)
for (int t = 0; t<_MAX_TIME; t++)
{
r_station_data[i][j][t] = 0; r_station_data[i][j][0] = g_node_vector[i].passenger_waiting[j];
}
}
void train_simulater(int k, int t)
{
if (t<planned_timetable[k].Arrive[0] || t>planned_timetable[k].Depart[g_number_of_nodes - 1])
{
Trains[k].depot = true;
}
else
{
Trains[k].depot = false;
for (int i = 0; i<g_number_of_nodes; i++)
{
Trains[k].dwell = false;
Trains[k].running = false;
if (t>planned_timetable[k].Arrive[i] && t <= planned_timetable[k].Depart[i])
{
Trains[k].dwell = true;
Trains[k].dwell_station = i;
break;
// cout<<"Dwell "<<i<<endl;
}
else if (i != g_number_of_nodes - 1)
{
if (t <= planned_timetable[k].Arrive[i + 1] && t>planned_timetable[k].Depart[i])
{
Trains[k].running = true;
Trains[k].running_link = i;
break;
}
}
}
}
}
void simulation_process()
{
//Step 2 Update the running states of trains
for (int i = 0; i<planned_timetable.size(); i++)
{
train *tb = new train();
Trains.push_back(*tb);
}
cout << "Number of passengers in vehicle " << 0 << " =: ";
int cc = 0;
for (int t = 1; t<_MAX_TIME; t++)
{
for (int i = 0; i<g_number_of_nodes; i++)
{
for (int j = 0; j<g_number_of_nodes; j++)
{
g_boarding[i][j] = 0.0;
}
}
for (int k = 0; k<planned_timetable.size(); k++)
{
//cout<<accumulate(Trains[k].passenger_num.begin(), Trains[k].passenger_num.end(),static_cast<float>(0.0))<<", ";
// Update the train state
train_simulater(k, t);
// Update the passenger state
if (Trains[k].depot == false)
{
if (Trains[k].dwell == true)
{
// Passenger alighting
Trains[k].passenger_num[Trains[k].dwell_station] = 0;
// Passenger boarding
float remaining_capacity = TRAIN_CAPACITY - accumulate(Trains[k].passenger_num.begin(), Trains[k].passenger_num.end(), static_cast<float>(0.0));
// cout<<"Remaining_capacity = "<<(int)remaining_capacity<<endl;
float station_waiting = accumulate(g_node_vector[Trains[k].dwell_station].passenger_waiting.begin(),
g_node_vector[Trains[k].dwell_station].passenger_waiting.end(), static_cast<float>(0.0));
if (station_waiting <= remaining_capacity)
{
for (int j = Trains[k].dwell_station; j<g_number_of_nodes; j++)
{
g_boarding[Trains[k].dwell_station][j] = g_node_vector[Trains[k].dwell_station].passenger_waiting[j];
Trains[k].passenger_num[j] += g_boarding[Trains[k].dwell_station][j];
}
}
else
{
for (int j = Trains[k].dwell_station; j<g_number_of_nodes; j++)
{
g_boarding[Trains[k].dwell_station][j] = remaining_capacity*g_node_vector[Trains[k].dwell_station].passenger_waiting[j] / station_waiting;
Trains[k].passenger_num[j] += g_boarding[Trains[k].dwell_station][j];
}
}
// Update the passenger flow
}
}
// Save data
for (int i = 0; i<g_number_of_nodes; i++)
{
r_vehicle_data[k][i][t] = Trains[k].passenger_num[i];
}
}
// Update the passengers at stations
// cout<<"QQ "<<r_vehicle_data[0][1][2]<<endl;
for (int i = 0; i<g_number_of_nodes; i++)
{
for (int j = 0; j<g_number_of_nodes; j++)
{
g_node_vector[i].passenger_waiting[j] = g_node_vector[i].passenger_waiting[j] - g_boarding[i][j] + g_demand_array[i][j][t];
r_station_data[i][j][t] = g_node_vector[i].passenger_waiting[j]; //Save data
}
}
// Update the passenger flow of station
}
cout << "Tese here = " << cc << "; Test another " << r_vehicle_data[0][1][2] << endl;
}
void g_SaveOutputData(void)
{
FILE* g_pFileTrainPAX = NULL;
g_pFileTrainPAX = fopen("output_TrainPAX.csv", "w");
if (g_pFileTrainPAX == NULL)
{
cout << "File output_LinkMOE.csv cannot be opened." << endl;
}
else
{
fprintf(g_pFileTrainPAX, "Time And Train ID\n");
for (int t = 0; t<_MAX_TIME; t++)
{
for (int i = 0; i<g_number_of_services; i++)
{
float in_vehicle_passenger = 0;
for (int j = 0; j<g_number_of_nodes; j++)
{
in_vehicle_passenger += r_vehicle_data[i][j][t];
if (i == 0)
{
cout << ": " << r_vehicle_data[i][j][t] << " ";
}
}
fprintf(g_pFileTrainPAX, "%.3f,", in_vehicle_passenger);
}
cout << endl;
fprintf(g_pFileTrainPAX, "\n");
}
}
fclose(g_pFileTrainPAX);
FILE* g_pFileStationPAX = NULL;
g_pFileStationPAX = fopen("output_StationPAX.csv", "w");
if (g_pFileStationPAX == NULL)
{
cout << "File output_LinkMOE.csv cannot be opened." << endl;
}
else
{
fprintf(g_pFileStationPAX, "Time And Station ID\n");
for (int t = 0; t<_MAX_TIME; t++)
{
for (int i = 0; i<g_number_of_nodes; i++)
{
float station_passenger = 0;
for (int j = 0; j<g_number_of_nodes; j++)
{
station_passenger += r_station_data[i][j][t];
}
fprintf(g_pFileStationPAX, "%.3f,", station_passenger);
}
fprintf(g_pFileStationPAX, "\n");
}
}
fclose(g_pFileStationPAX);
}
void g_SaveOutputData_CPLEX(void)
{
// Generated data
FILE* g_pFilePAX_PATH = NULL;
g_pFilePAX_PATH = fopen("output_pax_path.csv", "w");
if (g_pFilePAX_PATH == NULL)
{
cout << "File output_LinkMOE.csv cannot be opened." << endl;
}
else
{
fprintf(g_pFilePAX_PATH, "Time And Path ID\n");
for (int t = 0; t<_MAX_TIME; t++)
{
for (int i = 0; i<g_path_vector.size(); i++)
{
fprintf(g_pFilePAX_PATH, "%.3f,", g_demand_path_current[i][t]);
}
fprintf(g_pFilePAX_PATH, "\n");
}
}
fclose(g_pFilePAX_PATH);
// Boarding data
FILE* g_pFileBoard_PATH = NULL;
g_pFileBoard_PATH = fopen("output_board_path.csv", "w");
if (g_pFileBoard_PATH == NULL)
{
cout << "File output_LinkMOE.csv cannot be opened." << endl;
}
else
{
fprintf(g_pFileBoard_PATH, "Time And Path ID\n");
for (int t = 0; t<_MAX_TIME; t++)
{
for (int i = 0; i<g_path_vector.size(); i++)
{
fprintf(g_pFileBoard_PATH, "%.3f,", cplex_boarding[i][t]);
}
fprintf(g_pFileBoard_PATH, "\n");
}
}
fclose(g_pFileBoard_PATH);
FILE* g_pFilePAX_STATION = NULL;
g_pFilePAX_STATION = fopen("output_StationPAX.csv", "w");
if (g_pFilePAX_STATION == NULL)
{
cout << "File output_LinkMOE.csv cannot be opened." << endl;
}
else
{
fprintf(g_pFilePAX_STATION, "Time And Station ID\n");
fprintf(g_pFilePAX_STATION, "line,");
for (int i = 0; i<_MAX_ZONE; i++)
{
fprintf(g_pFilePAX_STATION, "%d,", i);
}
fprintf(g_pFilePAX_STATION, "\n");
for (int l = 0; l<2; l++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
fprintf(g_pFilePAX_STATION, "%d,", l);
for (int i = 0; i<_MAX_ZONE; i++)
{
fprintf(g_pFilePAX_STATION, "%.3f,", g_demand_array_line_arriving[i][l][t]);
}
fprintf(g_pFilePAX_STATION, "\n");
}
}
}
fclose(g_pFilePAX_STATION);
// Waiting passengers at stations
FILE* g_pFileWAIT_STATION = NULL;
g_pFileWAIT_STATION = fopen("output_StationWAIT.csv", "w");
if (g_pFileWAIT_STATION == NULL)
{
cout << "File output_LinkMOE.csv cannot be opened." << endl;
}
else
{
fprintf(g_pFileWAIT_STATION, "Time And Station ID\n");
fprintf(g_pFileWAIT_STATION, "line,");
for (int i = 0; i<_MAX_ZONE; i++)
{
fprintf(g_pFileWAIT_STATION, "%d,", i);
}
fprintf(g_pFileWAIT_STATION, "\n");
for (int l = 0; l<2; l++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
fprintf(g_pFileWAIT_STATION, "%d,", l);
for (int i = 0; i<_MAX_ZONE; i++)
{
fprintf(g_pFileWAIT_STATION, "%.3f,", g_demand_waiting[i][l][t]);
}
fprintf(g_pFileWAIT_STATION, "\n");
}
}
}
fclose(g_pFileWAIT_STATION);
// Timetable
FILE* timetable = NULL;
timetable = fopen("timetable.csv", "w");
if (timetable == NULL)
{
cout << "File timetable.csv cannot be opened." << endl;
}
else
{
fprintf(timetable, "Time And Line ID\n");
for (int t = 0; t<_MAX_TIME; t++)
{
for (int i = 0; i<number_of_lines; i++)
{
fprintf(timetable, "%d,", best_solution.x_lt[i][t]);
}
fprintf(timetable, "\n");
}
}
fclose(timetable);
}
int _tmain()
{
srand((unsigned)time(NULL));
//planned_timetable.
startTime = clock();
g_ReadInputData(); // step 1: read input data of network and demand table/agents
// to do: read demand tables
initialization();
cout << "Test " << g_path_vector.size() << endl;
passenger_demand_initilization();
// VLNS
for (int i = 0; i<number_of_lines; i++)
{
for (int t = 0; t<_MAX_TIME; t++)
{
int cc = 0;
if (i == 0)
{
cc = 7;
}
else
{
cc = 8;
}
if ((t) % cc == 0)
{
best_solution.x_lt[i][t] = 1;
}
else
{
best_solution.x_lt[i][t] = 0;
}
}
}
if (feasibility_check(best_solution) == true)
{
// vnls();
}
else
{
cout << "\t\tThe initial solution is infeasible! Termininated" << endl;
}
new_cplex_model();
if (feasibility_check(best_solution) == true)
{
cout << "Feasible!" << endl;
}
cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << endl;
cout << "The optimal value is: " << cost_calculation(best_solution) << endl;
int service_num[2] = { 0 };
for (int i = 0; i<2; i++)
{
cout << "Line " << i << " :";
for (int t = 0; t<_MAX_TIME; t++)
{
if (best_solution.x_lt[i][t] == 1)
{
service_num[i] += 1;
cout << t << ", ";
}
}
cout << endl;
}
endTime = clock();
cout << "The run time is: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;
cout << "Services of Line 1 = " << service_num[0] << endl;
cout << "Services of Line 2 = " << service_num[1] << endl;
//for(int i=0;i<number_of_lines;i++)
//{
// for(int t=0;t<_MAX_TIME;t++)
// {
// if(best_solution.x_lt[i][t]!=test_solution.x_lt[i][t])
// {
// cout<<"error"<<endl;
// }
// }
//}
//cout<<"Feasible3 "<<feasibility_check(test_solution)<<endl;
g_SaveOutputData_CPLEX();
// delete[] g_pNetworkForSP;
// best_solution.cost = cost_calculation();
exit(0);
}
<file_sep>/SPNetwork/stdafx.h
// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//
#pragma once
#include "targetver.h"
#include<iostream>
#include <stdio.h>
#include <tchar.h>
#include <math.h>
// LR parameters
const int n_given = 100;
const int ite=20;
const int choose =2;
const int T_stamp = 300; // Number of timestamps
const int i_station = 8; // Number of bi directional stations
const int k_train = 7; // Number of considered trains
const int t_arrival[]={0, 30, 60, 90, 120, 150, 180, 210, 240, 270};
const int t_interval = 10; // Length of each time interval
const int d_min = 30/t_interval; // Mimimul time intervals for dwelling
const int d_max = 90/t_interval; // Maximum time intervals for dwelling
const int d_options[5] = {3, 4, 5, 6, 7};
// Totally six segments
const int s[]={1050, 1515, 1050, 1050, 1050, 1515, 1050, 1050};
const int t_segment[]={10, 15, 10, 10, 10, 15, 10, 10};
// 0, 1, 2, 3, 4, 5, 6, 7
//const int v_l[]={2, 1, 4, 7, 10, 12, 13, 13, 13, 13, 13, 10, 7, 4, 1, 2}; // Corresponding to the 1515 distance
const int v_l[]={1, 3, 6, 9, 12, 15, 15, 15, 15, 15, 15, 12, 9, 6, 3, 1}; // Corresponding to the 1515 distance
const int s_l[]={0, 15, 60, 135, 240, 375, 525, 675, 825, 975, 1125, 1275, 1380, 1455, 1500, 1515};
const int v_s[]={1, 5, 10, 15, 15, 15, 15, 15, 10, 5, 1}; // Corresponding to the 1050 distance
const int s_s[]={0, 25, 100, 225, 375, 525, 675, 825, 950, 1025, 1050};
const int l_train=150; // Length of train k
//const int d_safe=20; // Safe margin
const int d_safe=75; // Safe margin
const int b_rate=1; // Emergency braking rate
const int t_reaction=1; // Reaction time
const int w=12;
const float percentage=1/w;
const int reaction_sc[10]={15, 16, 80, 18, 19, 10, 11, 12, 13, 14}; // Scenario-based reaction time
//const int reaction_p[3]={0.5, 0.5, 0.5}; // Scenario-based reaction time
//const int stochastic_parameters[2][11]={ 12, 15, 14, 14, 13, 13, 0, 16, 12, 13, 14,
// 75, 75, 76, 60, 33, 75, 190, 0, 76, 79, 84};
const int parameter_1=5;
const int parameter_2=45;
const int parameter_9=50;
const int parameter_10=60;
const int stochastic_parameters[7][12]={ 12, 20, 17, 15, 13, 0, 16, 12, 13, 14,19, 16,
70, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84, 15, parameter_10,
90, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84, 15, parameter_10,
90, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84,15, parameter_10,
90, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84,15,parameter_10,
90, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84,20, parameter_10,
90, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84,40, parameter_10};
const int first_stochastic_parameters[7][12]={ 12, 20, 17, 15, 13, 0, 16, 12, 13, 14,19, 16,
70, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84, 15, parameter_10,
90, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84, 15, parameter_10,
90, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84,15, parameter_10,
90, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84,15, parameter_10,
90, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84,15, parameter_10,
91, parameter_1, parameter_2, 80, 75, 190, 0, 76, parameter_9, 84,15, parameter_10};
/*const int first_stochastic_parameters[7][11]={ 12, 19, 20, 17, 15, 13, 0, 16, 12, 13, 14,
70, 15, 0, 45, 80, 75, 190, 0, 76, 79, 84,
90, 15, 0, 45, 80, 75, 190, 0, 76, 79, 84,
90, 15, 0, 45, 80, 75, 190, 0, 76, 79, 84,
90, 15, 0, 45, 80, 75, 190, 0, 76, 79, 84,
90, 15, 0, 45, 80, 75, 190, 0, 76, 79, 84,
91, 15, 0, 46, 80, 75, 190, 0, 76, 79, 84};*/
/*const int second_stochastic_parameters[7][11]={ 12, 19, 20, 17, 15, 13, 0, 16, 12, 13, 14,
70, 15, 0, 45, 80, 75, 190, 0, 76, 79, 84,
90, 15, 0, 45, 80, 75, 190, 0, 76, 79, 84,
90, 15, 0, 45, 80, 75, 190, 0, 76, 79, 84,
225, 15, 0, 45, 80, 75, 190, 0, 76, 79, 84,
225, 1500, 0, 45, 80, 75, 190, 0, 76, 79, 84,
91, 1500, 0, 46, 80, 75, 190, 0, 76, 79, 84};*/
// Representation of stochastic parameters: First line: Reaction time; Second line: d_safe
const int depart_choices=4;
const int d_t_h=7;
/*const int train_depart_options[depart_choices][k_train]={0, 0+d_t_h, 2*d_t_h, 2*d_t_h, 4*d_t_h, 5*d_t_h, 6*d_t_h,
3, 3+d_t_h, 3+2*d_t_h, 3+3*d_t_h,3+ 4*d_t_h, 3+5*d_t_h, 3+6*d_t_h,
6, 6+d_t_h, 6+2*d_t_h, 6+3*d_t_h, 6+4*d_t_h, 6+5*d_t_h, 6+6*d_t_h,
8, 8+d_t_h, 8+2*d_t_h, 8+3*d_t_h, 8+4*d_t_h, 8+5*d_t_h, 8+6*d_t_h};*/
const int train_depart_options[depart_choices][k_train]= {0, 0+d_t_h, 0+2*d_t_h, 0+3*d_t_h, 1+ 4*d_t_h, 0+5*d_t_h, 0+6*d_t_h,
1, 1+d_t_h, 1+2*d_t_h, 1+3*d_t_h, 1+ 4*d_t_h, 1+5*d_t_h, 1+6*d_t_h,
2, 2+d_t_h, 2+2*d_t_h, 2+3*d_t_h, 2+4*d_t_h, 2+5*d_t_h, 2+6*d_t_h,
3, 3+d_t_h, 3+2*d_t_h, 3+3*d_t_h, 3+4*d_t_h, 3+5*d_t_h, 3+6*d_t_h};
/*const int train_depart_options[depart_choices][k_train]={0, 0+d_t_h, 2*d_t_h, 2*d_t_h, 4*d_t_h, 5*d_t_h, 6*d_t_h,
3, 3+d_t_h, 3+2*d_t_h, 3+3*d_t_h,3+ 4*d_t_h, 3+5*d_t_h, 3+6*d_t_h,
6, 6+d_t_h, 6+2*d_t_h, 6+3*d_t_h, 6+4*d_t_h, 6+5*d_t_h, 6+6*d_t_h,
8, 8+d_t_h, 8+2*d_t_h, 8+3*d_t_h, 8+4*d_t_h, 8+5*d_t_h, 8+6*d_t_h};*/
/*const int train_depart_options[depart_choices][k_train]={0, 0, 2, 2, 4, 5, 6,
3, 3, 3+2, 3+3,3+ 4, 3+5, 3+6,
6, 6, 6+2, 6+3, 6+4, 6+5, 6+6,
8, 8, 8+2, 8+3, 8+4, 8+5, 8+6};*/
int t_l=15; // Totally 15 running intervals
int t_s=10; // Totally 10 running intervals
int t_ar=12;
const int m_big=1000;
double cc= pow((double)2,(double)8);
const int dwell_state=(int)(cc);
extern int dwelling_time[];
extern int index_dwelling[][6];
//const int t_r[]={t_s, t_l, t_s, t_ar, t_s, t_l, t_s, t_ar};
const int t_r[]={10, 15, 10, 12, 10, 15, 10, 12};
//int dwelling_time[6];
int p_distance(int i, int t, int k);
int v_distance(int i, int t);
double sub1(double i);
//double f_path(int i, int j, int *k);
double f_coupling(int s, int i, int *q, int d, int *g, int k, double x);
double test_f_coupling(int s, int i, int *q, int d, int *g, int k, double x);
double first_train_f_coupling(int s, int i, int *j, int *x);
double test_first_train_f_coupling(int s, int i, int *j, int *x);
// Defination of speed profiles
// TODO: 在此处引用程序需要的其他头文件
<file_sep>/SPNetwork/network.h
#pragma once
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <list>
#include <algorithm>
#include <time.h>
#include <functional>
#include<stdio.h>
#include<math.h>
#include <numeric>
#define _MAX_ZONE 10
#define _MAX_TIME 99999
#define _MAX_LABEL_COST 999999
extern int g_number_of_links;
extern int g_number_of_nodes;
extern int g_number_of_services;
class CLink;
class CNode
{
public:
vector<float> passenger_waiting;
float passenger_waiting_num;
CNode()
{
passenger_waiting = vector<float>();
passenger_waiting_num = accumulate(passenger_waiting.begin(), passenger_waiting.end(), 0);
zone_id = -1;
accessible_node_count = 0;
}
int accessible_node_count;
int node_seq_no; // sequence number
int node_id; //external node number
int zone_id;
double x;
double y;
std::vector<CLink> m_outgoing_link_vector;
std::vector<int> m_incoming_link_seq_no_vector;
};
class CLink
{
public:
CLink() // construction
{
cost = 0;
BRP_alpha = 0.15f;
BRP_beta = 4.0f;
link_capacity = 1000;
free_flow_travel_time_in_min = 1;
flow_volume = 0;
link_spatial_capacity = 100;
/*
CFlowArrivalCount = 0;
CFlowDepartureCount = 0;
LinkOutCapacity = 0;
LinkLeftOutCapacity = 0;
LinkInCapacity = 0;
m_LeftTurn_NumberOfLanes = 0;
m_LeftTurn_link_seq_no = -1;
m_OutflowNumLanes = 1;*/
}
~CLink()
{
//if (flow_volume_for_each_o != NULL)
// delete flow_volume_for_each_o;
}
void free_memory()
{
}
void AddAgentsToLinkVolume()
{
}
void tally_flow_volume_across_all_processors();
float get_time_dependent_link_travel_time(int node_time_stamp_in_min)
{
int time_interval_no = node_time_stamp_in_min / 15;
if (time_interval_no < m_avg_travel_time.size())
return m_avg_travel_time[time_interval_no];
else
return cost;
}
std::vector<int> m_total_volume_vector;
std::vector<float> m_avg_travel_time;
// 1. based on BPR.
int m_LeftTurn_link_seq_no;
int m_RandomSeed;
int link_seq_no;
int from_node_seq_no;
int to_node_seq_no;
float cost;
float fftt;
float free_flow_travel_time_in_min;
int type;
float link_capacity;
float link_spatial_capacity;
float flow_volume;
float travel_time;
float BRP_alpha;
float BRP_beta;
float length;
void statistics_collection(int time_stamp_in_min);
/// end of simulation data
// signal data
bool m_bSignalizedArterialType;
int m_current_plan_no;
int m_number_of_plans;
int m_plan_startime_in_sec[20];
int m_plan_endtime_in_sec[20];
int m_to_node_cycle_in_sec[20];
int m_to_node_offset_in_sec[20];
int number_of_timing_plans;
float m_SaturationFlowRate_In_vhc_per_hour_per_lane[20];
int m_GreenStartTime_In_Second[20];
int m_GreenEndTime_In_Second[20];
float m_LeftTurn_SaturationFlowRate_In_vhc_per_hour_per_lane[20];
int m_LeftTurnGreenStartTime_In_Second[20];
int m_LeftTurnGreenEndTime_In_Second[20];
void UpdateCellVehiclePosition(int current_time_interval, int cell_no, int agent_id);
/*
void SetupCell(int number_of_cells)
{
for (int i = 0; i < number_of_cells; i++)
{
m_cell_current_t.push_back(-1);
m_cell_prev_t_1.push_back(-1);
}
}
void CopyCell()
{
// copy cell states
for (int c = 0; c < m_cell_current_t.size(); c++)
{
m_cell_prev_t_1[c] = m_cell_current_t[c];
m_cell_current_t[c] = -1;
}
}*/
float GetTimeDependentCapacityAtSignalizedIntersection(
double current_timeInMin,
int ¤t_plan_no,
int plan_startime_in_sec[20],
int plan_endtime_in_sec[20],
int to_node_cycle_in_sec[20],
int to_node_offset_in_sec[20],
float SaturationFlowRate[20],
int GreenStartTime_in_second[20],
int GreenEndTime_in_second[20],
float simulation_time_interval_in_second);
//
float get_VOC_ratio()
{
return flow_volume / max((float)0.00001, link_capacity);
}
float get_speed()
{
return length / max(travel_time, (float)0.0001) * 60; // per hour
}
/*float GetRandomRatio()
{
m_RandomSeed = (LCG_a * m_RandomSeed + LCG_c) % LCG_M; //m_RandomSeed is automatically updated.
return float(m_RandomSeed) / LCG_M;
}
std::vector<int> m_cell_current_t;
std::vector<int> m_cell_prev_t_1;*/
};
class CPath
{
public:
int path_id;
int column_cost;
float column_flow;
string served_pax_group;
std::vector<int> served_pax_group_vector;
string column_node_seq;
string column_node_time_seq;
std::vector<int> column_node_vector;
std::vector<int> column_node_line_vector;
//std::vector<int> column_node_arc_vector;
//std::vector<string> column_node_time_arc_vector;
CPath()
{
path_id = 0;
column_cost = 0.0;
column_flow = 0.0;
}
};
extern std::vector <CPath> g_path_vector;
class timetable
{
public:
int Trainindex;
vector<float> Arrive;
vector<float> Depart;
vector<string> PassStations;
timetable()
{
Arrive = vector<float>(g_number_of_nodes);
Depart = vector<float>(g_number_of_nodes);
}
//哪辆列车在哪个车站的到达和出发时间
// FLOAT TIMETABLE.TRAIN.STATION.DEPARTURE;
// FLPAT TIMETABLE.TRAIN.STATION.DEPARTURE;
};
class train
{
public:
bool depot;
bool dwell;
int dwell_station;
bool running;
int running_link;
//float sum_passenger;
vector<float> passenger_num;
train()
{
depot = false;
dwell = false;
running = false;
passenger_num = vector<float>(g_number_of_nodes);
//sum_passenger = accumulate(passenger_num.begin(), passenger_num.end(), 0);
}
//
};
class simulation
{
public:
vector<int> station_flow;
vector<int> service_flow;
};
extern std::vector<CNode> g_node_vector;
extern std::vector<CLink> g_link_vector;
extern std::vector<timetable> planned_timetable;
extern std::vector<train> Trains;
// extern vector<CAgent> g_agent_vector;
extern std::map<int, CLink*> g_pLink_map; // link seq no
class NetworkForSP // mainly for shortest path calculation
{
public:
NetworkForSP()
{
pFileAgentPathLog = NULL;
}
int m_threadNo; // internal thread number
int m_ListFront;
int m_ListTail;
int* m_SENodeList;
// std::list<int> m_SENodeList; //scan eligible list as part of label correcting algorithm
float* m_node_label_cost; // label cost // for shortest path calcuating
float* m_node_label_generalized_time; // label time // for shortest path calcuating
int* m_node_predecessor; // predecessor for nodes
int* m_node_status_array; // update status
int* m_link_predecessor; // predecessor for this node points to the previous link that updates its label cost (as part of optimality condition) (for easy referencing)
FILE* pFileAgentPathLog; // file output
float* m_link_volume_array; // link volume for all agents assigned in this network (thread)
float* m_link_cost_array; // link cost
std::vector<int> m_node_vector; // assigned nodes for computing
/*std::vector<CNode2NodeAccessibility> m_node2node_accessibility_vector;*/
void AllocateMemory(int number_of_nodes, int number_of_links)
{
m_SENodeList = new int[number_of_nodes];
m_node_predecessor = new int[number_of_nodes];
m_node_status_array = new int[number_of_nodes];
m_node_label_cost = new float[number_of_nodes];
m_node_label_generalized_time = new float[number_of_nodes];
m_link_predecessor = new int[number_of_nodes]; // note that, the size is still the number of nodes, as each node has only one link predecessor
//char buffer[256];
//sprintf_s(buffer, "%s_%d.csv", "agent_path", m_threadNo);
//pFileAgentPathLog = fopen(buffer, "w");
m_link_volume_array = new float[number_of_links];
m_link_cost_array = new float[number_of_links];
for (int l = 0; l < number_of_links; l++)
{
m_link_volume_array[l] = 0.0;
m_link_cost_array[l] = 1.0; //default value
}
}
~NetworkForSP()
{
if (m_SENodeList != NULL)
delete m_SENodeList;
if (m_node_label_cost != NULL)
delete m_node_label_cost;
if (m_node_predecessor != NULL)
delete m_node_predecessor;
if (m_node_status_array != NULL)
delete m_node_status_array;
if (m_link_predecessor != NULL)
delete m_link_predecessor;
if (m_link_volume_array != NULL)
delete m_link_volume_array;
if (m_link_cost_array != NULL)
delete m_link_cost_array;
if (pFileAgentPathLog != NULL)
fclose(pFileAgentPathLog);
}
// SEList: scan eligible List implementation: the reason for not using STL-like template is to avoid overhead associated pointer allocation/deallocation
void SEList_clear()
{
m_ListFront = -1;
m_ListTail = -1;
}
void SEList_push_front(int node)
{
if (m_ListFront == -1) // start from empty
{
m_SENodeList[node] = -1;
m_ListFront = node;
m_ListTail = node;
}
else
{
m_SENodeList[node] = m_ListFront;
m_ListFront = node;
}
}
void SEList_push_back(int node)
{
if (m_ListFront == -1) // start from empty
{
m_ListFront = node;
m_ListTail = node;
m_SENodeList[node] = -1;
}
else
{
m_SENodeList[m_ListTail] = node;
m_SENodeList[node] = -1;
m_ListTail = node;
}
}
bool SEList_empty()
{
return(m_ListFront == -1);
}
int SEList_front()
{
return m_ListFront;
}
void SEList_pop_front()
{
int tempFront = m_ListFront;
m_ListFront = m_SENodeList[m_ListFront];
m_SENodeList[tempFront] = -1;
}
int optimal_label_correcting(int origin_node, int destination_node, int departure_time, int shortest_path_debugging_flag, FILE* pFileDebugLog)
// time-dependent label correcting algorithm with double queue implementation
{
// computing_times ++;
int internal_debug_flag = 0;
if (g_node_vector[origin_node].m_outgoing_link_vector.size() == 0)
{
return 0;
}
for (int i = 0; i < g_number_of_nodes; i++) //Initialization for all nodes
{
m_node_status_array[i] = 0; // not scanned
m_node_label_cost[i] = _MAX_LABEL_COST;
m_node_predecessor[i] = -1; // pointer to previous NODE INDEX from the current label at current node and time
m_link_predecessor[i] = -1; // pointer to previous NODE INDEX from the current label at current node and time
}
//Initialization for origin node at the preferred departure time, at departure time, cost = 0, otherwise, the delay at origin node
m_node_label_cost[origin_node] = 0; //absolute time
m_node_label_generalized_time[origin_node] = 0; //relative travel time
SEList_clear();
SEList_push_back(origin_node);
while (!SEList_empty())
{
int from_node = SEList_front();//pop a node FromID for scanning
SEList_pop_front(); // remove current node FromID from the SE list
m_node_status_array[from_node] = 2;
if (shortest_path_debugging_flag)
fprintf(pFileDebugLog, "SP: SE node: %d\n", g_node_vector[from_node].node_id);
//scan all outbound nodes of the current node
for (int i = 0; i < g_node_vector[from_node].m_outgoing_link_vector.size(); i++) // for each link (i,j) belong A(i)
{
int to_node = g_node_vector[from_node].m_outgoing_link_vector[i].to_node_seq_no;
// ASSERT(to_node <= g_number_of_nodes);
bool b_node_updated = false;
float new_to_node_cost = m_node_label_cost[from_node] + m_link_cost_array[g_node_vector[from_node].m_outgoing_link_vector[i].link_seq_no];
if (shortest_path_debugging_flag)
{
fprintf(pFileDebugLog, "SP: checking from node %d, to node %d cost = %d\n",
g_node_vector[from_node].node_id,
g_node_vector[to_node].node_id,
new_to_node_cost, g_node_vector[from_node].m_outgoing_link_vector[i].cost);
}
if (new_to_node_cost < m_node_label_cost[to_node]) // we only compare cost at the downstream node ToID at the new arrival time t
{
if (shortest_path_debugging_flag)
{
fprintf(pFileDebugLog, "SP: updating node: %d current cost: %.2f, new cost %.2f\n",
g_node_vector[to_node].node_id,
m_node_label_cost[to_node], new_to_node_cost);
}
// update cost label and node/time predecessor
float aaa = 0;
aaa = new_to_node_cost;
m_node_label_cost[to_node] = aaa;
int link_seq_no = g_node_vector[from_node].m_outgoing_link_vector[i].link_seq_no;
//float new_to_node_time = m_node_label_generalized_time[from_node] + g_link_vector[link_seq_no].free_flow_travel_time_in_min;
//m_node_label_generalized_time[to_node] = new_to_node_time;
m_node_predecessor[to_node] = from_node; // pointer to previous physical NODE INDEX from the current label at current node and time
m_link_predecessor[to_node] = g_node_vector[from_node].m_outgoing_link_vector[i].link_seq_no; // pointer to previous physical NODE INDEX from the current label at current node and time
b_node_updated = true;
if (shortest_path_debugging_flag)
fprintf(pFileDebugLog, "SP: add node %d into SE List\n",
g_node_vector[to_node].node_id);
if (g_node_vector[to_node].node_seq_no != -1 && to_node != origin_node)
{
if (m_node_status_array[to_node] == 0)
{
SEList_push_back(to_node);
m_node_status_array[to_node] = 1;
}
}
}
}
}
if (destination_node >= 0 && m_node_label_cost[destination_node] < _MAX_LABEL_COST)
return 1;
else if (destination_node == -1)
return 1; // one to all shortest pat
else
return -1;
}
void optimal_label_correcting_for_all_nodes_assigned_to_processor()
{
cout << "Test " << m_node_vector.size() << endl;
for (int i = 0; i < m_node_vector.size(); i++) //Initialization for all nodes
{
int origin = m_node_vector[i];
int return_value = optimal_label_correcting(origin, -1, 0, 0, NULL); // one to all shortest path
}
}
// step 2: scan the shortest path to compute the link volume,
};<file_sep>/README.md
# Coordinated-train-timetabling-Models-Construction-Test-Instance
| ed5ae931e5065f27536cc68432a7045ed3648be4 | [
"Markdown",
"C",
"C++"
] | 4 | C++ | JerryYINJIATENG/Coordinated-train-timetabling-Models-Construction-Test-Instance | 3f535b622f2658466974d5f0dcee7cb236b3ffff | 4f7f46db8f14ad203459141f140f375e407bd788 |
refs/heads/master | <file_sep>import discord
import command
import os
import json
import dropbox
client = discord.Client()
bot_token = os.environ.get("bot_token", None)
name_cookie = os.environ.get("name_cookie", None)
exclusive_servers = os.environ.get("exclusive_servers", None)
dbx_token = os.environ.get("dbx_token", None)
try:
with open("local_env.json") as data_file:
data = json.load(data_file)
bot_token = data["bot_token"]
name_cookie = data["name_cookie"]
exclusive_servers = data["exclusive_servers"]
dbx_token = data["dbx_token"]
except:
print("local env not found")
cmd = None
isReady = False
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
global cmd
global isReady
global dbx_token
dbx = dropbox.Dropbox(dbx_token)
cmd = command.Command(client, dbx)
isReady = True
testGame = discord.Game()
testGame.name = "!commands for list"
await client.change_presence(game=testGame)
@client.event
async def on_message(message):
if not isReady:
return
#if message.author.name == client.user.name:
# print('this is me')
is_no_u = await check_for_no_u_message(message)
is_cookie_gay = await check_message_from_cookie_gay(message)
if is_no_u or is_cookie_gay:
await send_no_u_message(message)
else:
await cmd.parse(message)
async def check_message_from_cookie_gay(message):
if message.author.name != name_cookie:
return False
print('this is cookie')
for mention in message.mentions:
if mention.name == client.user.name:
if message.content.lower().__contains__('gay') or message.content.lower().__contains__('ghey'):
return True
return False
return False
async def check_for_no_u_message(message):
if(message.author.name == client.user.name):
return False
for mention in message.mentions:
if mention.name == client.user.name:
if message.content.lower().__contains__('no u'):
return True
return False
async def send_no_u_message(message):
authorId = "<@" + message.author.id + ">"
await client.send_message(message.channel, authorId + " no u")
client.run(bot_token)<file_sep>import discord
import random
import re
import os
import requests
from bs4 import BeautifulSoup as BS
from PIL import Image
import uuid
import json
dbx_reactions_dir = "/reactions/"
dbx_reactions_for_approval_dir = "/reactions/forApproval/"
local_tempDir = "tmp/"
local_reactions_dir = "reactions/"
owner_id = os.environ.get('owner_id', None)
testing_server_id = os.environ.get('testing_server_id', None)
channel_bot_pms = "bot-pms"
channel_reactions_for_approval = "reactions-for-approval"
reactions_per_message = 50
if owner_id == None:
with open("local_env.json") as data_file:
data = json.load(data_file)
owner_id = data["owner_id"]
testing_server_id = data["testing_server_id"]
class Command():
def __init__(self, client, dbx):
self.client = client
for server in client.servers:
if server.id == testing_server_id:
for channel in server.channels:
if channel.name == channel_bot_pms:
self.channel_bot_pms = channel
continue
if channel.name == channel_reactions_for_approval:
self.channel_reactions_for_approval = channel
continue
break
self.dbx = dbx
async def __notexist__(self, message):
print("Command does not exist. From",message.server.name,message.channel.name,message.author.name)
async def __commands__(self, message):
commands = ""
commands += "!aww or !a - Fetch a random image of cute stuffs >.<" + "\n\n"
commands += "!dadjoke or !d - Generate a dad joke" + "\n\n"
commands += "!rdump or !rd - Fetch a random image content" + "\n\n"
commands += "!react or !r {args} - Reaction command." + "\n" \
"> list - Fetch list of react images" + "\n" \
"> {react_name} - Fetch a react image" + "\n" \
"> add {react_name} - Add a react image for approval" + "\n\n"
commands += "!purge or !p {args} - Purge command. (default=all)" + "\n" \
"> all - Purge all messages by the bot" + "\n" \
"> reacts - Purge all react images by the bot" + "\n\n"
em = discord.Embed(title="Commands", description=commands)
em.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
if message.author.id == owner_id:
await self.client.send_message(self.channel_bot_pms, embed=em)
else:
await self.client.send_message(message.author, embed=em)
async def parse(self, message):
if not message.content.startswith("!"):
return
contents = message.content.split(" ");
command = contents[0]
command = command[1:]
await getattr(self,'__%s__' % command,self.__notexist__)(message)
async def __r__(self,message):
await self.__react__(message)
async def __react__(self,message):
args = message.content.split(" ")
if len(args) == 1:
return
arg = args[1]
if arg == "list":
file_list = get_files_list(self.dbx, dbx_reactions_dir)
file_list.sort()
range_len = int(len(file_list)/reactions_per_message) + 1
for i in range(range_len):
print("page ", i)
tmp_list = file_list[i * reactions_per_message : i * reactions_per_message + reactions_per_message]
em = discord.Embed(title="Reaction List " + str(i+1) + "/" + str(range_len), description="\n".join(tmp_list))
em.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
if message.author.id == owner_id:
await self.client.send_message(self.channel_bot_pms, embed=em)
else:
await self.client.send_message(message.author, embed=em)
return
elif arg == "add":
if len(message.attachments) == 0:
em = discord.Embed(title="Command error", description="No attachments found")
await self.client.send_message(message.channel, embed=em)
return
if len(args) != 3:
em = discord.Embed(title="Command error", description="Invalid number of arguments")
await self.client.send_message(message.channel, embed=em)
return
url = message.attachments[0].get("url")
fileparts = message.attachments[0].get("filename").split(".")
extension = "." + fileparts[len(fileparts)-1]
filename = args[2] + extension
if file_exists(self.dbx, filename, message.author.id == owner_id):
em = discord.Embed(title="Command error", description="React name already exists")
await self.client.send_message(message.channel, embed=em)
else:
result = save_react(self.dbx, url, filename, message.author.id == owner_id)
if result:
em = None
if message.author.id == owner_id:
em = discord.Embed(title="Command success", description="Added " + args[2])
else:
em2 = discord.Embed(title="For approval", description=args[2])
em2.set_image(url=url)
await self.client.send_message(self.channel_reactions_for_approval, embed=em2)
em = discord.Embed(title="Command success", description="Added " + args[2] + " for approval")
await self.client.send_message(message.channel, embed=em)
else:
em = discord.Embed(title="Command failed", description="Failed to add " + args[2])
await self.client.send_message(message.channel, embed=em)
return
elif message.author.id == owner_id and (arg == "approve" or arg == "reject"):
if len(args) < 3 or len(args) > 4:
em = discord.Embed(title="Command error", description="Invalid number of arguments")
await self.client.send_message(message.channel, embed=em)
return
async for tmp_message in self.client.logs_from(self.channel_reactions_for_approval):
print(tmp_message.embeds)
if len(tmp_message.embeds) == 1 and tmp_message.embeds[0]["title"] == "For approval" and tmp_message.embeds[0]["description"] == args[2]:
parts = tmp_message.embeds[0]["image"]["url"].split("/")
parts = parts[len(parts)-1].split(".")
extension = "." + parts[len(parts)-1]
from_name = args[2] + extension
to_name = args[2] + extension
if len(args) == 4:
to_name = args[3] + extension
try:
self.dbx.files_move(dbx_reactions_for_approval_dir + from_name, dbx_reactions_dir + to_name)
await self.client.delete_message(tmp_message)
if message.channel == channel_reactions_for_approval:
await self.client.delete_message(message)
except:
em = discord.Embed(title="Approval failed", description="React name already exists")
await self.client.send_message(message.channel, embed=em)
break
return
else:
exact = True
if arg.endswith("."):
arg = arg[0:-1]
exact = False
result = []
start = 0
while True:
tmp_result = self.dbx.files_search(dbx_reactions_dir, arg, start=start)
result.extend(tmp_result.matches)
if not tmp_result.more:
break;
start = tmp_result.start
if len(result) == 0 or exact and not str(result[0].metadata.name).lower().startswith(arg.lower() + "."):
em = discord.Embed(title="Command error", description="React does not exist")
await self.client.send_message(message.channel, embed=em)
return
index = 0
if not exact:
index = random.randrange(len(result))
name = result[index].metadata.name
path = str(uuid.uuid4().hex)
os.mkdir(local_tempDir + path)
md, response = self.dbx.files_download(dbx_reactions_dir+name)
f = open(local_tempDir + path + "/" + name, 'wb') # create file locally
f.write(response.content) # write image content to this file
f.close()
extension = "." + name.split(".")[-1]
await self.client.send_file(message.channel, local_tempDir + path + "/" + name, filename="react"+extension)
os.remove(local_tempDir + path + "/" + name)
os.rmdir(local_tempDir + path)
async def __d__(self, message):
await self.__dadjoke__(message)
async def __dadjoke__(self, message):
response = requests.get("https://icanhazdadjoke.com/slack")
joke = response.json().get('attachments')[0].get('text')
em = discord.Embed(title="Dad Joke", description=joke)
await self.client.send_message(message.channel, embed=em)
async def __rd__(self, message):
await self.__rdump__(message)
async def __rdump__(self, message):
await self.client.send_typing(message.channel)
path = fetch_ifunny_shuffle()
await self.client.send_file(message.channel, path)
os.remove(path)
async def __a__(self, message):
await self.__aww__(message)
async def __aww__(self, message):
await self.client.send_typing(message.channel)
path = fetch_random_reddit_image_content('aww')
await self.client.send_file(message.channel, path)
os.remove(path)
async def __p__(self, message):
await self.__purge__(message)
async def __purge__(self, message):
args = message.content.split(" ")
if len(args) == 1:
args.append("all")
arg = args[1]
tmp_timestamp = None
timestamp = None
messages = 0
if arg == "all":
await self.client.purge_from(message.channel, limit=300,
check=lambda m: m.author == self.client.user)
elif arg == "reacts":
await self.client.purge_from(message.channel, limit=300,
check=lambda m: m.author == self.client.user and len(m.attachments) > 0
and m.attachments[0]["filename"].startswith("react."))
def fetch_ifunny_shuffle():
ifunny = requests.get("https://ifunny.co/feeds/shuffle").content
soup = BS(ifunny, "html.parser")
div = soup.select("div.post__media > div.media")[0]
data_type = div.get("data-type")
if data_type == "video":
return fetch_ifunny_shuffle()
elif data_type == "image":
print('gif content')
content = div.get("data-source")
return download_image(content, local_tempDir)
else:
div = soup.select("div.post__media > div.media img")[0]
content = div.get("src")
path = download_image(content, local_tempDir)
content = Image.open(path)
width, height = content.size
content = content.crop((0, 0, width, height - 20))
content.save(path)
return path
def fetch_random_reddit_image_content(subreddit):
r = requests.get("https://www.reddit.com/r/"+subreddit+"/random.json",
headers={"User-agent": "Yotsubot getting a random post" + uuid.uuid4().hex}).content
item = json.loads(r)[0].get("data").get("children")[0].get("data")
domain = item.get("domain")
url = item.get("url")
print('fetch')
if (domain == "i.redd.it" or domain == "i.imgur.com") and (url.endswith(".jpg") or url.endswith(".png")):
return download_image(url, local_tempDir)
else:
return fetch_random_reddit_image_content(subreddit)
def download_image(url, path):
if path[-1] == "/":
parts = url.split('/');
parts = parts[len(parts) - 1].split(".")
extension = "." + parts[len(parts) - 1]
name = str(uuid.uuid4().hex)
path += name + extension
elif os.path.exists(path):
return None
f = open(path, 'wb') # create file locally
f.write(requests.get(url).content) # write image content to this file
f.close()
return path
def get_files_list(dbx, arg):
file_list = []
response = None
if isinstance(arg, str):
response = dbx.files_list_folder(arg)
else:
response = dbx.files_list_folder_continue(arg)
for metadata in response.entries:
strings = metadata.name.split(".")
if len(strings) == 2:
file_list.append(strings[0])
if response.has_more:
file_list.extend(get_files_list(dbx, response.cursor))
return file_list
def file_exists(dbx, path, isOwner):
try:
result = dbx.files_get_metadata(dbx_reactions_dir + path)
return True
except:
if not isOwner:
try:
result = dbx.files_get_metadata(dbx_reactions_for_approval_dir + path)
return True
except:
return False
return False
def save_react(dbx, url, path, isOwner):
if isOwner:
path = dbx_reactions_dir + path
else:
path = dbx_reactions_for_approval_dir + path
result = dbx.files_save_url(path, url)
jobid = result.get_async_job_id()
while True:
result = dbx.files_save_url_check_job_status(jobid)
if result.is_complete():
return True
elif result.is_failed():
return False
def auto_role_tagging():
print('auto_role_tagging start')
'''
for i, role in enumerate(message.author.roles):
message.author.roles[i] = str(role)
if message.content == "%refresh" and message.author.roles.__contains__("Admin"):
print("refreshing")
'''
'''
for member in message.server.members:
for i, role in enumerate(member.roles):
member.roles[i] = str(role)
if member.roles.__contains__("Bots"):
continue
if member.game != None:
print(member.name,"playing",member.game.name)
else:
print(member.name, "is not playing")
print(message.raw_role_mentions)
print(message.content)
channel = discord.utils.get(message.server.channels, name="general");
print(channel.name)
async for m in client.logs_from(channel, 9999):
print(m.content)
'''
async def react_old(self, message):
args = message.content.split(" ")
if len(args) == 1:
return
reactName = args[1]
files = os.listdir("reactions")
if reactName == "list":
reactList = "";
for file in files:
react = file.split(".")[0]
if react.startswith("loliPolice"):
react = react[:-1]
if not reactList.__contains__(react):
reactList += react + "\n"
reactList = reactList[:-1]
em = discord.Embed(title="Reaction List", description=reactList)
em.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
if message.author.id == owner_id:
await self.client.send_message(self.channel_bot_pms, embed=em)
else:
await self.client.send_message(message.author, embed=em)
return;
elif reactName == "add" and message.author.id == owner_id:
if len(message.attachments) == 0:
em = discord.Embed(title="Command error", description="No attachments found")
await self.client.send_message(message.channel, embed=em)
return
if len(args) != 3:
em = discord.Embed(title="Command error", description="Invalid number of arguments")
await self.client.send_message(message.channel, embed=em)
return
url = message.attachments[0].get("url")
fileparts = message.attachments[0].get("filename").split(".")
extension = "." + fileparts[len(fileparts)-1]
#regex = "\s*(%s\d*\.\w*)\s*" % reactName
#matches = re.findall(regex, " ".join(files))
path = local_reactions_dir + args[2] + extension
result = download_image(url, path)
if result == None:
em = discord.Embed(title="Command error", description="React name already exists")
await self.client.send_message(message.channel, embed=em)
else:
em = discord.Embed(title="Command success", description="Added " + args[2])
await self.client.send_message(message.channel, embed=em)
#f = open(reactionsDir + args[2] + extension, 'wb') # create file locally
#f.write(requests.get(url).content) # write image content to this file
#f.close()
return
else:
regex = "\s*(%s\d*\.\w*)\s*" % reactName
matches = re.findall(regex, " ".join(files))
path = ""
if len(matches) == 0:
print("React does not exists.")
return
elif len(matches) == 1:
path = local_reactions_dir + matches[0]
else:
i = random.randrange(0,len(matches)-1)
path = local_reactions_dir + matches[i]
await self.client.send_file(message.channel, path)<file_sep>discord==0.0.2
bs4==0.0.1
requests==2.19.1
Pillow==5.3.0
dropbox==9.1.0<file_sep>import re
import os
import requests
from bs4 import BeautifulSoup as BS
from PIL import Image
import praw
import time
import random
import uuid
import json
files = os.listdir("reactions")
files.append('loliPolice4.jpg')
print(" ".join(files))
#regex = ".\s(%s[0-9]*\.\w*).\s" % "loliPolice"
regex = "\s*(%s\d*\.\w*)\s*" % "aiGood"
print(regex)
matches = re.findall(regex, " ".join(files))
print(matches)
print("asdqweasd".replace("asd","qwe",1))
'''
url = "https://cdn.discordapp.com/attachments/370073365907767298/371802004688863253/FB_IMG_1492378612678.jpg"
f = open('test.jpg','wb') #create file locally
f.write(requests.get(url).content) #write image content to this file
f.close()
'''
#"https://ifunny.co/feeds/shuffle"
#"https://ifunny.co/fun/5guVpF5a2"
'''
ifunny = requests.get("https://ifunny.co/feeds/shuffle").content
soup = BS(ifunny,"html.parser")
div = soup.select("div.post__media > div.media")[0]
data_type = div.get("data-type")
if(data_type == "video"):
print("recurse")
elif(data_type == "image"):
print('gif content')
content = div.get("data-source")
print(content)
else:
div = soup.select("div.post__media > div.media img")[0]
content = div.get("src")
f = open('tmp/test.jpg', 'wb') # create file locally
f.write(requests.get(content).content) # write image content to this file
f.close()
test = Image.open("tmp/test.jpg")
test.show()
width, height = test.size
print(width, height)
test = test.crop((0,0,width,height-20))
test.show()
test.save("tmp/test2.jpg")
print(content)
'''
'''
r = praw.Reddit(client_id='evotNYj0m13_hA', client_secret='<KEY>',user_agent='Yotsubot')
random_time = random.randrange(1356998400,int(time.time()))
posts = r.subreddit('aww').
i = 0
for post in posts:
print(post.title)
i += 1
print("Total:",i)
'''
'''
r = requests.get("https://www.reddit.com/r/aww/random.json",headers = {'User-agent': 'Yotsubot getting a random post'+uuid.uuid4().hex}).content
a = json.loads(r)
print(a[0].get('data').get('children')[0].get('data').get('domain'))
#if(domain == "i.redd.it" or domain == "imgur.com"):
'''
domain = "i.imgur.com"
url = "https://i.imgur.com/xQnyb1s.gifv"
if domain == "i.redd.it" or domain == "i.imgur.com" and (url.endswith(".jpg") or url.endswith(".png")):
print("accepted")
else:
print("recurse")
| 4aad1f4a65cda5e188cfe56275a642b2f1648f5e | [
"Python",
"Text"
] | 4 | Python | jomarcruzzz/discord-yotsubot | 736755f062d24441e9eb14eb48a3f61fcd4f4317 | 5f3f7dad1d15110d01ea0afd9303c18356b627ef |
refs/heads/master | <repo_name>Code-Community99/Hiq-django<file_sep>/suggestion/forms.py
from django.forms import ModelForm ,Textarea
from .models import suggetion_box
class sugfrm(ModelForm):
class Meta:
model = suggetion_box
widgets = {
'suggestion':Textarea(attrs = {"rows":6 , "cols":40})
}
fields = ("suggestion",)
<file_sep>/logout/views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from signup.models import signup_user
# Create your views here.
def logout(request):
try:
try:
loguser = signup_user.objects.get(Email = request.session['email'])
loguser.logstatus = False
loguser.save()
print(signup_user.objects.get(Email = request.session['email']).logstatus)
except Exception as e:
print("->>>> {}\n\n".format(e))
# pass
# Delete the session data
# request.session.clear()
request.session.flush()
except:
return HttpResponse("You are not logged in")
else:
return redirect("/")
print(signup_user.objects.get(logstatus = False))
<file_sep>/home/admin.py
from django.contrib import admin
from .models import home_data
# Register your models here.
class home_data_disp(admin.ModelAdmin):
model = 'home_data'
fields = ['']
# admin.site.register(home_data , home_data_disp)
<file_sep>/gallery/views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
# Create your views here.
from .forms import galform
from .models import HiQGallery
from signup.models import signup_user
def photos(request):
uploadimage = HiQGallery.objects.order_by("id")
form = galform()
if request.method =="POST":
email = ""
try:
statusdecision = signup_user.objects.get(Email = request.session["email"]).logstatus
request.session['email']
except Exception as e:
lcontrol = False
uname = "You are not yet logged in."
return redirect("/login/")
else:
lcontrol = True
try:
email = signup_user.objects.get(Email = request.session['email']).uid
except Exception as e:
print("{}\n\n\n\n\n\n\n\n\n\n".format(e))
return redirect("/login/")
else:
getuid = email
HiQGallery.objects.create(image = request.FILES['image'], uid_id = getuid, imagedescription = request.POST['imagedescription'])
hqgallery = HiQGallery.objects.all()
return render(request , "./gallery/gallery.html" , context = {"gallery":hqgallery , "uploadimage":uploadimage , "loginshow":lcontrol , "uploadimage":form})
else:
hqgallery = HiQGallery.objects.all()
# uploaduser
lcontrol = False
try:
statusdecision = signup_user.objects.get(Email = request.session["email"]).logstatus
request.session['email']
except Exception as e:
lcontrol = False
return render(request , "./gallery/gallery.html" , context = {"gallery":hqgallery , "uploadimage":uploadimage , "uploadimage":form , "loginshow":lcontrol })
else:
lcontrol = True
hqgallery = HiQGallery.objects.all()
return render(request , "./gallery/gallery.html" , context = {"gallery":hqgallery , "uploadimage":uploadimage , "uploadimage":form , "loginshow":lcontrol })
def uploadphotos(request):
if request.method == "POST":
try:
HiQGallery.objects.create(uid_id = signup_user.objects.get(Email = request.session["email"]).uid ,
image = request.FILES["image"])
return redirect("/gallery")
except KeyError as e:
return redirect("/login/")
else:
pass
else:
pass
frm = galform
return render(request , "./gallery/uploadgal.html" , context = {"up":frm})
<file_sep>/upload_pro/models.py
from django.db import models
# Create your models here.
from signup.models import signup_user
class project(models.Model):
cat = (("Web" , "Website"),("Android app" , "Android app") , ("Art & poem" , "Art & poem") ,("Not listed", "Not listed"))
uid = models.ForeignKey(signup_user , on_delete = models.CASCADE)
# projectowner = models.EmailField(max_length = 50)
project_name = models.CharField(max_length = 30)
category = models.CharField(max_length = 30 , null = True , choices = cat)
project_description = models.TextField(max_length = 255)
file = models.FileField(max_length = 100)
uploadtime = models.DateTimeField(auto_now_add=True , null = True)
class Meta:
db_table = "projects"
def __str__(self):
return self.projectowner
<file_sep>/Feeds/views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import feeds_list
from signup.models import signup_user
from .forms import feedform
from comments.models import comment_list
from django.db.models import Count
def Feeds(request):
try:
statusdecision = signup_user.objects.get(Email = request.session["email"]).logstatus
request.session["email"]
except:
lcontrol = False
uname = "You are not yet logged in."
return redirect("/login")
else:
lcontrol = True
if request.method == "POST":
pass
else:
updates = feeds_list.objects.order_by("-post_time").annotate(Count("comment_list__uid"))
commentcount = []
print(vars(feeds_list.objects.all()))
# for x in updates:
# commentcount.append(feeds_list.objects.filter(fid = x.Fid))
online_users = []
filler = signup_user.objects.filter(logstatus=True)
for user in filler:
online_users.append(user.First_Name)
return render(request , "./Feeds/feed.html" , context = {"updates" : updates,"online_users":online_users , "commentcount":commentcount , "loginshow":lcontrol})
def addFeeds(request):
useremail = ""
try:
useremail = request.session["email"]
except:
return redirect("/login/")
else:
if request.method =="POST":
feed = request.POST["feed"]
uid = signup_user.objects.get(Email = useremail).uid
feeds_list.objects.create(uid_id = uid, feed = feed)
return redirect("/Feeds/")
else:
form = feedform()
return render(request , "./Feeds/feed.html" , context = {"form":form})
<file_sep>/signup/admin.py
from django.contrib import admin
from .models import signup_user
class hiq_users_disp(admin.ModelAdmin):
model = "hiq_users_disp"
list_display = ["uid","First_Name" , "Second_name" , "Password" , "Email" , "Phone_Number"]
class Meta:
pass
admin.site.register(signup_user , hiq_users_disp)
<file_sep>/logout/urls.py
from django.conf.urls import url
from . import views
app_name = "logout"
urlpatterns=[
url("logout/" , views.logout , name = "logout")
]
<file_sep>/gallery/admin.py
from django.contrib import admin
# Register your models here.
from .models import HiQGallery
class md(admin.ModelAdmin):
list_display = ("uid" , "image")
admin.site.register(HiQGallery , md)
<file_sep>/home/forms.py
from django import forms
from .models import home_data
# class loginfrm(forms.ModelForm):
# class Meta:
# model = "hqlog"
# fields = [""]
class loginfrm(forms.Form):
username = forms.CharField(max_length = 40 ,label = "hq")
password = forms.CharField(max_length = 40 ,label = "hq")
email = forms.CharField(max_length = 40 ,label = "hq")
<file_sep>/signup/models.py
from django.db import models
from cloudinary.models import CloudinaryField
# Create your models here.
class signup_user(models.Model):
uid = models.AutoField(primary_key = True)
First_Name = models.CharField(max_length = 30)
Second_name = models.CharField(max_length = 30)
Password = models.CharField(max_length = 255)
Email = models.EmailField(max_length = 30 , unique = True)
Phone_Number = models.CharField(max_length = 30)
profilepic = CloudinaryField("image")
logstatus = models.BooleanField(max_length = 3 , default = False)
admin_status = models.BooleanField(max_length = 3, default = 0)
class Meta:
db_table = "users"
<file_sep>/login/views.py
from django.shortcuts import render,redirect
from signup.models import signup_user
from .forms import loginfrm
from events.models import events_list
from django.utils import timezone
from django.contrib.auth.hashers import check_password
# Create your views here.
def login(request , param = ""):
error_var = ""
sess = ""
alredylog = param
print(alredylog)
try:
events_list.objects.filter(eventup_date__lte = timezone.now()).delete()
except Exception as e:
pass
if request.method == 'POST':
form = loginfrm(request.POST)
try:
form = loginfrm(request.POST)
logstats = signup_user.objects.get(Email = request.POST['email'])
except:
error_var = "no user with name exists"
form = loginfrm(request.POST)
return render (request , "./login/login.html" , context = {"form": form , "error":error_var ,"sess":sess , "alredy":alredylog})
else:
form = loginfrm(request.POST)
if check_password(request.POST['password'] , logstats.Password):
request.session["username"] = logstats.First_Name
logstats.logstatus = True
logstats.save()
# print()
# request.session["email"] = signup_user.objects.get(Email = request.POST['email'])
# set the username of the currrent user
sess = request.session["username"]
# set the session variable email address
request.session["email"] = request.POST['email']
# Expires immediately th user exits the browser
request.session.set_expiry(0)
# redirect users to their profile page
return redirect("/")
else:
error_var = "Wrong credentials Please try again"
return render (request , "./login/login.html" , context = {"form": form , "error":error_var ,"sess":sess , "alredy":alredylog})
else:
form = loginfrm()
return render (request , "./login/login.html" , context = {"form": form , "error":error_var ,"sess":sess , "alredy":alredylog})
<file_sep>/comments/views.py
from django.shortcuts import render,redirect
from .models import comment_list
from django.http import HttpResponse
from .forms import commentform
from signup.models import signup_user
from Feeds.models import feeds_list
def commentview(request , feedid):
uname = ""
try:
statusdecision = signup_user.objects.get(Email = request.session["email"]).logstatus
request.session["email"]
except:
lcontrol = False
uname = "You are not yet logged in."
return redirect("/login/")
else:
lcontrol = True
if not statusdecision:
uname = "You are not yet logged in."
# print(statusdecision)
return redirect("/login/")
else:
try:
form = commentform()
fid = feedid
feedcontent = feeds_list.objects.get(Fid = fid)
comments = comment_list.objects.filter(fid_id = feedid).order_by("comment_post_time")
except Exception as e:
return redirect("/Feeds/")
else:
return render(request , "./comments/comments.html/" , context = {"comments":comments , "form":form,"fid":fid ,
"fidcontent":feedcontent,"loginshow":lcontrol})
def addcomment(request):
try:
request.session["email"]
except:
return redirect("/login")
else:
form = commentform()
fid = request.POST['fid']
cuid = signup_user.objects.get(Email = request.session["email"]).uid
comments = comment_list.objects.filter(fid = request.POST['fid'])
comment_list.objects.create(uid_id = cuid,fid_id = request.POST['fid'] , comments = str(request.POST["comments"]))
return redirect("/comments/{}/#test".format(fid))
<file_sep>/Feeds/forms.py
from django import forms
from .models import feeds_list
class feedform(forms.ModelForm):
class Meta:
model = feeds_list
fields = ("feed",)
<file_sep>/upload_pro/urls.py
from django.conf.urls import url
from . import views
app_name = "upload"
urlpatterns = [
url("delete_project/(?P<deletedp>[\w]+\D+\w*)/" , views.delete_project , name = "delete_project"),
url("delete_project/<slug:deletedp>/" , views.delete_project , name = "delete_project"),
url("^$" , views.upload , name = "upload"),
url("projects/<str:delpro>/" , views.projects , name = "projects"),
]
<file_sep>/comments/urls.py
from django.conf.urls import url
from . import views
app_name = "coms"
urlpatterns =[
url(r"(?P<feedid>[\d]+)" , views.commentview , name = "comments"),
url(r"addcomment/" , views.addcomment , name = "addcomment"),
]
<file_sep>/signup/views.py
from django.shortcuts import render,redirect
from .models import signup_user
from django.contrib.auth.hashers import make_password
# Create your views here.
def signup(request):
error_log = {}
if request.method == "POST":
try:
signup_user.objects.get(Email = request.POST["email"])
except Exception as e:
signup_user.objects.create(First_Name = request.POST["fname"] , Second_name = request.POST['sname'] ,
Password = <PASSWORD>(request.POST['password']) , profilepic = request.FILES['profile'], Email = request.POST['email'] , Phone_Number = request.POST['pnumber'])
return render(request , "./login/login.html")
else:
error_log = {"email":"Email is in use by another account. Try another one"}
return render(request , "./signup/signup.html" , context = {"error_log":[errormessage for errormessage in error_log.values()]})
else:
return render(request , "./signup/signup.html")
<file_sep>/gallery/migrations/0001_initial.py
# Generated by Django 3.0.2 on 2020-01-31 11:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('signup', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='HiQGallery',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('imagedescription', models.CharField(max_length=255)),
('image', models.FileField(max_length=255, upload_to='')),
('uid', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='signup.signup_user')),
],
),
]
<file_sep>/comments/templatetags/strf.py
from django import template
from time import strftime,time,mktime
from datetime import datetime
register = template.Library()
def st(timeobj):
return timeobj.strftime("%Y-%h-%d,%H:%M:%S")
register.filter("time" , st)
<file_sep>/upload_pro/forms.py
from django import forms
from .models import project
class uploadform(forms.ModelForm):
# category = forms.ChoiceField(options=["It"])
class Meta:
model = project
fields = ["category" , "project_name" , "project_description" , "file"]
<file_sep>/uprofile/urls.py
from django.conf.urls import url
from . import views
app_name = "profile"
urlpatterns = [
url("^$" , views.profile_viewer , name = "profile"),
url("update/" , views.update , name = "update"),
]
<file_sep>/events/admin.py
from django.contrib import admin
# Register your models here.
from .models import events_list
class event_display(admin.ModelAdmin):
model = events_list
list_display = ["event_id","event_organizer","event_description","event_post_date"]
class Meta:
pass
admin.site.register(events_list,event_display)
<file_sep>/home/tests.py
from django.test import TestCase
# Create your tests here.
class myhome(TestCase):
def test_pub(self):
self.assertIs(True)
<file_sep>/upload_pro/views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
# Create your views here.
from .forms import uploadform
from .models import project
from signup.models import signup_user
def projects(request):
try:
pro = project.objects.filter(uid = signup_user.objects.get(Email = request.session["email"])).order_by("uploadtime")
except:
errorlog = "Login First"
return redirect("/login")
else:
return render(request , "./upload_pro/projects.html" , context = {"yourprojects":pro})
def delete_project(request , deletedp = "Nothing altered .... "):
otherprojects = ""
uname = ""
try:
# print(deletedp)
project.objects.filter(project_name=deletedp).delete()
except:
pass
else:
# print(signup_user.objects.get(Email = request.session["email"]).Email)
# print("Got the value ->> {}".format(signup_user.objects.get(Email = request.session["email"]).uid))
otherprojects = project.objects.filter(uid = signup_user.objects.get(Email = request.session["email"])).order_by("uploadtime")
# otherprojects = project.objects.filter(uid_id.uid = 5)
# print(otherprojects)
uname = request.session["email"].split("@")[0]
usern = request.session["username"]
userinfo = signup_user.objects.get(Email = request.session["email"])
return render(request , "./uprofile/user.html" , context = {"projects":project.objects.filter(uid = userinfo.uid) ,
"userinfo":userinfo , "profile": signup_user.objects.get(Email = request.session["email"]).profilepic, "email":uname , "username":usern})
# return render(request , "./uprofile/profile.html" , context = {"pro_del":deletedp,"otherpros":otherprojects})
def upload(request):
if request.method=='POST':
uname = ""
try:
uname = request.session["email"].split("@")[0]
usern = request.session["username"]
except:
uname = "You are not yet logged in."
return redirect("/login/")
else:
project.objects.create(project_name = request.POST['project_name'] ,
project_description = request.POST["project_description"] , uid = signup_user.objects.get(Email = request.session["email"]), file = request.FILES["file"])
print(request.session["username"])
return redirect("profile/")
else:
print("Null and void")
return render(request , './upload_pro/upload.html' , context = {"form":uploadform})
<file_sep>/gallery/models.py
from django.db import models
from signup.models import signup_user
# Create your models here.
class HiQGallery(models.Model):
id = models.AutoField(primary_key = True)
uid = models.ForeignKey(signup_user , on_delete = models.CASCADE)
imagedescription = models.CharField(max_length = 255)
image = models.FileField(max_length = 255)
<file_sep>/comments/models.py
from django.db import models
# Create your models here.
from signup.models import signup_user
from Feeds.models import feeds_list
class comment_list(models.Model):
cid = models.AutoField(primary_key = True)
uid = models.ForeignKey(signup_user,on_delete = models.CASCADE)
fid = models.ForeignKey(feeds_list , on_delete = models.CASCADE)
comments = models.TextField(max_length=255)
comment_post_time = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = "comments"
def __str__(self):
return self.comments
<file_sep>/events/urls.py
from django.conf.urls import url
from . import views
app_name = "events"
urlpatterns = [
url("^$" , views.events , name = "events"),
url("add_event/" , views.add_event , name = "add_event"),
]
<file_sep>/uprofile/views.py
from django.shortcuts import render,redirect
from upload_pro.models import project
from signup.models import signup_user
from events.models import events_list
import datetime
from django.http import HttpResponse
# Create your views here.
def profile_viewer(request):
uname = ""
events_list.objects.filter(eventup_date__lte = datetime.datetime.now()).delete()
try:
statusdecision = signup_user.objects.get(Email = request.session["email"]).logstatus
except:
uname = "You are not yet logged in."
return redirect("/login/")
else:
if not statusdecision:
uname = "You are not yet logged in."
print(statusdecision)
return redirect("/login/")
else:
uname = request.session["email"].split("@")[0]
usern = request.session["username"]
userinfo = signup_user.objects.get(Email = request.session["email"])
return render(request , "./uprofile/user.html" , context = {"projects":project.objects.filter(uid = userinfo.uid) ,
"userinfo":userinfo , "profile": signup_user.objects.get(Email = request.session["email"]).profilepic, "email":uname , "username":usern})
def update(request):
if request.method == "POST":
fname = request.POST["fname"]
lname = request.POST["lname"]
mail = request.POST["email"]
phone = request.POST["pnumber"]
uobject = signup_user.objects.get(Email = request.session["email"])
uobject.First_Name = fname
uobject.Second_name = lname
uobject.Email = mail
uobject.Phone_Number = phone
try:
img = request.FILES["imq"]
except Exception as e:
pass
else:
uobject.profilepic = img
try:
request.POST["password"][0]
except Exception as e:
pass
else:
uobject.Password = request.POST["password"]
request.session["email"] = mail
request.session["username"] = fname
# uobject.First_Name
uobject.save()
return redirect("/profile/")
<file_sep>/comments/admin.py
from django.contrib import admin
# Register your models here.
from .models import comment_list
class comments_displ(admin.ModelAdmin):
models = "comment_list"
list_display = ["cid","uid","fid","comments","comment_post_time"]
admin.site.register(comment_list , comments_displ)
<file_sep>/home/models.py
from django.db import models
# Create your models here.
class home_data(models.Model):
pass
class Meta:
db_table = "home_resources"
<file_sep>/upload_pro/admin.py
from django.contrib import admin
# Register your models here.
from .models import project
class project_disp(admin.ModelAdmin):
model = project
list_display = ["uid","project_name","project_description" ,"file","uploadtime"]
admin.site.register(project,project_disp)
<file_sep>/suggestions/migrations/0001_initial.py
# Generated by Django 3.0.2 on 2020-01-31 11:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('signup', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='suggetion_box',
fields=[
('sid', models.AutoField(primary_key=True, serialize=False)),
('suggestion', models.CharField(default='', max_length=255)),
('suggestuser', models.ForeignKey(default=1, max_length=50, on_delete=django.db.models.deletion.CASCADE, to='signup.signup_user')),
],
options={
'db_table': 'suggestions',
},
),
migrations.CreateModel(
name='public_suggetion_box',
fields=[
('sid', models.AutoField(primary_key=True, serialize=False)),
('suggestion', models.CharField(default='', max_length=255)),
('suggestuser', models.ForeignKey(default=1, max_length=50, on_delete=django.db.models.deletion.CASCADE, to='signup.signup_user')),
],
options={
'db_table': 'psuggetions',
},
),
]
<file_sep>/Feeds/models.py
from django.db import models
from signup.models import signup_user
# Create your models here.
class feeds_list(models.Model):
Fid = models.AutoField(primary_key = True)
uid = models.ForeignKey(signup_user , on_delete = models.CASCADE)
feed = models.CharField(max_length = 1255)
post_time = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = "feeds"
def _str__(self):
return self.feed
<file_sep>/signup/migrations/0001_initial.py
# Generated by Django 3.0.2 on 2020-01-31 11:46
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='signup_user',
fields=[
('uid', models.AutoField(primary_key=True, serialize=False)),
('First_Name', models.CharField(max_length=30)),
('Second_name', models.CharField(max_length=30)),
('Password', models.CharField(max_length=255)),
('Email', models.EmailField(max_length=30, unique=True)),
('Phone_Number', models.CharField(max_length=30)),
('profilepic', models.ImageField(default='None', upload_to='')),
('logstatus', models.BooleanField(default=False, max_length=3)),
('admin_status', models.BooleanField(default=0, max_length=3)),
],
options={
'db_table': 'users',
},
),
]
<file_sep>/login/urls.py
from django.conf.urls import url
from . import views
app_name = "login"
urlpatterns = [
url("^$" , views.login , name = "login"),
url("^<slug:param>/" , views.login , name = "login"),
url("(?P<param>[\w]*)/" , views.login , name = "login"),
]
<file_sep>/suggestions/urls.py
from django.conf.urls import url
from . import views
app_name = "suggestions"
urlpatterns = [
url("^$" , views.suggest , name = "suggest"),
url("^delete/(?P<project_id>[\w]*)/" , views.delete_suggestion , name = "delete"),
url("^suggestions/(?P<sugid>[\d]*)" , views.post_publoc , name = "suggestion")
]
<file_sep>/events/models.py
from django.db import models
# Create your models here.
from signup.models import signup_user
class events_list(models.Model):
event_id = models.AutoField(primary_key = True)
event_organizer = models.ForeignKey(signup_user , on_delete = models.CASCADE)
event_description = models.TextField(max_length = 255)
event_venue = models.TextField(max_length = 255)
eventup_date = models.DateTimeField(max_length = 30)
event_post_date = models.DateTimeField(auto_now_add=True)
# eventDate = models.DateField(max_length = 40)
class Meta:
db_table = "events"
def __str__(self):
return self.event_description
<file_sep>/home/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import loginfrm
from events.models import events_list
import datetime
from django.utils import timezone
from signup.models import signup_user
from django.contrib.auth.hashers import make_password
# Create your views here.
def home(request):
try:
events_list.objects.filter(eventup_date__lte = timezone.now()).delete()
pass
except Exception as e:
pass
else:
pass
form = loginfrm()
if "username" in request.session:
lcontrol = True
else:
lcontrol = False
return render (request , "./home/index.html" , context = {"form": form , "loginshow":lcontrol})
def handle404(request ,exception):
return HttpResponse("Hello world")
<file_sep>/Feeds/admin.py
from django.contrib import admin
from .models import feeds_list
class feed_displ(admin.ModelAdmin):
model = "feeds_list"
list_display = ["Fid","uid", "feed" , "post_time"]
admin.site.register(feeds_list , feed_displ)
<file_sep>/hq/views.py
from django.shortcuts import render
from django.http import HttpResponse
def handle404(request , exception):
return render(request , "./error404.html".format(exception))
<file_sep>/hq/urls.py
from django.contrib import admin
from django.conf.urls import url,include
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url("" , include("home.urls")),
url('admin/', admin.site.urls),
url("login/" , include("login.urls")),
url("signup/" , include("signup.urls")),
url("events/" , include("events.urls")),
url("profile/" , include("uprofile.urls")),
url("upload/" , include("upload_pro.urls")),
url("logout/" , include("logout.urls")),
url("gallery/" , include("gallery.urls")),
url("Feeds/" , include("Feeds.urls")),
url("comments/" , include("comments.urls")),
url("suggestions/" , include("suggestions.urls")),
]+static(settings.MEDIA_URL , document_root = settings.MEDIA_ROOT)
handler404 = views.handle404
<file_sep>/login/forms.py
from django import forms
from signup.models import signup_user
class loginfrm(forms.ModelForm):
class Meta:
model = signup_user
fields = ("First_Name" , "Second_name" , "<PASSWORD>" , "Email" ,"Phone_Number")
<file_sep>/suggestion/views.py
from django.shortcuts import render,redirect
from .forms import sugfrm
from django.http import HttpResponse
from .models import suggetion_box , public_suggetion_box
from signup.models import signup_user
def suggest(request):
try:
suggestion_access = request.session['email']
except Exception as e:
return redirect("/login/")
else:
frm = sugfrm()
suggestion_access = signup_user.objects.get(Email = suggestion_access)
suggestP = public_suggetion_box.objects.all()
suggestion_data = suggetion_box.objects.all()
if request.method=="POST":
errorlog = ""
try:
uname = request.POST['uname']
except Exception as e:
suggetion_box.objects.create(suggestion = request.POST["suggestion"])
return redirect("/suggestions/")
else:
try:
uid = suggestion_access.uid
except Exception as e:
errorlog = "No user with your identity is n our system"
return redirect("/suggestions/")
# return render( request, "suggestion/suggest.html" , context = {"signup":frm , "errorlog":errorlog , "access":suggestion_access ,"suggestion_data":suggestion_data})
else:
suggetion_box.objects.create(suggestuser_id = uid , suggestion = request.POST["suggestion"])
return redirect("/suggestions/")
# return render( request, "suggestion/suggest.html" , context = {"signup":frm , "errorlog":errorlog , "access":suggestion_access})
else:
return render( request, "suggestion/suggest.html" , context = {"signup":frm , "access":suggestion_access , "suggestion_data":suggestion_data , "suggestP":suggestP})
def post_publoc(request , sugid):
try:
psdata = suggetion_box.objects.get(sid = sugid)
public_suggetion_box.objects.create(suggestuser_id = psdata.suggestuser_id, suggestion = psdata.suggestion)
except Exception as e:
return redirect("/suggestions/")
else:
return redirect("/suggestions/")
def delete_suggestion(request , project_id):
suggetion_box.objects.get(sid = project_id).delete()
return redirect("/suggestions/")
<file_sep>/gallery/urls.py
from django.contrib import admin
from django.conf.urls import url,include
from . import views
app_name ="gallery"
urlpatterns = [
url("^$" , views.photos , name = "view_photo"),
url("galleryup/" , views.uploadphotos , name = "upload_photo"),
]
<file_sep>/requirements.txt
asgiref==3.2.3
certifi==2019.11.28
chardet==3.0.4
DateTime==4.3
dj-database-url==0.5.0
Django==3.0.2
django-heroku==0.3.1
gunicorn==20.0.4
idna==2.8
mysqlclient==1.4.6
Pillow==7.0.0
pipenv==2018.11.26
psycopg2==2.8.4
psycopg2-binary==2.8.4
psycopg2-pgevents==0.1.1
pytz==2019.3
requests==2.22.0
sqlparse==0.3.0
urllib3==1.25.8
virtualenv==16.7.9
virtualenv-clone==0.5.3
whitenoise==5.0.1
zope.interface==4.7.1
<file_sep>/suggestion/models.py
from django.db import models
from signup.models import signup_user
class suggetion_box(models.Model):
sid = models.AutoField(primary_key = True)
suggestuser = models.ForeignKey(signup_user , default = 1, max_length = 50, on_delete = models.CASCADE)
suggestion = models.CharField(max_length = 255 , default="")
class Meta:
db_table = "suggestions"
class public_suggetion_box(models.Model):
sid = models.AutoField(primary_key = True)
suggestuser = models.ForeignKey(signup_user , default = 1, max_length = 50, on_delete = models.CASCADE)
suggestion = models.CharField(max_length = 255 , default="")
class Meta:
db_table = "psuggetions"
<file_sep>/events/views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import eventfrm
from .models import events_list
import datetime
from django.utils import timezone
# Create your views here.
from signup.models import signup_user
def events(request):
try:
statusdecision = signup_user.objects.get(Email = request.session["email"]).logstatus
request.session['email']
except Exception as e:
lcontrol = False
uname = "You are not yet logged in."
return redirect("/login/")
else:
lcontrol = True
if not statusdecision:
uname = "You are not yet logged in."
print(statusdecision)
return redirect("/login/")
else:
try:
events_list.objects.filter(eventup_date__lte = timezone.now()).delete()
except Exception as e:
pass
event_var = events_list.objects.all().order_by("eventup_date")
# signup_user.objects.get()
try:
sess = request.session["username"]
except:
sess = ""
return render(request , "./events/events.html" , context = {"events":event_var, "username":sess , "loginshow":lcontrol})
def add_event(request):
errorlog = ""
print("{}\n\n\n\n\n\n\n\n".format(request.POST['description']))
if request.method=='POST':
try:
uname = request.session["email"]
except:
errorlog = "Please login to continue"
uname = "Anornymous"
return render(request , "./events/addevents.html" , context = {"events":eventfrm,"errorlog":errorlog})
else:
events_list.objects.create(event_organizer_id = signup_user.objects.get(Email = request.session["email"]).uid,
event_venue = request.POST['location'], event_description = request.POST['description'],
eventup_date = request.POST["eventup_date"])
return redirect("/events/")
else:
return render(request , "./events/addevents.html" , context = {"events":eventfrm})
<file_sep>/upload_pro/migrations/0001_initial.py
# Generated by Django 3.0.2 on 2020-01-31 11:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('signup', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='project',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('project_name', models.CharField(max_length=30)),
('category', models.CharField(choices=[('Web', 'Website'), ('Android app', 'Android app'), ('Art & poem', 'Art & poem'), ('Not listed', 'Not listed')], max_length=30, null=True)),
('project_description', models.TextField(max_length=255)),
('file', models.FileField(upload_to='')),
('uploadtime', models.DateTimeField(auto_now_add=True, null=True)),
('uid', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='signup.signup_user')),
],
options={
'db_table': 'projects',
},
),
]
<file_sep>/uprofile/apps.py
from django.apps import AppConfig
class UprofileConfig(AppConfig):
name = 'uprofile'
| 88bbf27deb0b2a1b96985c0a94ff0b7a3d012820 | [
"Python",
"Text"
] | 49 | Python | Code-Community99/Hiq-django | af62622648ad88f6e8d94e86a8dc5d6660e3bbe2 | e8efb7d63bd4fc0bc8e2af193fdec9aaab0975b0 |
refs/heads/main | <file_sep>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from objective import analytic
from selection import selection
from crossover import crossover
from mutation import mutation
#----------------------------------------------------------------------------------------------------------------------#
# Parameters
#----------------------------------------------------------------------------------------------------------------------#
n = 10 # Dimension of optimization problem (num of parameters in objective function)
pop_size = 100 # Population size
min_init = -10 # Minimum value an allele can be initialized with
max_init = 10 # Maximum value an allele can be initialized with
eps = 1e-5 # Convergance tolerance
F = 1 # Scale factor
max_gens = 1000 # Max number of generations
#----------------------------------------------------------------------------------------------------------------------#
# Population (Agents) Initialization
#----------------------------------------------------------------------------------------------------------------------#
# Random init
population = np.array([np.random.uniform(min_init, max_init, size=n) for i in range(pop_size)])
# Function evaluations for eaach
fitness = np.array([analytic.ackley(population[i], n=n) for i in range(pop_size)])
#----------------------------------------------------------------------------------------------------------------------#
# Differential Optimization
#----------------------------------------------------------------------------------------------------------------------#
# Starting point
best = np.amin(fitness)
generation = 0
# Save best solution and population average each generation
best_vec = [best]
ave_vec = [np.average(fitness)]
# Loop until solution within tolerance or max generations
while (best > eps) and (generation < max_gens):
# Increment generation count
generation += 1
# Loop over agents (indexes)
for i in range(len(population)):
#--------------------------------------------------------------------------------------------------------------#
# Agent Selection (random uniform)
#--------------------------------------------------------------------------------------------------------------#
parents = selection.uniform(population, i)
#--------------------------------------------------------------------------------------------------------------#
# Mutation (differential)
#--------------------------------------------------------------------------------------------------------------#
offspring = mutation.differential(parents, F)
#--------------------------------------------------------------------------------------------------------------#
# Survival (elitist)
#--------------------------------------------------------------------------------------------------------------#
# New function evaluation
f_offspring = analytic.ackley(offspring, n=n)
# Apply deterministic elite selection between current agent and new offspring
selection.elitist(population, fitness, i, offspring, f_offspring)
#------------------------------------------------------------------------------------------------------------------#
# End of generation
#------------------------------------------------------------------------------------------------------------------#
# Print some stats
print('Generation: {:4d} \tPopulation Average: {:7.4f} \tBest Function Value: {:.5f}'.format(generation,
np.average(fitness),
best))
# Check for solution
best = np.amin(fitness)
# Update lists of best / averages
best_vec.append(best)
ave_vec.append(np.average(fitness))
#----------------------------------------------------------------------------------------------------------------------#
# Outputs
#----------------------------------------------------------------------------------------------------------------------#
# Solution print
print('Solution: {:s}'.format(np.array2string(population[np.argmin(fitness)])))
# Algorithm performance
plt.figure(1)
plt.plot(np.arange(generation+1), ave_vec, label='population average')
plt.plot(np.arange(generation+1), best_vec, label='best solution')
plt.legend(fontsize=14)
plt.xlabel('Generation', fontsize=14)
plt.show()<file_sep>import numpy as np
def uniform(population, idx, num=3):
'''
This function selects num unique parents from the population. It also ensures that none of the parents selected
is the agent in the population located at idx.
@param: population (m by n numpy array) - collection of m agents of dimension n
@param: idx (int) - index of agent not to include in random selection
@param: num (int) - number of random selections (default 3 as required by differential evolution)
'''
# dummy population which does not contain agent at idx
dummy_pop = np.delete(population, idx, axis=0)
# Select three unique random agents from dummy pop (uniform random)
idxes = np.random.choice(len(dummy_pop), size=num, replace=False)
return [dummy_pop[i] for i in idxes]
def elitist(population, fitness, idx, offspring, f):
'''
This function performs deterministic elitist selection between a new offspring with function evaluation f with an
existing agent in the population at idx. If the offspring is an improvement, it replaces the old agent, otherwise no
change is made.
@param: population (m by n numpy array) - collection of m agents of dimension n
@param: fitness (m by 1 numpy array) - corresponding fitness values of each agent in population
@param: idx (int) - index of agent in population being compared
@param: offspring (n x 1 numpy array) - new candidate offspring
@param: f (float) - function value of offspring
'''
if (f <= fitness[idx]):
population[idx] = offspring
fitness[idx] = f
<file_sep>import numpy as np
def ackley2D(x, y):
f = -20 * np.exp(-0.2 * np.sqrt(0.5 * (x**2 + y**2) )) - np.exp( 0.5*(np.cos(2*np.pi*x) + np.cos(2*np.pi*y)) ) + np.e + 20
return f
def ackley(x, n=2):
# Evaluate the sums
s1, s2 = 0, 0
for i in range(n):
s1 += x[i]**2
s2 += np.cos(2*np.pi*x[i])
return -20 * np.exp( -0.2 * np.sqrt(s1 / n)) - np.exp(s2 / n) + 20 + np.e
<file_sep>import numpy as np
def uniform(parent1, parent2, p=0.5):
# Sanity check
assert(len(parent1)==len(parent2))
# Initialize offspring
offspring = 0 * parent1
for i in range(len(parent1)):
# Take allele from parent1
if (np.random.uniform() < p):
offspring[i] = parent1[i]
# Take allele from parent2
else:
offspring[i] = parent2[i]
return offspring
<file_sep># Differential Evolution Global Numerical Optimizer
This project is a differential evolution algorithm for numerically solving the global minima of non-linear, discontinuous, noisy, and dynamic objective functions. It is bench-tested with the Ackley function in n-dimensions. The design is standard for differential evoltuion:
Agent selection: Unique random uniform <br />
Mutation: Differential <br />
Survival: Deteminstic Elite <br />
<file_sep>from crossover import crossover
def differential(agents, rate):
# Base vector
base = agents[0]
# Perturbation vector
p = rate * (agents[1] - agents[2])
# Mutant vector
M = base + p
# Trial vector (offspring)
T = crossover.uniform(base, M)
return T | e5dde6976ea7c40e4cd3408adb67036d603be6f3 | [
"Markdown",
"Python"
] | 6 | Python | haydenbanting/DE-Global-Numerical-Optimizer | e0970a01b5c1e7d5b5452d897d58ae0d2364f43e | 1e01b7d914f0564fc1cf70bf2f0a60a631c5b66e |
refs/heads/master | <repo_name>Zenleaf/purescript-hareactive<file_sep>/src/Hareactive/Dom.js
const H = require("@funkia/hareactive");
exports._streamFromEvent = H.streamFromEvent;
| 4c078e45978eedd73d66aef0f1495a10c030db64 | [
"JavaScript"
] | 1 | JavaScript | Zenleaf/purescript-hareactive | 39fcb4f65f37d825cafe59f569c2f0a7f2243b12 | 95d5a1bc13d67acc9eab8d2886541f4a2d223aae |
refs/heads/master | <repo_name>simboben/source<file_sep>/config/routes.rb
Rails.application.routes.draw do
#active admin urls
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
#categories controller
resources :categories
#items controller
resources :items
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
# a user could sign up multiple times
resources :users
#users can only make one session
resource :session
get "about", to: "pages#about"
root "pages#home"
end
<file_sep>/app/models/item.rb
class Item < ApplicationRecord
has_many :category_items
has_many :categories, through: :category_items
validates :title, presence: true
mount_uploader :image, ImageUploader
end
<file_sep>/app/admin/item.rb
ActiveAdmin.register Item do
permit_params :title, :description, :image, category_ids: []
form do |f|
f.inputs do
f.input :title
f.input :description
f.input :image
f.input :categories, as: :check_boxes, collection: Category.order("title asc")
end
f.actions
end
end
<file_sep>/app/helpers/items_helper.rb
module ItemsHelper
def format_categories(categories)
links = categories.map do |cat|
link_to cat.title, category_path(cat)
end
links.to_sentence.html_safe
end
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
#make current user_available to views
helper_method :current_user, :is_logged_in?
#run this on every page and action
before_action :current_user
def current_user
if is_logged_in?
@current_user = User.find(session[:user_id])
else
@current_user = nil
end
@current_user
end
def is_logged_in?
session[:user_id].present?
end
def force_login
unless is_logged_in?
flash[:error] = "You are not logged in"
redirect_to new_user_path
end
end
end
<file_sep>/config/initializers/carrierwave.rb
CarrierWave.configure do |config|
config.fog_provider = 'fog/aws'
config.fog_credentials = {
provider: 'AWS', # required
aws_access_key_id: Rails.application.credentials.aws[Rails.env.to_sym][:aws_key], # required unless using use_iam_profile
aws_secret_access_key: Rails.application.credentials.aws[Rails.env.to_sym][:aws_password],
region: Rails.application.credentials.aws[Rails.env.to_sym][:aws_region], # required unless using use_iam_profile
}
config.fog_directory = Rails.application.credentials.aws[Rails.env.to_sym][:aws_bucket] # required
config.fog_public = false # optional, defaults to true
config.fog_attributes = { cache_control: "public, max-age=#{365.days.to_i}" } # optional, defaults to {}
end
<file_sep>/app/controllers/items_controller.rb
class ItemsController < ApplicationController
before_action :force_login
def index
# if there's a search, filter!!!
# if not, show all!
if params[:q].present?
# this is where we search!
@items = Item.where("lower(title) LIKE ?", "%" + params[:q].downcase + "%")
else
# show all
@items = Item.all
end
end
def show
@item = Item.find(params[:id])
end
end
| 576e1463c9cc7cc3934b66d1b6c8f723932fe4ef | [
"Ruby"
] | 7 | Ruby | simboben/source | 666cdfad4cc4a9428c4f7523451e685a04b2f05c | d84d604da59c8d5bfeafe1d35b798ab73febab2f |
refs/heads/master | <repo_name>konGiann/Pang<file_sep>/Pang!/Assets/Scripts/CharacterController2D.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CharacterController2D : MonoBehaviour
{
// public editor properties
public float moveSpeed = 3f;
public int playerHealth = 1;
public bool playerCanMove = true;
// player tracking
bool _facingRight = true;
bool _isRunning = false;
// player motion
float horizontalMovement;
// components references
Transform _transform;
Rigidbody2D _rb;
Animator _anim;
SoundManager _sound;
private void Awake()
{
_transform = GetComponent<Transform>();
_rb = GetComponent<Rigidbody2D>();
_sound = SoundManager.sm;
_anim = GetComponent<Animator>();
if (_anim == null)
Debug.LogWarning("There is no Animator attached to player object");
}
// Update is called once per frame
void Update()
{
// get player input on the X axis
horizontalMovement = Input.GetAxisRaw("Horizontal");
if(horizontalMovement != 0)
{
_isRunning = true;
}
else
{
_isRunning = false;
}
_anim.SetBool("Running", _isRunning);
}
private void LateUpdate()
{
Vector3 localScale = _transform.localScale;
// determine which direction the player is facing and flip sprite accordingly
if (horizontalMovement > 0 && !_facingRight)
{
FlipPlayer();
}
else if (horizontalMovement < 0 && _facingRight)
{
FlipPlayer();
}
}
private void FixedUpdate()
{
// move player
_rb.velocity = new Vector2((horizontalMovement * moveSpeed) * Time.fixedDeltaTime, 0);
}
// respawn player
public void RespawnPlayer()
{
_anim.SetTrigger("Respawn");
// spawn player at starting position
transform.position = new Vector3(0f, 0, 0f);
}
IEnumerator KillPlayer()
{
_sound.audioController.PlayOneShot(_sound.LostLife);
// pause game play death animation and then resume
GameManager.gm.PauseGame();
_anim.SetTrigger("Death");
yield return new WaitForSecondsRealtime(2f);
GameManager.gm.ResumeGame();
// reset game stats
GameManager.gm.ResetLevel();
}
public void ApplyDamage(int damage)
{
playerHealth -= damage;
if(playerHealth <= 0)
{
StartCoroutine(KillPlayer());
}
}
// flip sprite
private void FlipPlayer()
{
_facingRight = !_facingRight;
transform.Rotate(0f, 180f, 0f);
}
}
<file_sep>/Pang!/Assets/Scripts/PlayerPrefManager.cs
using UnityEngine;
public static class PlayerPrefManager
{
public static int GetLives()
{
if (PlayerPrefs.HasKey("Lives"))
return PlayerPrefs.GetInt("Lives");
else
return 0;
}
public static void SetLives(int lives)
{
PlayerPrefs.SetInt("Lives", lives);
}
public static int GetScore()
{
if (PlayerPrefs.HasKey("Score"))
return PlayerPrefs.GetInt("Score");
else
return 0;
}
public static void SetScore(int score)
{
PlayerPrefs.SetInt("Score", score);
}
public static int GetHighscore()
{
if (PlayerPrefs.HasKey("Highscore"))
return PlayerPrefs.GetInt("Highscore");
else
return 0;
}
public static void SetHighscore(int highscore)
{
PlayerPrefs.SetInt("Highscore", highscore);
}
// Save player stats and keep them when moving to the next level
public static void SavePlayerStats(int lives, int score, int highscore)
{
PlayerPrefs.SetInt("Lives", lives);
PlayerPrefs.SetInt("Score", score);
PlayerPrefs.SetInt("Highscore", highscore);
}
public static void ResetPlayerState(int startingLives)
{
Debug.Log("Reseting player stats");
PlayerPrefs.SetInt("Lives", startingLives);
PlayerPrefs.SetInt("Score", 0);
}
}
<file_sep>/Pang!/Assets/Scripts/MainMenuManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
public class MainMenuManager : MonoBehaviour
{
public GameObject HowToPlayPanel;
bool isHowToPlayPanelActive;
public void StartNewGame()
{
PlayerPrefManager.ResetPlayerState(3);
StartCoroutine(LoadFirstLevel());
}
public void QuitGame()
{
Application.Quit();
}
public void HowToPlay()
{
HowToPlayPanel.SetActive(!isHowToPlayPanelActive);
isHowToPlayPanelActive = !isHowToPlayPanelActive;
}
IEnumerator LoadFirstLevel()
{
yield return new WaitForSeconds(1f);
SceneManager.LoadScene("Level 1");
}
}
<file_sep>/Pang!/Assets/Editor/GameManagerEditor.cs
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(GameManager))]
public class GameManagerEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
GameManager gm = (GameManager)target;
if(GUILayout.Button("Add Big Balloon"))
{
Instantiate(gm.BalloonsPrefabs[0], new Vector3(0, 4, 0), gm.BalloonsPrefabs[0].transform.rotation);
}
if (GUILayout.Button("Add Medium Balloon"))
{
Instantiate(gm.BalloonsPrefabs[1], new Vector3(0, 4, 0), gm.BalloonsPrefabs[0].transform.rotation);
}
if (GUILayout.Button("Add Small Balloon"))
{
Instantiate(gm.BalloonsPrefabs[2], new Vector3(0, 4, 0), gm.BalloonsPrefabs[0].transform.rotation);
}
if (GUILayout.Button("Add Tiny Balloon"))
{
Instantiate(gm.BalloonsPrefabs[3], new Vector3(0, 4, 0), gm.BalloonsPrefabs[0].transform.rotation);
}
if(GUILayout.Button("Remove ALL Balloons from Scene."))
{
GameObject[] allBalloons = GameObject.FindGameObjectsWithTag("Balloon");
foreach (var balloon in allBalloons)
{
DestroyImmediate(balloon);
}
}
}
}
<file_sep>/Pang!/Assets/Scripts/PowerUp.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerUp : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag == "Player")
{
other.gameObject.GetComponent<PlayerShoot>().ActiveWeapon = PlayerShoot.Weapons.Bullet;
// play sound
Destroy(gameObject);
}
}
}
<file_sep>/Pang!/Assets/Scripts/GameStats.cs
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameStats : MonoBehaviour
{
public TextMeshProUGUI PlayerScore;
public TextMeshProUGUI BestScore;
private void Start()
{
SoundManager.sm.PlayMusicForLevel(SceneManager.GetActiveScene());
PlayerScore.text += PlayerPrefManager.GetScore().ToString();
BestScore.text += PlayerPrefManager.GetHighscore().ToString();
}
}
<file_sep>/Pang!/Assets/Scripts/Bounce.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bounce : MonoBehaviour
{
public int BounceForce = 10000;
public int BalloonDirection = 1;
public float ConstantSpeed = 0.1f;
public float SmoothingFactor = 0.1f;
Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector3(2, 0, 0);
Debug.Log("Starting velocity: " + rb.velocity);
}
private void Start()
{
//rb.velocity = new Vector3(2, 0, 0);
}
private void FixedUpdate()
{
if(rb.velocity.x < 2 && rb.velocity.x >= 0)
{
rb.velocity = new Vector3(2, 0, 0);
}
else if(rb.velocity.x < 0 && rb.velocity.x > -2)
{
rb.velocity = new Vector3(-2, 0, 0);
}
Debug.Log(rb.velocity);
}
private void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag == "Floor")
{
//rb.velocity = Vector2.zero;
rb.AddForce(Vector2.up * BounceForce);
}
}
}
<file_sep>/Pang!/Assets/Scripts/SoundManager.cs
using UnityEngine;
using UnityEngine.SceneManagement;
public class SoundManager : MonoBehaviour
{
public static SoundManager sm;
[Header("Main Menu Sounds")]
public AudioClip MainMenuTrack;
public AudioClip MenuItemToggle;
[Header("Cyber City Tracks")]
public AudioClip CyberCityTrack_1;
[Header("Dark City Tracks")]
public AudioClip DarkCityTrack_1;
[Header("Level SFX")]
public AudioClip BallExplosion;
public AudioClip LostLife;
public AudioClip NewHighscore;
public AudioClip CountDownBeep;
public AudioClip CountDownOver;
public AudioClip LevelCompleted;
public AudioClip ComboBroke;
public AudioClip GameOverMusic;
public AudioClip GameWin;
[HideInInspector]
public AudioSource audioController;
// private fields
Scene currentScene;
void Awake()
{
if (sm == null)
sm = GetComponent<SoundManager>();
DontDestroyOnLoad(gameObject);
// get current screen
currentScene = SceneManager.GetActiveScene();
// add an audiosource controller
audioController = gameObject.AddComponent<AudioSource>();
// start music for main menu
PlayMusicForLevel(currentScene);
// loop music
audioController.loop = true;
}
// play the music clip assigned for each level when the level loads
public void PlayMusicForLevel(Scene scene)
{
switch (scene.name)
{
case "MainMenu":
audioController.Stop();
audioController.clip = MainMenuTrack;
audioController.Play();
break;
case "Level 1":
audioController.Stop();
audioController.clip = CyberCityTrack_1;
audioController.Play();
break;
case "Level 2":
audioController.Stop();
audioController.clip = DarkCityTrack_1;
audioController.Play();
break;
case "GameOver":
audioController.Stop();
audioController.clip = GameOverMusic;
audioController.Play();
break;
default:
break;
}
}
// menu items sfx
public void PlayMenuToggleSound()
{
audioController.PlayOneShot(MenuItemToggle);
}
public void PlayMenuSelectedSound()
{
audioController.PlayOneShot(MenuItemToggle);
}
}
<file_sep>/Pang!/Assets/Scripts/AnchorController.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnchorController : MonoBehaviour
{
public float BulletSpeed;
public float BulletDamage = 100;
public GameObject FloatingText;
// Rigidbody2D rb;
SoundManager _sound;
Vector3 expand; // to help up make anchor expand vertically
bool isFullyExpanded; // check if it reached the end
bool destroyObject;
private void Awake()
{
//rb = GetComponent<Rigidbody2D>();
_sound = SoundManager.sm;
}
// Start is called before the first frame update
void Start()
{
//rb.velocity = transform.up * BulletSpeed;
}
private void Update()
{
if (!isFullyExpanded)
{
expand = transform.localScale;
expand.y += 35f * Time.deltaTime;
transform.localScale = expand;
}
if (transform.localScale.y >= 20 && !destroyObject)
{
isFullyExpanded = true;
destroyObject = true;
Destroy(gameObject, 1.5f);
}
}
private void LateUpdate()
{
// destroy bullet even if it is not destroyed on collision and reset combo counter
if (transform.position.y >= 9)
{
// play break combo effect if combo is active
if (GameManager.gm.comboCounter > 0)
{
SoundManager.sm.audioController.PlayOneShot(SoundManager.sm.ComboBroke);
}
// reset combo
GameManager.gm.comboCounter = 0;
// reset combo UI
GameManager.gm.UIComboCounter.text = "";
// flawless victory is impossible now
GameManager.gm.flawlessVictory = false;
Destroy(gameObject);
}
}
private void OnTriggerEnter2D(Collider2D otherObject)
{
if (otherObject.tag == "Balloon")
{
// play ball split sound
_sound.audioController.PlayOneShot(_sound.BallExplosion);
// damage ball
otherObject.GetComponent<BalloonController>().DamageBall(BulletDamage);
// add points to player's score
// apply bonus damage based on the y position of the ball
otherObject.GetComponent<BalloonController>().ScoreValue += (int)Math.Ceiling(transform.position.y);
GameManager.gm.AddScore(otherObject.GetComponent<BalloonController>().ScoreValue);
// pop up points on canvas
var FloatingObj = Instantiate(FloatingText, transform.position, Quaternion.identity);
FloatingObj.GetComponent<FloatingTextController>().Init(1f, "+" + otherObject.GetComponent<BalloonController>().ScoreValue.ToString());
GameManager.gm.comboCounter++;
GameManager.gm.timeHit = Time.time;
if (GameManager.gm.hitsToWin <= 0)
{
GameManager.gm.StartCoroutine(GameManager.gm.LoadNextLevel());
}
// destroy bullet
Destroy(gameObject);
}
}
}
<file_sep>/Pang!/Assets/Scripts/BalloonController.cs
using UnityEngine;
public class BalloonController : MonoBehaviour
{
[Range(-1f, 1f)]
[Tooltip("Direction of the balloon on the x axis (left or right)")]
public int BalloonDirection;
public float Health = 100;
public int ScoreValue = 10;
public string BalloonType;
public int DamageToPlayer = 100;
public GameObject BallToSpawnOne;
public GameObject BallToSpawnTwo;
public Transform BallOnePosition;
public Transform BallTwoPosition;
private Rigidbody2D _rigidbody2D;
private void Awake()
{
// get component references
_rigidbody2D = GetComponent<Rigidbody2D>();
}
void Start()
{
_rigidbody2D.AddForce(new Vector2((float)BalloonDirection * 2000, 0));
}
public void DamageBall(float damage)
{
Health -= damage;
if(Health <= 0)
{
if (BalloonType != "Tiny")
{
SpawnBalls();
}
Destroy(gameObject);
// reduce hits needed to win the level
GameManager.gm.hitsToWin--;
// check if it was the last balloon to win the level
// we check this here to avoid using it in the update
}
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Player")
{
other.gameObject.GetComponent<CharacterController2D>().ApplyDamage(DamageToPlayer);
}
}
public void SpawnBalls()
{
Instantiate(BallToSpawnOne, BallOnePosition.position, BallOnePosition.rotation);
BallToSpawnOne.GetComponent<BalloonController>().BalloonDirection = 1;
Instantiate(BallToSpawnTwo, BallTwoPosition.position, BallTwoPosition.rotation);
BallToSpawnTwo.GetComponent<BalloonController>().BalloonDirection = -1;
}
}
<file_sep>/Pang!/Assets/Scripts/FloatingTextController.cs
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class FloatingTextController : MonoBehaviour
{
public float DestroyAfterSeconds = 1f;
public TextMeshProUGUI TextToShow;
[Range(0f, 10f)]
public float MovementSpeed = 6;
Vector2 movement;
public void Init(float time, string text)
{
DestroyAfterSeconds = time;
TextToShow.text = text;
}
private void Awake()
{
movement = new Vector2(transform.position.x, transform.position.y);
}
private void Update()
{
movement.y += 0.1f * MovementSpeed * Time.smoothDeltaTime;
transform.position = movement;
}
private void Start()
{
StartCoroutine(DestroyObjectAfterSeconds(DestroyAfterSeconds));
}
private IEnumerator DestroyObjectAfterSeconds(float seconds)
{
yield return new WaitForSeconds(seconds);
Destroy(gameObject);
}
}
<file_sep>/Pang!/Assets/Scripts/GameManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public static GameManager gm;
[Header("Game Settings")]
public int PlayerLives = 3;
public int PlayerScore = 0;
public int PlayerHighscore = 0;
public string NextLevelToLoad;
public string GameOverScreen;
[Tooltip("Assign all possible balloon prefabs.")]
[HideInInspector]
public List<GameObject> BalloonsPrefabs;
[Header("UI Settings")]
public TextMeshProUGUI UIScore;
public TextMeshProUGUI UILevel;
public TextMeshProUGUI UIHighScore;
public TextMeshProUGUI UILives;
public TextMeshProUGUI UICountDownNumber;
public TextMeshProUGUI UIComboCounter;
#region private variables
private Scene _currentScene;
// save all ball positions and their name for level reset
private Dictionary<Vector3, string> _startingBallsPosition;
// check if player has achieved a new score in this session and handle it
private static bool _hasNewHighscore = false;
private SoundManager _sound;
private GameObject _player;
#endregion
#region player specifics
[HideInInspector]
// to implement combos/multipliers
public int comboCounter;
[HideInInspector]
// check if player missed a shot or not
public bool flawlessVictory = true;
[HideInInspector]
// to calculate win condition
public int hitsToWin;
[HideInInspector]
// to calculate previous succesful hit
public float timeHit;
#endregion
// setup defaults and assign references
private void Awake()
{
if (gm == null)
gm = GetComponent<GameManager>();
_player = GameObject.FindGameObjectWithTag("Player");
if (_player == null)
Debug.LogError("Could not find Player gameobject!");
if (_sound == null)
_sound = SoundManager.sm;
if (BalloonsPrefabs == null || !BalloonsPrefabs.Any())
Debug.LogWarning("There are no prefabs attatched to the editor!");
// store balls' starting positions into a list so we can later reset them
_startingBallsPosition = new Dictionary<Vector3, string>();
// Find all balloons in scene and save their starting position, balloon type and direction
var allBalloons = FindAllBalloonsInScene();
foreach (var ballloon in allBalloons)
{
_startingBallsPosition.Add(new Vector3(ballloon.transform.position.x,
ballloon.transform.position.y),
ballloon.GetComponent<BalloonController>().BalloonType + ","
+ ballloon.GetComponent<BalloonController>().BalloonDirection.ToString());
}
SetupDefaults();
// play level music
_sound.PlayMusicForLevel(_currentScene);
}
// set gamemanager defaults
private void SetupDefaults()
{
// get current scene
_currentScene = SceneManager.GetActiveScene();
// load the same level again if we didn't specify the next level
if (NextLevelToLoad == "")
NextLevelToLoad = _currentScene.name;
// load the same level again if we didn't specify the gameover level
if (GameOverScreen == "")
GameOverScreen = _currentScene.name;
// get stored stat values
RefreshPlayerState();
// ready UI
RefreshGUI();
CalculateHitsForWin();
}
private void Start()
{
// stop game time and initiate countdown
Time.timeScale = 0;
StartCoroutine(CountDown());
}
// calculate maximum hits needed to complete the level
private void CalculateHitsForWin()
{
hitsToWin = 0;
foreach (var balloon in _startingBallsPosition)
{
var parameters = balloon.Value.Split(',');
switch (parameters[0])
{
case "Big":
hitsToWin += 15;
break;
case "Medium":
hitsToWin += 7;
break;
case "Small":
hitsToWin += 3;
break;
case "Tiny":
hitsToWin += 1;
break;
default:
break;
}
}
Debug.Log(hitsToWin);
}
private void Update()
{ // always check for combos
CheckCombo();
}
// check if gameover, else reset level
public void ResetLevel()
{
// subtract from player lives
PlayerLives--;
// store lives
PlayerPrefManager.SetLives(PlayerLives);
RefreshGUI();
// if game over
if (PlayerLives <= 0)
{
// Save stats
PlayerPrefManager.SavePlayerStats(PlayerLives, PlayerScore, PlayerHighscore);
// load game over screen
SceneManager.LoadScene(GameOverScreen);
}
// else respawn player and balloons at starting point
else
{
// load default weapon
_player.GetComponent<PlayerShoot>().ActiveWeapon = PlayerShoot.Weapons.Anchor;
// respawn player
_player.GetComponent<CharacterController2D>().RespawnPlayer();
// respawn balloons
RespawnBalloons();
// reset hit points needed to win
CalculateHitsForWin();
}
}
// respawn balls at starting position when we reset the level
private void RespawnBalloons()
{
// Find all balls in scene and delete them
List<GameObject> allBalloons = FindAllBalloonsInScene();
foreach (var balloon in allBalloons)
{
Destroy(balloon);
}
// foreach starting position, instantiate the matching balloon prefab and set its direction
foreach (KeyValuePair<Vector3, string> balloon in _startingBallsPosition)
{
var parameters = balloon.Value.Split(',');
for (int i = 0; i < BalloonsPrefabs.Count; i++)
{
if (parameters[0] == BalloonsPrefabs[i].GetComponent<BalloonController>().BalloonType)
{
var obj = Instantiate(BalloonsPrefabs[i], balloon.Key, BalloonsPrefabs[i].transform.rotation);
obj.GetComponent<BalloonController>().BalloonDirection = int.Parse(parameters[1]);
}
}
}
}
// use it to find all balloons in the level
private List<GameObject> FindAllBalloonsInScene()
{
var allBalloons = new List<GameObject>(GameObject.FindGameObjectsWithTag("Balloon"));
return allBalloons;
}
// add to player's score
public void AddScore(int amount)
{
PlayerScore += amount;
UIScore.text = "Score: " + PlayerScore.ToString();
// check if it is a new highscore
if (PlayerScore > PlayerHighscore)
{
PlayerHighscore = PlayerScore;
UIHighScore.text = "Best Score: " + PlayerHighscore.ToString();
PlayerPrefManager.SetHighscore(PlayerHighscore);
if (!_hasNewHighscore)
{
_sound.audioController.PlayOneShot(_sound.NewHighscore);
_hasNewHighscore = true;
}
}
}
// used on setup defaults and level reset
private void RefreshGUI()
{
UIScore.text = "Score: " + PlayerScore.ToString();
UIHighScore.text = "Best Score: " + PlayerHighscore.ToString();
UILives.text = "Lives: " + PlayerLives.ToString();
UILevel.text = _currentScene.name;
UIComboCounter.text = "";
comboCounter = 0;
}
// used on setup defaults
private void RefreshPlayerState()
{
PlayerLives = PlayerPrefManager.GetLives();
PlayerScore = PlayerPrefManager.GetScore();
PlayerHighscore = PlayerPrefManager.GetHighscore();
}
// increament combocounter if the next bullet does not miss in a timeframe of 2 seconds
public void CheckCombo()
{
// check when was the last time the player hit a balloon and check if combo can continue
float timeNow = Time.time;
float timeDif = timeNow - timeHit;
if (comboCounter > 0)
{
UIComboCounter.enabled = true;
UIComboCounter.text = comboCounter.ToString() + "x Combo!";
}
// check if combo breaks
if (timeDif > 2f && comboCounter != 0)
{
UIComboCounter.enabled = false;
comboCounter = 0;
// play broke combo sound
_sound.audioController.PlayOneShot(_sound.ComboBroke);
}
}
public void PauseGame()
{
Time.timeScale = 0f;
}
public void ResumeGame()
{
Time.timeScale = 1f;
}
#region Coroutines
// countdown for level to start
IEnumerator CountDown()
{
if (!PauseMenu.GameIsPaused)
{
_sound.audioController.PlayOneShot(_sound.CountDownBeep);
UICountDownNumber.text = "3";
yield return new WaitForSecondsRealtime(1);
_sound.audioController.PlayOneShot(_sound.CountDownBeep);
UICountDownNumber.text = "2";
yield return new WaitForSecondsRealtime(1);
_sound.audioController.PlayOneShot(_sound.CountDownBeep);
UICountDownNumber.text = "1";
yield return new WaitForSecondsRealtime(1);
_sound.audioController.PlayOneShot(_sound.CountDownOver);
UICountDownNumber.text = "GO!";
yield return new WaitForSecondsRealtime(1);
Time.timeScale = 1;
UICountDownNumber.gameObject.SetActive(false);
}
}
public IEnumerator LoadNextLevel()
{
// save stats
PlayerPrefManager.SavePlayerStats(PlayerLives, PlayerScore, PlayerHighscore);
// play level completed sound
_sound.audioController.PlayOneShot(_sound.LevelCompleted);
yield return new WaitForSeconds(2.5f);
// load next level
SceneManager.LoadScene(NextLevelToLoad);
}
#endregion
}
<file_sep>/Pang!/Assets/Scripts/PlayerShoot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShoot : MonoBehaviour
{
// fire starting points for each weapon
public Transform anchorFirePoint;
public Transform bulletFirePoint;
// how fast can the player shoot with each weapon
const float ANCHOR_FIRE_RATE = 1;
const float BULLET_FIRE_RATE = .4f;
// weapon prefabs
public GameObject anchorPref;
public GameObject bulletPref;
// simple enum to control which is the active weapon
public enum Weapons
{
Anchor,
Bullet
}
public Weapons ActiveWeapon = Weapons.Anchor;
private bool _allowFire = true;
void Update()
{
if (Input.GetButtonDown("Fire1") && _allowFire)
{
switch (ActiveWeapon)
{
case Weapons.Anchor:
//fireRate = 1;
StartCoroutine(ShootAnchor());
break;
case Weapons.Bullet:
//fireRate = .4f;
StartCoroutine(ShootBullet());
break;
default:
break;
}
}
}
IEnumerator ShootAnchor()
{
_allowFire = false;
Instantiate(anchorPref, anchorFirePoint.position, anchorFirePoint.rotation);
yield return new WaitForSeconds(ANCHOR_FIRE_RATE);
_allowFire = true;
}
IEnumerator ShootBullet()
{
_allowFire = false;
Instantiate(bulletPref, bulletFirePoint.position, bulletFirePoint.rotation);
yield return new WaitForSeconds(BULLET_FIRE_RATE);
_allowFire = true;
}
}
| 42c80a71f0413f471b72a345eb41fc97c7a03917 | [
"C#"
] | 13 | C# | konGiann/Pang | 2fa6990fb0328afdfb9dae5499b9abb0c31188db | 09718df08e434d8ba3ac85cff546ec30f8763043 |
refs/heads/main | <repo_name>xyproto/mcbanner<file_sep>/image.go
package mcbanner
import (
"bytes"
"image/color"
"image/png"
"log"
)
// The difference between two color values, as float64 (0..1)
func Colordiff(a, b uint32) float64 {
af := float64(a) / (256.0 * 256.0)
bf := float64(b) / (256.0 * 256.0)
res := af - bf
if res < 0 {
return -res
}
return res
}
func Valuediff(a, b float64) float64 {
res := a - b
if res < 0 {
return -res
}
return res
}
// Lightness
func Value(r, g, b uint32) float64 {
rf := float64(r) / (256.0 * 256.0)
gf := float64(g) / (256.0 * 256.0)
bf := float64(b) / (256.0 * 256.0)
return (rf + gf + bf) / 3.0
}
// Find the distance between two colors, 0..1
func Distance(c1, c2 color.Color) float64 {
r1, g1, b1, _ := c1.RGBA()
r2, g2, b2, _ := c2.RGBA()
//v1 := Value(r1, g1, b1)
//v2 := Value(r2, g2, b2)
//return (Colordiff(r1, r2) + Colordiff(g1, g2) + Colordiff(b1, b2) + Valuediff(v1, v2)) * 0.25
return (Colordiff(r1, r2) + Colordiff(g1, g2) + Colordiff(b1, b2)) * 0.33
}
// Find how visually similar two images are, from 0..1
// Does not take the human vision into account, only rgb values
func Likeness(png1, png2 []byte) float64 {
buf1 := bytes.NewBuffer(png1)
buf2 := bytes.NewBuffer(png2)
i1, err := png.Decode(buf1)
if err != nil {
log.Fatalln(err.Error())
}
i2, err := png.Decode(buf2)
if err != nil {
log.Fatalln(err.Error())
}
if i1.Bounds() != i2.Bounds() {
log.Fatalf("Can only compare images of same size! Got %v and %v.\n", i1.Bounds(), i2.Bounds())
}
counter := 0
sum := 0.0
for y := i1.Bounds().Min.Y; y < i1.Bounds().Max.Y; y++ {
for x := i1.Bounds().Min.X; x < i1.Bounds().Max.X; x++ {
//log.Printf("d %.3f\n", Distance(i1.At(x, y), i2.At(x, y)))
sum += Distance(i1.At(x, y), i2.At(x, y))
counter++
}
}
//log.Printf("Difference %.3f\n", res)
return sum / float64(counter)
}
// Compare a banner with a png file, return the likeness as float64
func Compare(b *Banner, pngbytes []byte) float64 {
return Likeness(b.PNG(), pngbytes)
}
<file_sep>/cmd/mcweb/pages.go
package main
import (
"fmt"
"github.com/unrolled/render"
"github.com/xyproto/mcbanner"
"github.com/xyproto/onthefly"
"io/ioutil"
"log"
"net/http"
"strconv"
)
const (
zoomFactor = 8 // 8x zoom when displaying banners
)
// TODO: This works as long as there are not too many users. Fix.
var gB *mcbanner.Banner
var gHow []string
func mainPage(mux *http.ServeMux, path string, r *render.Render) {
mux.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
data := map[string]string{
"title": version_string,
}
// TODO: Enable this if a development environment variable is on
// Reload template (great for development)
//r = render.New(render.Options{})
// Render and return
r.HTML(w, http.StatusOK, "index", data)
})
}
func comparison(mux *http.ServeMux, path string, r *render.Render) {
mcbanner.Seed()
svgurl1 := "/img/a.svg"
pngurl1 := "/img/a.png"
pngurl2 := "/img/c1.png"
pngbytes2, err := ioutil.ReadFile("public" + pngurl2)
if err != nil {
log.Fatalln("Could not read: " + "public" + pngurl2)
}
b, _ := mcbanner.NewRandomBanner()
svgxml1 := b.SVG()
pngbytes1 := b.PNG()
likeness := mcbanner.Likeness(pngbytes1, pngbytes2)
mux.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
b, _ = mcbanner.NewRandomBanner()
svgxml1 = b.SVG()
pngbytes1 = b.PNG()
likeness = mcbanner.Likeness(pngbytes1, pngbytes2)
bw := strconv.Itoa(mcbanner.BannerW) + "px"
bh := strconv.Itoa(mcbanner.BannerH) + "px"
data := map[string]string{
"title": "Comparison",
"likeness": fmt.Sprintf("%.0f%%", likeness*100.0),
"bannerWidth": bw,
"bannerHeight": bh,
"svg": svgurl1,
"png1": pngurl1,
"png2": pngurl2,
}
// TODO: Enable this only if a development environment variable is on
// Reload template (great for development)
r = render.New(render.Options{})
// Render and return
r.HTML(w, http.StatusOK, "comparison", data)
})
mux.HandleFunc(svgurl1, func(w http.ResponseWriter, req *http.Request) {
w.Header().Add("Content-Type", "image/svg+xml")
w.Write(svgxml1)
})
//mux.HandleFunc(pngurl1, func(w http.ResponseWriter, req *http.Request) {
// w.Header().Add("Content-Type", "image/png")
// w.Write(pngbytes1)
//})
mux.HandleFunc(pngurl2, func(w http.ResponseWriter, req *http.Request) {
w.Header().Add("Content-Type", "image/png")
w.Write(pngbytes2)
})
}
// Generate a new onthefly Page (HTML5 and CSS combined)
func patternGalleryPage(title string, svgurls, captions []string) *onthefly.Page {
var specialPageZoomFactor = 0.7
// Create a new HTML5 page, with CSS included
page := onthefly.NewHTML5Page(title)
page.AddContent(title)
// Change the margin (em is default)
page.SetMargin(3)
// Change the font family
page.SetFontFamily("sans-serif")
// Change the color scheme
page.SetColor("black", "#a0a0a0")
// Include the generated SVG image on the page
body, _ := page.GetTag("body")
// CSS attributes for the body tag
body.AddStyle("font-size", "2em")
// Div
div := body.AddNewTag("div")
div.AddStyle("font-size", "0.5em")
// CSS style
div.AddStyle("margin-top", "2em")
// Add images
var (
tag, figure *onthefly.Tag
useObjectTag = false
)
for i, svgurl := range svgurls {
figure = div.AddNewTag("figure")
if useObjectTag {
// object tag
tag = figure.AddNewTag("object")
// HTML attributes
tag.AddAttrib("data", svgurl)
tag.AddAttrib("type", "image/svg+xml")
} else {
// img tag
tag = figure.AddNewTag("img")
// HTML attributes
tag.AddAttrib("src", svgurl)
tag.AddAttrib("alt", "Banner")
}
cap := figure.AddNewTag("figcaption")
cap.AddContent(captions[i])
}
page.AddStyle(`
body { margin: 2em auto; width: 60%; padding: 1em; height: 100%; }
figure { float: left; display; block; width: 12%; }
figure img { display: block: width: 90%; margin: 0 auto; padding: 0; }
figure figcaption { display: block; margin 0.5em auto; width: 90%; padding: 0.3em; font: italic small Arial, sans-serif; text-align: left; }}
`)
// CSS style
w := strconv.Itoa(int(mcbanner.BannerW * zoomFactor * specialPageZoomFactor))
h := strconv.Itoa(int(mcbanner.BannerH * zoomFactor * specialPageZoomFactor))
tag.AddStyle("width", w+"px")
tag.AddStyle("height", h+"px")
tag.AddStyle("border", "4px solid black")
return page
}
// Create a pattern gallery under the given path
func patternGallery(mux *http.ServeMux, path string) {
var (
svgurls, descs []string
b *mcbanner.Banner
)
for i := mcbanner.PatternLowerThird; i <= mcbanner.PatternLogo; i++ {
b = mcbanner.NewBanner()
p, _ := mcbanner.NewPattern(mcbanner.PatternFull, mcbanner.ColorBrightWhite)
b.AddPattern(p)
p, _ = mcbanner.NewPattern(i, mcbanner.ColorRed)
b.AddPattern(p)
svgxml := b.SVG()
// Publish the generated SVG as "/img/banner_NNN.svg"
svgurl := fmt.Sprintf("/img/banner_%d.svg", i)
mux.HandleFunc(svgurl, func(w http.ResponseWriter, req *http.Request) {
w.Header().Add("Content-Type", "image/svg+xml")
w.Write(svgxml)
})
svgurls = append(svgurls, svgurl)
descs = append(descs, p.PatternString())
}
// Generate a Page that includes the svg images
page := patternGalleryPage("Pattern gallery", svgurls, descs)
// Publish the generated Page in a way that connects the HTML and CSS
page.Publish(mux, path, "/css/banner.css", false)
}
func randomBanner(mux *http.ServeMux, path string, r *render.Render) {
mux.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
bw := strconv.Itoa(mcbanner.BannerW*zoomFactor) + "px"
bh := strconv.Itoa(mcbanner.BannerH*zoomFactor) + "px"
// Reload template (great for development)
//r = render.New(render.Options{})
// The recipe
mcbanner.Seed()
var howP []*mcbanner.Pattern
gB, howP = mcbanner.NewRandomBanner()
// how is a list of pattern.String() based on howP
how := []string{}
for _, p := range howP {
how = append(how, p.String())
}
data := map[string]interface{}{
"title": "Random banner",
"bannerWidth": bw,
"bannerHeight": bh,
"how": how,
"howTitle": "How to make it yourself",
}
// Render and return
r.HTML(w, http.StatusOK, "random", data)
})
// TODO: One url per generated banner. /img/generated/123/123/result.svg
mux.HandleFunc("/img/random.svg", func(w http.ResponseWriter, req *http.Request) {
w.Header().Add("Content-Type", "image/svg+xml")
b, _ := mcbanner.NewRandomBanner()
w.Write(b.SVG())
})
}
<file_sep>/cmd/evolve/main.go
package main
import (
"flag"
"io/ioutil"
"log"
_ "net/http/pprof"
"os"
"runtime"
"runtime/pprof"
"github.com/xyproto/mcbanner"
)
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`")
var memprofile = flag.String("memprofile", "", "write memory profile to `file`")
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal("could not create CPU profile: ", err)
}
defer f.Close()
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal("could not start CPU profile: ", err)
}
defer pprof.StopCPUProfile()
}
targetImageFilename := "../mcweb/public/img/c1.png"
pngbytes, err := ioutil.ReadFile(targetImageFilename)
if err != nil {
log.Fatalf("Could not read: %s\n", targetImageFilename)
}
mcbanner.FindBest(mcbanner.Likeness, pngbytes, "/tmp/best.png")
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
defer f.Close()
runtime.GC() // get up-to-date statistics
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write memory profile: ", err)
}
}
}
<file_sep>/cmd/random/main.go
package main
import (
"github.com/xyproto/mcbanner"
"os"
)
func main() {
mcbanner.Seed()
ban, _ := mcbanner.NewRandomBanner()
os.Stdout.Write(ban.PNG())
}
<file_sep>/random.go
package mcbanner
import (
"log"
"math/rand"
"time"
)
func Seed() {
rand.Seed(time.Now().UnixNano())
}
func randomPattern() int {
// PatternLowerThird is the first Pattern
// PatternFull is the one after the last one we wish to return
return PatternLowerThird + rand.Intn(PatternFull-PatternLowerThird)
}
func randomColor() int {
// colorWhite is the first constant, colorBlack is the last one
return ColorWhite + rand.Intn((ColorBlack-ColorWhite)+1)
}
func NewRandomPattern() Pattern {
// error is only returned if the values are invalid
// randomPattern and randomColor only returns valid values, so the error can be ignored
pat, err := NewPattern(randomPattern(), randomColor())
if err != nil {
log.Println("ERROR WHEN GENERATING RANDOM PATTERN")
}
return *pat
}
<file_sep>/convert.go
package mcbanner
import (
"io/ioutil"
"os"
"os/exec"
"github.com/xyproto/cookie"
)
// Use rsvg to render svg (convert bytes from svg to png)
func Convert(imagebytes []byte, fromformat, toformat string) []byte {
randomString := cookie.RandomHumanFriendlyString(8) // Collisions are rare and not critical, for this function
path := "/tmp/"
inputFilename := path + randomString + ".svg"
outputFilename := path + randomString + ".png"
// write the .svg file
if err := ioutil.WriteFile(inputFilename, imagebytes, 0600); err != nil {
panic(err)
}
// convert the .svg file to the output format (perhaps png)
if err := exec.Command("rsvg-convert", inputFilename, "-b", "white", "-f", toformat, "-o", outputFilename).Run(); err != nil {
panic(err)
}
// read the converted image
b, err := ioutil.ReadFile(outputFilename)
if err != nil {
panic(err)
}
// remove both temporary files
if err := os.Remove(inputFilename); err != nil {
panic(err)
}
if err = os.Remove(outputFilename); err != nil {
panic(err)
}
return b
}
<file_sep>/cmd/mcweb/compileloop.sh
#!/bin/sh
export PORT=3020
SOURCE=
for f in *.go ../*.go; do
SOURCE+="$f "
done
BIN=web
PIDFILE=/tmp/$BIN.pid
LOG=errors.err
M5=nop
SUMFILE=/tmp/$BIN.sumfile.txt
echo 'Starting compilation loop'
echo 'Reading pid'
if [ -e $PIDFILE ]; then
echo 'Killing server'
kill `cat $PIDFILE` > /dev/null
rm "$PIDFILE"
rm "$SUMFILE"
fi
while true; do
OLDM5=$M5
md5sum $SOURCE > $SUMFILE
M5=$(md5sum $SUMFILE)
if [ "$OLDM5" != "$M5" ]; then
echo 'Source changed'
echo 'Reading pid'
if [ -e $PIDFILE ]; then
echo 'Killing server'
kill `cat $PIDFILE` > /dev/null
rm $PIDFILE
fi
clear
date
echo
echo -n 'Recompiling ...'
[ -e $LOG ] && rm $LOG
go build -o $BIN > $LOG
if [ "$(wc -c $LOG | cut -d' ' -f1)" == '0' ]; then
rm $LOG
fi
if [ -e $LOG ]; then
echo
cat $LOG
else
echo ok
fi
echo
echo 'Backing up executable'
if [ -e "/tmp/$BIN" ]; then
rm "/tmp/$BIN"
fi
cp "./$BIN" "/tmp/$BIN"
echo 'Starting server'
./$BIN &
echo 'Writing pid'
pgrep $BIN > $PIDFILE
fi
# Wait for the source to be changed
inotifywait -q $SOURCE
sleep 1
done
<file_sep>/README.md
# mcbanner
Application for generating Minecraft banners.
## Includes
* A web server/page showing the variations of Minecraft banners, as SVG approximations (`mcweb`).
* A commandline application for evolving Minecraft banners with genetic algorithms (`evolve`).
* Go code for generating a random SVG banner and rendering it as PNG by using `rsvg-convert` (`random`).
## Original goal
* Given an image, get the steps for creating the closest looking Minecraft banner. This goal is a work in progress, since the evolution is not rapid enough. Perhaps using smaller images when rendering from SVG, or another algorithm, would work.
## General information
* Version: 2.0.1
* License: MIT
<file_sep>/cmd/random/buildrunview.sh
#!/bin/sh
go get -d
go build
./compare > out.png
eog out.png
<file_sep>/ga.go
package mcbanner
// Genetic algorithm
import (
"fmt"
"io/ioutil"
"math/rand"
)
const (
POPSIZE = 800
MAXGENERATIONS = 50 // 3000
)
// This is what every solution is being compared against
var target_png_bytes []byte
// A solution is up to maxPatterns Patterns
type Solution []Pattern
// A population is a collection of solutions
type Population []Solution
// For storing the population fitnesses before sorting
type PopulationFitness []float64
func NewPopulationFitness(popsize int) PopulationFitness {
return make(PopulationFitness, popsize)
}
func NewRandomSolution() Solution {
sol := make([]Pattern, maxPatterns)
for i := 0; i < maxPatterns; i++ {
sol[i] = NewRandomPattern()
}
return sol
}
func (sol Solution) String() string {
//s := fmt.Sprintf("Solution with %d patterns: ", len(sol))
s := "Solution: "
for i := 0; i < maxPatterns; i++ {
s += sol[i].String()
if i != maxPatterns-1 {
s += " | " // separator
}
}
return s + "\n"
}
func (sol Solution) Banner() *Banner {
b := NewBanner()
for i := 0; i < len(sol); i++ {
b.AddPattern(&sol[i])
}
return b
}
func (sol Solution) fitness() float64 {
//if err := sol[0].Valid(); err != nil {
// log.Fatalln("Can't find fitness for an invalid solution: ", err.Error())
//}
return Compare(sol.Banner(), target_png_bytes)
}
func NewPopulation(size int) Population {
Seed()
pop := make([]Solution, size)
for i := 0; i < size; i++ {
pop[i] = NewRandomSolution()
}
return pop
}
func crossover(a, b Solution, point int) Solution {
// Can start with a blank solution, since the elements will be filled in
c := make([]Pattern, maxPatterns)
for i := 0; i < point; i++ {
c[i] = a[i]
}
for i := point; i < maxPatterns; i++ {
c[i] = b[i]
}
return c
}
func (sol Solution) mutate() {
randpos := rand.Intn(maxPatterns)
sol[randpos] = NewRandomPattern()
}
func sum(scores []float64) float64 {
var total float64
for _, score := range scores {
total += score
}
return total
}
func FindBest(fitnessfunction func([]byte, []byte) float64, png_bytes []byte, bestFilename string) {
target_png_bytes = png_bytes
var (
bestfitnessindex = 0
popsize int = POPSIZE
pop = NewPopulation(popsize)
generation int
average float64
)
for generation = 0; generation < MAXGENERATIONS; generation++ {
fmt.Println("Generation", generation)
fit := NewPopulationFitness(popsize)
//fmt.Println("fit ok")
//fmt.Println("population:", pop)
for i, s := range pop {
fit[i] = s.fitness()
//fmt.Printf("fit[%d] ok\n", i)
}
//fmt.Println(fit)
total := sum(fit)
fmt.Println("total =", total)
average = total / float64(popsize)
fmt.Println("average =", average)
var (
bestfitness, nextbestfitness float64
nextbestfitnessindex = 0
)
for i := range fit {
if fit[i] >= bestfitness {
nextbestfitness = bestfitness
bestfitness = fit[i]
nextbestfitnessindex = bestfitnessindex
bestfitnessindex = i
}
}
fmt.Println("best =", bestfitness)
fmt.Println("nextbest =", nextbestfitness)
if bestfitness == 1.0 {
fmt.Println("Found fitness 1")
break
}
fmt.Println("best solution:", pop[bestfitnessindex])
ioutil.WriteFile(bestFilename, pop[bestfitnessindex].Banner().PNG(), 0644)
var (
mutrate float64 = 0.0
crossrate float64 = 0.1
newpoprate float64 = 0.0
)
for i := range pop {
fitness := fit[i]
if average > 0.7 && fitness < 0.5 {
pop[i] = NewRandomSolution()
} else if average > 0.8 && fitness < 0.6 {
pop[i] = NewRandomSolution()
} else if average > 0.9 && fitness < 0.7 {
pop[i] = NewRandomSolution()
} else if fitness < (average * 0.3) {
// 50% chance of being replaced with randomness
if rand.Float64() <= 0.5 {
pop[i] = NewRandomSolution()
}
}
if bestfitness > average {
// slow down the mutation rate
mutrate = 0.15
crossrate = 0.07
} else {
mutrate = 0.4
crossrate = 0.4
}
if bestfitness == nextbestfitness {
mutrate *= 3.0
}
if average > 0.9 {
newpoprate = 0.4
} else {
newpoprate = 0.2
}
// An advantage for the best ones
if fitness > (bestfitness * 0.9) {
if rand.Float64() <= 0.9 {
continue
}
}
// A certain chance for mutation
if rand.Float64() <= mutrate {
// Changing one of the elements of a solution.
// Tested. Works.
i := rand.Intn(int(popsize))
pop[i].mutate()
}
// A certain chance for crossover
if rand.Float64() <= crossrate {
// Crossing the best and next best solution to a new solution.
// Tested. Works.
crossoverpoint := int(rand.Intn(maxPatterns))
pop[i] = crossover(pop[bestfitnessindex], pop[nextbestfitnessindex], crossoverpoint)
}
// A certain chance for new random variations
if rand.Float64() <= newpoprate {
// Tested. Works.
pop[i] = NewRandomSolution()
}
}
fmt.Println("end of generation", generation)
//fmt.Println("population:", pop)
}
fmt.Println("generation", generation)
fmt.Println(pop[bestfitnessindex])
}
<file_sep>/banner.go
package mcbanner
import (
"github.com/xyproto/tinysvg"
"log"
)
const (
BannerW = 20
BannerH = 40
fullW = BannerW
fullH = BannerH
halfW = BannerW / 2
halfH = BannerH / 2
thirdW = BannerW / 3
thirdH = BannerH / 3
fifthW = BannerW / 5
fifthH = BannerH / 5
sixthW = BannerW / 6
sixthH = BannerH / 6
tenthW = BannerW / 10
tenthH = BannerH / 10
maxX = fullW - 1
maxY = fullH - 1
)
type Banner struct {
Patterns []*Pattern
curpat int
}
func NewBanner() *Banner {
return &Banner{}
}
func (b *Banner) AddPattern(p *Pattern) {
if len(b.Patterns) > maxPatterns {
log.Fatalln("Too many patters for banner, max", maxPatterns)
}
b.Patterns = append(b.Patterns, p)
}
func (b *Banner) Draw(svg *tinysvg.Tag) {
// draw each Pattern
for _, p := range b.Patterns {
color, ok := colors[p.color]
if !ok {
log.Fatalln("Invalid color ID: ", p.color)
}
DrawPattern(svg, p.pattern, color)
}
}
// Generate a new SVG image for the banner
func (b *Banner) Image() *tinysvg.Document {
if b == nil {
log.Fatalln("Can't generate SVG for a *Banner that is nil!")
}
document, svg := tinysvg.NewTinySVG(BannerW, BannerH)
svg.Describe("A banner")
b.Draw(svg)
return document
}
func (b *Banner) SVG() []byte {
return b.Image().Bytes()
}
func (b *Banner) PNG() []byte {
return Convert(b.SVG(), "svg", "png")
}
func NewRandomBanner() (b *Banner, how []*Pattern) {
// Generate new banner
b = NewBanner()
how = []*Pattern{}
p, _ := NewPattern(PatternFull, randomColor())
b.AddPattern(p)
how = append(how, p)
// Up to 6 different Patterns
for i := 0; i < maxPatterns; i++ {
p, _ = NewPattern(randomPattern(), randomColor())
b.AddPattern(p)
how = append(how, p)
}
return b, how
}
<file_sep>/cmd/mcweb/main.go
package main
import (
"net/http"
"runtime"
"github.com/codegangsta/negroni"
"github.com/unrolled/render"
)
const (
version_string = "MC Banner Generator 2.0.1"
)
// Set up the paths and handlers then start serving.
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
// Create a Negroni instance and a ServeMux instance
n := negroni.Classic()
r := render.New(render.Options{})
mux := http.NewServeMux()
// Publish the main page
mainPage(mux, "/", r)
// Publish the pattern gallery page
patternGallery(mux, "/patterns")
// Publish the random banner page
randomBanner(mux, "/random", r)
// Publish the svg->pixel vs png->pixel comparison page
comparison(mux, "/comparison", r)
// Handler goes last
n.UseHandler(mux)
// Listen for requests
n.Run(":3020")
}
<file_sep>/cmd/mcweb/ginloop.sh
#!/bin/sh
gin -p 3000 -a 3020 run
<file_sep>/go.mod
module github.com/xyproto/mcbanner
go 1.11
require (
github.com/codegangsta/negroni v1.0.0
github.com/unrolled/render v1.0.1
github.com/xyproto/cookie v0.0.0-20181220103240-f4de411f45ff
github.com/xyproto/onthefly v0.0.0-20191021105244-b7c58dc7f08b
github.com/xyproto/randomstring v0.0.0-20181222003104-0f764aabc45a // indirect
github.com/xyproto/tinysvg v0.0.0-20191101100520-ef4e4a2e5b89
)
<file_sep>/color.go
package mcbanner
var (
colors = map[int]string{
ColorWhite: "#989898",
ColorOrange: "#804d23",
ColorMagenta: "#6b3181",
ColorLightBlue: "#3e5b7f",
ColorYellow: "#898923",
ColorLime: "#4c7815",
ColorPink: "#8f4c62",
ColorGray: "#313131",
ColorLightGray: "#5b5b5b",
ColorCyan: "#314c5b",
ColorPurple: "#4d2b6a",
ColorBlue: "#23316b",
ColorBrown: "#3e3123",
ColorGreen: "#3e4c23",
ColorRed: "#5c2323",
ColorBlack: "#151515",
ColorBrightWhite: "#ffffff",
}
)
<file_sep>/pattern.go
package mcbanner
import (
"errors"
"fmt"
"github.com/xyproto/tinysvg"
"math"
"strconv"
)
const (
maxPatterns = 6
// Same order as minecraft.gamepedia.com/Banner
PatternLowerThird = iota // Base Fess Banner
PatternUpperThird // Chief Fess Banner
PatternLeftThird // Pale Dexter Banner
PatternRightThird // Pale Sinister Banner
PatternCenterThird // Pale Banner
PatternHorizontalLine // Fess Banner
PatternDiagonal1 // Bend Banner
PatternDiagonal2 // Bend Sinister Banner
patterStripes // Paly Banner
PatternDiaCross // Saltire Banner
PatternCross // Cross Banner
PatternUpperLeftTriangle // Per Bend Sinister Banner
PatternUpperRightTriangle // Per Bend Banner
PatternLowerLeftTriangle // Per Bend Inverted Banner
PatternLowerRightTriangle // Per Bend Sinister Inverted Banner
PatternLeftHalf // Per Pale Banner
PatternRightHalf // Per Pale Inverted Banner
PatternUpperHalf // Per Fess Banner
PatternLowerHalf // Per Fess Inverted Banner
PatternLowerLeftSquare // Base Dexter Canton Banner
PatternLowerRightSquare // Base Sinister Canton Banner
PatternUpperLeftSquare // Chief Dexter Canton Banner
PatternUpperRightSqaure // Chief Sinister Canton Banner
PatternLowerTriangle // Chevron Banner
PatternUpperTriangle // Inverted Chevron Banner
PatternLowerWaves // Base Indented Banner
PatternUpperWaves // Chief Indented Banner
PatternCircle // Roundel Banner
PatternDiamond // Lozenge Banner
PatternBorder // Bordure Banner
PatternWaveBorder // Black/Dyed Borduer Indented Banner
PatternBricks // Black/Dyed Field Masoned Banner
PatternGradientDown // Gradient Banner
PatternGradientUp // Base Gradient Banner
PatternCreeper // Black/Dyed Creeper Charge Banner
PatternSkull // Black/Dyed Skull Charge Banner
PatternFlower // Black/Dyed Flower Charge Banner
PatternLogo // Black/Dyed Mojang Charge Banner
// Custom Patterns
PatternFull // Background
ColorWhite = iota
ColorOrange
ColorMagenta
ColorLightBlue
ColorYellow
ColorLime
ColorPink
ColorGray
ColorLightGray
ColorCyan
ColorPurple
ColorBlue
ColorBrown
ColorGreen
ColorRed
ColorBlack
// Custom Colors
ColorBrightWhite
)
var PatternDesc = map[int]string{
PatternLowerThird: "Base Fess Banner",
PatternUpperThird: "Chief Fess Banner",
PatternLeftThird: "Pale Dexter Banner",
PatternRightThird: "Pale Sinister Banner",
PatternCenterThird: "Pale Banner",
PatternHorizontalLine: "Fess Banner",
PatternDiagonal1: "Bend Banner",
PatternDiagonal2: "Bend Sinister Banner",
patterStripes: "Paly Banner",
PatternDiaCross: "Saltire Banner",
PatternCross: "Cross Banner",
PatternUpperLeftTriangle: "Per Bend Sinister Banner",
PatternUpperRightTriangle: "Per Bend Banner",
PatternLowerLeftTriangle: "Per Bend Inverted Banner",
PatternLowerRightTriangle: "Per Bend Sinister Inverted Banner",
PatternLeftHalf: "Per Pale Banner",
PatternRightHalf: "Per Pale Inverted Banner",
PatternUpperHalf: "Per Fess Banner",
PatternLowerHalf: "Per Fess Inverted Banner",
PatternLowerLeftSquare: "Base Dexter Canton Banner",
PatternLowerRightSquare: "Base Sinister Canton Banner",
PatternUpperLeftSquare: "Chief Dexter Canton Banner",
PatternUpperRightSqaure: "Chief Sinister Canton Banner",
PatternLowerTriangle: "Chevron Banner",
PatternUpperTriangle: "Inverted Chevron Banner",
PatternLowerWaves: "Base Indented Banner",
PatternUpperWaves: "Chief Indented Banner",
PatternCircle: "Roundel Banner",
PatternDiamond: "Lozenge Banner",
PatternBorder: "Bordure Banner",
PatternWaveBorder: "Borduer Indented Banner",
PatternBricks: "Field Masoned Banner",
PatternGradientDown: "Gradient Banner",
PatternGradientUp: "Base Gradient Banner",
PatternCreeper: "Creeper Charge Banner",
PatternSkull: "Skull Charge Banner",
PatternFlower: "Flower Charge Banner",
PatternLogo: "Mojang Charge Banner",
PatternFull: "Background",
}
type Pattern struct {
pattern int
color int
}
func (pat *Pattern) Valid() error {
if (pat.pattern < PatternLowerThird) || (pat.pattern > PatternFull) {
return errors.New(fmt.Sprintf("Invalid Pattern ID: %d\n", pat.pattern))
}
if (pat.color < ColorWhite) || (pat.color > ColorBrightWhite) {
return errors.New(fmt.Sprintf("Invalid Color ID: %d\n", pat.color))
}
return nil
}
func NewPattern(patId, Color int) (*Pattern, error) {
pat := &Pattern{patId, Color}
if err := pat.Valid(); err != nil {
return nil, err
}
return pat, nil
}
func DrawPattern(svg *tinysvg.Tag, Pattern int, Color string) {
switch Pattern {
case PatternLowerThird: // Base Fess Banner
svg.Box(0, fullH-thirdH, fullW, fullH-thirdH, Color)
case PatternUpperThird: // Chief Fess Banner
svg.Box(0, 0, fullW, thirdH, Color)
case PatternLeftThird: // Pale Dexter Banner
svg.Box(0, 0, thirdW, fullH, Color)
case PatternRightThird: // Pale Sinister Banner
svg.Box(fullW-thirdW, 0, thirdW, fullH, Color)
case PatternCenterThird: // Pale Banner
svg.Box(halfW-(thirdW/2), 0, thirdW, fullH, Color)
case PatternHorizontalLine: // Fess Banner
svg.Box(0, halfH-1, fullW, thirdW/2, Color)
case PatternDiagonal1: // Bend Banner
svg.Line(0, 0, fullW, fullH, thirdW, Color)
case PatternDiagonal2: // Bend Sinister Banner
svg.Line(fullW, 0, 0, fullH, thirdW, Color)
case patterStripes: // Paly Banner
for i := 0.15; i < 1.0; i += 0.25 {
x := int(float64(fullW) * i)
svg.Line(x, 0, x, fullH, sixthW, Color)
}
case PatternDiaCross: // Saltire Banner
svg.Line(0, 0, fullW, fullH, thirdW, Color)
svg.Line(fullW, 0, 0, fullH, thirdW, Color)
case PatternCross: // Cross Banner
svg.Line(0, halfH, fullW, halfH, sixthW, Color)
svg.Line(halfW, 0, halfW, fullH, sixthW, Color)
case PatternUpperLeftTriangle: // Per Bend Sinister Banner
svg.Triangle(0, 0, fullW, 0, 0, fullH, Color)
case PatternUpperRightTriangle: // Per Bend Banner
svg.Triangle(0, 0, fullW, 0, fullW, fullH, Color)
case PatternLowerLeftTriangle: // Per Bend Inverted Banner
svg.Triangle(0, fullH, 0, 0, fullW, fullH, Color)
case PatternLowerRightTriangle: // Per Bend Sinister Inverted Banner
svg.Triangle(0, fullH, fullW, 0, fullW, fullH, Color)
case PatternLeftHalf: // Per Pale Banner
svg.Box(0, 0, halfW, fullH, Color)
case PatternRightHalf: // Per Pale Inverted Banner
svg.Box(halfW, 0, halfW, fullH, Color)
case PatternUpperHalf: // Per Fess Banner
svg.Box(0, 0, fullW, halfH, Color)
case PatternLowerHalf: // Per Fess Inverted Banner
svg.Box(0, halfH, fullW, halfH, Color)
case PatternLowerLeftSquare: // Base Dexter Canton Banner
svg.Box(0, fullH-thirdH, halfW, thirdH, Color)
case PatternLowerRightSquare: // Base Sinister Canton Banner
svg.Box(halfW, fullH-thirdH, halfW, thirdH, Color)
case PatternUpperLeftSquare: // Chief Dexter Canton Banner
svg.Box(0, 0, halfW, thirdH, Color)
case PatternUpperRightSqaure: // Chief Sinister Canton Banner
svg.Box(halfW, 0, halfW, thirdH, Color)
case PatternLowerTriangle: // Chevron Banner
svg.Triangle(0, fullH, fullW, fullH, halfW, halfH, Color)
case PatternUpperTriangle: // Inverted Chevron Banner
svg.Triangle(0, 0, fullW, 0, halfW, halfH, Color)
case PatternLowerWaves: // Base Indented Banner
svg.Ellipse(sixthW, fullH, fifthW, thirdW, Color)
svg.Ellipse(halfW, fullH, fifthW, thirdW, Color)
svg.Ellipse(fullW-sixthW, fullH, fifthW, thirdW, Color)
case PatternUpperWaves: // Chief Indented Banner
svg.Ellipse(sixthW, 0, fifthW, thirdW, Color)
svg.Ellipse(halfW, 0, fifthW, thirdW, Color)
svg.Ellipse(fullW-sixthW, 0, fifthW, thirdW, Color)
case PatternCircle: // Roundel Banner
svg.Circle(halfW, halfH, thirdW, Color)
case PatternDiamond: // Lozenge Banner
svg.Poly4(halfW, fifthH,
fullW-fifthW, halfH,
halfW, fullH-fifthH,
fifthW, halfH,
Color)
case PatternBorder: // Bordure Banner
svg.Line(0, 0, fullW, 0, sixthW, Color)
svg.Line(fullW, 0, fullW, fullH, sixthW, Color)
svg.Line(0, fullH, fullW, fullH, sixthW, Color)
svg.Line(0, 0, 0, fullH, sixthW, Color)
case PatternWaveBorder: // Black/Dyed Borduer Indented Banner
br := halfH // radius of circles in corners
ofs1 := fifthH // offset away from the center, corner circles
brx := sixthH // radius x of circles along the sides
bry := fullH / 7 // radius y of circles along the sides
ofs2 := sixthH / 3 // offset away from the center, side circles
bh := fullH/4 + fullH/8 // placement of circles along the sides
// corners
svg.Ellipse(0-ofs1, 0-ofs1, br, br, Color)
svg.Ellipse(0-ofs1, fullH+ofs1, br, br, Color)
svg.Ellipse(fullW+ofs1, 0-ofs1, br, br, Color)
svg.Ellipse(fullW+ofs1, fullH+ofs1, br, br, Color)
// sides
svg.Ellipse(0-ofs2, bh, brx, bry, Color)
svg.Ellipse(0-ofs2, fullH-bh, brx, bry, Color)
svg.Ellipse(fullW+ofs2, bh, brx, bry, Color)
svg.Ellipse(fullW+ofs2, fullH-bh, brx, bry, Color)
case PatternBricks: // Black/Dyed Field Masoned Banner
brickW := fullW / 4
brickH := fullH / 13
ofs := 0
for y := 0; y < fullH; y += brickH + 1 {
for x := ofs; x < fullW; x += brickW + 1 {
svg.Box(x, y, brickW, brickH, Color)
}
// Alternate the x offset for every row of bricks
if ofs == 0 {
ofs = -brickH
} else {
ofs = 0
}
}
case PatternGradientDown: // Gradient Banner
ur, _ := strconv.ParseUint(Color[1:3], 16, 0)
ug, _ := strconv.ParseUint(Color[3:5], 16, 0)
ub, _ := strconv.ParseUint(Color[5:7], 16, 0)
r := int(ur)
g := int(ug)
b := int(ub)
a := 1.0
for y := 0; y < fullH; y++ {
a = 1.0 - (float64(y) / float64(fullH))
svg.Box(0, y, fullW, 1, string(tinysvg.ColorBytesAlpha(r, g, b, a)))
}
case PatternGradientUp: // Base Gradient Banner
ur, _ := strconv.ParseUint(Color[1:3], 16, 0)
ug, _ := strconv.ParseUint(Color[3:5], 16, 0)
ub, _ := strconv.ParseUint(Color[5:7], 16, 0)
r := int(ur)
g := int(ug)
b := int(ub)
a := 1.0
for y := 0; y < fullH; y++ {
a = float64(y) / float64(fullH)
svg.Box(0, y, fullW, 1, string(tinysvg.ColorBytesAlpha(r, g, b, a)))
}
case PatternCreeper: // Black/Dyed Creeper Charge Banner
// eyes
svg.Box(sixthW-tenthW/2, thirdH-tenthH/2, halfW/2, halfW/2, Color)
svg.Box(fullW-(sixthW+halfW/2)+tenthW/2, thirdH-tenthH/2, halfW/2, halfW/2, Color)
// nose
svg.Line(halfW, thirdH+tenthH, halfW, halfH+(halfW/3), halfW/2, Color)
// whiskers
svg.Box(sixthW+sixthW, thirdH+fifthH, tenthW, halfW/2, Color)
svg.Box(fullW-(sixthW+sixthW)-tenthW, thirdH+fifthH, tenthW, halfW/2, Color)
case PatternSkull: // Black/Dyed Skull Charge Banner
hy := (tenthH / 2)
boxx := fifthW + (tenthW / 2)
boxy := halfH - sixthH
// Top of the head
svg.Box(boxx, boxy-hy, halfW, hy*2, Color)
// Side of face
svg.Box(boxx, boxy+hy, hy, hy*2, Color)
svg.Box(boxx+(halfW-hy), boxy+hy, hy, hy*2, Color)
// Nose
svg.Box(boxx+(halfW-hy)/2, boxy+hy, hy, hy/2, Color)
// Cheeks
svg.Box(boxx+(halfW-hy)/2-hy, boxy+hy+hy/2, hy, hy/2, Color)
svg.Box(boxx+(halfW-hy)/2+hy, boxy+hy+hy/2, hy, hy/2, Color)
// Bottom of face
svg.Box(boxx, boxy+hy*3-(hy/2), halfW, 1, Color)
// The cross
ofs := thirdH // offset from bottom
svg.Line(sixthW, fullH-(sixthH+ofs), fullW-sixthW, fullH-ofs, tenthW, Color)
svg.Line(fullW-sixthW, fullH-(sixthH+ofs), sixthW, fullH-ofs, tenthW, Color)
// Ends of cross
svg.Circle(hy+hy/2, halfH+hy/2, hy/2, Color)
svg.Circle(fullW-(hy+hy/2), halfH+hy/2, hy/2, Color)
svg.Circle(hy+hy/2, halfH+hy*4-hy/2, hy/2, Color)
svg.Circle(fullW-(hy+hy/2), halfH+hy*4-hy/2, hy/2, Color)
case PatternFlower: // Black/Dyed Flower Charge Banner
svg.Circle(halfW, halfH, sixthW, Color)
numcircles := 10
step := (math.Pi * 2.0) / float64(numcircles)
radius := fullW / 20
spacing := float64(thirdW)
linet := tenthW / 2 // line thickness
jointt := tenthW / 2 // line joint thickness (circles)
var (
linex, liney, oldx, oldy, firstx, firsty int
)
for r := 0.0; r < math.Pi*2.0; r += step {
// Draw outer circles
x := int(math.Floor(math.Cos(r)*spacing+0.5)) + halfW
y := int(math.Floor(math.Sin(r)*spacing+0.5)) + halfH
svg.Circle(x, y, radius, Color)
// Draw circle made out of lines
oldx = linex
oldy = liney
linex = int(math.Floor(math.Cos(r)*spacing*0.8+0.5)) + halfW
liney = int(math.Floor(math.Sin(r)*spacing*0.8+0.5)) + halfH
if oldx == 0 {
firstx = linex
firsty = liney
} else {
svg.Line(oldx, oldy, linex, liney, linet, Color)
svg.Circle(linex, liney, jointt, Color)
}
}
svg.Line(linex, liney, firstx, firsty, linet, Color)
svg.Circle(firstx, firsty, jointt, Color)
case PatternLogo: // Black/Dyed Mojang Charge Banner
numsteps := 10
step := (math.Pi * 2.0) / float64(numsteps)
spacing := float64(thirdW)
linet := fifthW // line thickness
var (
linex, liney, oldx, oldy int
)
for r := math.Pi / 2; r < (math.Pi*2.0)-(math.Pi/2); r += step {
// Draw circle made out of lines
oldx = linex
oldy = liney
linex = int(math.Floor(math.Cos(r)*spacing*0.8+0.5)) + halfW
liney = int(math.Floor(math.Sin(r)*spacing*0.8+0.5)) + halfH
if oldx == 0 {
svg.Line(linex, liney, fullW-fifthW, liney, linet, Color)
} else {
svg.Line(oldx, oldy, linex, liney, linet, Color)
}
}
svg.Line(linex, liney, fullW-fifthW, liney+fifthW, linet, Color)
svg.Line(fullW-thirdW, thirdH, (fullW-thirdW)+tenthW, thirdH+tenthW, tenthW, Color)
case PatternFull:
svg.Box(0, 0, fullW, fullH, Color)
}
}
func (pat *Pattern) PatternString() string {
desc, ok := PatternDesc[pat.pattern]
if !ok {
return "Unknown Pattern"
}
return desc
}
// TODO: Switch the switch with a lookup like in PatternString
func (pat *Pattern) ColorString() string {
switch pat.color {
case ColorWhite:
return "White"
case ColorOrange:
return "Orange"
case ColorMagenta:
return "Magenta"
case ColorLightBlue:
return "LightBlue"
case ColorYellow:
return "Yellow"
case ColorLime:
return "Lime"
case ColorPink:
return "Pink"
case ColorGray:
return "Gray"
case ColorLightGray:
return "LightGray"
case ColorCyan:
return "Cyan"
case ColorPurple:
return "Purple"
case ColorBlue:
return "Blue"
case ColorBrown:
return "Brown"
case ColorGreen:
return "Green"
case ColorRed:
return "Red"
case ColorBlack:
return "Black"
case ColorBrightWhite:
return "Custom color"
default:
return "Unknown color"
}
}
func (pat *Pattern) String() string {
return pat.ColorString() + " " + pat.PatternString()
}
<file_sep>/ga_test.go
package mcbanner
import (
//"fmt"
//"io/ioutil"
"testing"
)
func TestGA(t *testing.T) {
//pngbytes, err := ioutil.ReadFile("web/public/img/c1.png")
//if err != nil {
// t.Errorf("%s\n", "Could not read: web/public/img/c1.png")
//}
//FindBest(Likeness, pngbytes)
//t.Errorf("%s\n", s)
//const in, out = 4, 2
//if x := Sqrt(in); x != out {
// t.Errorf("Sqrt(%v) = %v, want %v", in, x, out)
//}
}
func TestFitness(t *testing.T) {
//sol := NewSolution()
//fmt.Println(sol)
//fmt.Println("fitness:", sol.fitness())
}
<file_sep>/TODO.md
Plans
=====
- [ ] A custom image renderer for the subset of SVG that is in use
- [ ] Render smaller images when evolving
- [ ] Random generator counter
- [ ] Better text in the howto (not "Black Black/Dyed [...] Banner")
- [ ] New page for comparing an uploaded image with a randomly generated banner
- [ ] Subdomain instead of port :3000
- [ ] Rate limit
| 70405c6fa83997c908865ddef91ea815714827bb | [
"Markdown",
"Go Module",
"Go",
"Shell"
] | 18 | Go | xyproto/mcbanner | 323ba99525a7eeb34b6cfd08ef0bdd1626b324a6 | c0e8364501bd962b02d9469da205fbddbf1d840d |
refs/heads/master | <file_sep>from abc import ABCMeta, abstractmethod
from ojai.DocumentStream import DocumentStream
class QueryResult(DocumentStream):
__metaclass__ = ABCMeta
@abstractmethod
def get_query_plan(self):
"""Returns a query plan that was used for this QueryResults"""
raise NotImplementedError("This should have been implemented.")
| 1dbd0460e31a8113f616423cf08f3ef4c871ae59 | [
"Python"
] | 1 | Python | smakireddy/ojai | 941b229dda257fe61af33f770b3084c69047afcf | 42c769f01c14b7bd0d6c36111325321d53ce9e85 |
refs/heads/master | <repo_name>trevoruehlinx1/todo-react<file_sep>/src/App.js
import React, { Component } from 'react';
import './App.css';
import TaskList from './Components/TaskList';
import TaskForm from './Components/TaskForm';
class App extends Component {
constructor(props){
super(props);
let tasks = [];
if(!localStorage.getItem('TASKS')) {
tasks = [
{task: 'Go to Dentist', isComplete: false},
{task: 'Do Gardening', isComplete: true},
{task: 'Renew Library Account', isComplete: false},
];
}
else
tasks = JSON.parse(localStorage.getItem('TASKS'));
this.state = {
task: "",
tasks:tasks,
isComplete:false
};
this.deleteTask = this.deleteTask.bind(this);
this.toggleTaskStatus = this.toggleTaskStatus.bind(this);
this.addTask = this.addTask.bind(this);
}
render() {
localStorage.setItem('TASKS', JSON.stringify(this.state.tasks));
return (
<div className="App">
The App
<TaskForm onSubmit= {this.addTask} />
<TaskList tasks= {this.state.tasks} deleteTask={this.deleteTask.bind(this)} toggleTaskStatus={this.toggleTaskStatus.bind(this)}/>
</div>
);
}
deleteTask(taskIndex) {
console.log("on delete task");
let tasks = JSON.parse(JSON.stringify(this.state.tasks));
tasks.splice(taskIndex, 1);
this.setState({tasks});
}
toggleTaskStatus(index) {
console.log(index);
let tasks = JSON.parse(JSON.stringify(this.state.tasks));
tasks[index].isComplete = !tasks[index].isComplete;
this.setState({tasks:tasks});
}
addTask(task) {
console.log("add task");
const tasks = this.state.tasks;
let newTask = {
task,
isComplete: false,
};
//let parentDiv = document.getElementById('addTask').parentElement;
//if(task === '') {
//parentDiv.classList.add('has-error');
//} else {
//parentDiv.classList.remove('has-error');
tasks.push(newTask);
this.setState(tasks);
//}
}
}
export default App;
<file_sep>/src/Components/Task.js
import React, { Component } from 'react';
class Task extends Component{
toggleTask()
{
this.props.toggleTaskStatus(this.props.index);
}
render(){
const task = this.props.task;
//const toggleTaskStatus = this.props.toggleTaskStatus;
const onDeleteTask = this.onDeleteTask.bind(this);
const isComplete = this.props.isComplete;
return(
<li className="list-group-item checkbox">
<div className="row">
<div className="col-md-1 col-xs-1 col-lg-1 col-sm-1 checkbox">
<label><input id="toggleTaskStatus" type="checkbox" onChange={this.toggleTask.bind(this)} checked={(isComplete?'checked':'')} /></label>
</div>
<div className={"col-md-10 col-xs-10 col-lg-10 col-sm-10 task-text "+ (isComplete?'complete':'')}>
{task.task}
</div>
<div className="col-md-1 col-xs-1 col-lg-1 col-sm-1 delete-icon-area">
<a className="" href="/" onClick={onDeleteTask} > <i id="deleteTask" data-id="{index}" className="delete-icon glyphicon glyphicon-trash"></i></a>
</div>
</div>
</li>
)
}
onDeleteTask(event) {
event.preventDefault();
const deleteTask = this.props.deleteTask;
let index = this.props.index;
deleteTask(index);
}
}
export default Task; | 17ccc429222f8f96e925b9bbdadcf1d43ab5e140 | [
"JavaScript"
] | 2 | JavaScript | trevoruehlinx1/todo-react | b8cc29dc590bfaad1a6bfe3e30bf9d6ee950ead1 | a445dbfc442997ff6bd9a33bb72db86e0d4f07f9 |
refs/heads/master | <repo_name>Ikutzu/EntityComponentSystem<file_sep>/EntityComponentSystem/Game.h
#pragma once
#include "GameObject.h"
#include "SystemManager.h"
#include "RenderSystem.h"
#include "RenderComponentFactory.h"
#include "Transform.h"
#include <vector>
class Game
{
public:
Game(sf::RenderWindow* win);
~Game();
void Update(float dt);
void Draw();
private:
void UpdateControls(float dt);
SystemManager systemManager;
sf::RenderWindow* window;
GameObject* player;
std::vector<GameObject*> gameObjectList;
};
<file_sep>/EntityComponentSystem/main.cpp
#include "Game.h"
#include "GameObject.h"
#include "Render.h"
#include "Transform.h"
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "EntityComponentSystem");
sf::Clock clock;
Game game(&window);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
sf::Time dt = clock.restart();
game.Update(dt.asSeconds());
window.clear();
game.Draw();
window.display();
}
return 0;
}<file_sep>/EntityComponentSystem/RenderComponentFactory.h
#pragma once
#include "Render.h"
class RenderComponentFactory
{
public:
static RenderComponentFactory* GetInstance();
Render* CreateRenderComponent(std::string textureName);
private:
RenderComponentFactory();
~RenderComponentFactory();
static RenderComponentFactory* instance;
};
<file_sep>/EntityComponentSystem/Render.h
#pragma once
#include "Component.h"
#include <SFML/Graphics.hpp>
class Render : public Component
{
public:
Render();
~Render();
sf::Texture* texture;
sf::VertexArray vertices;
void SetSize(sf::Vector2f size);
};<file_sep>/EntityComponentSystem/SystemManager.h
#pragma once
#include "GameObject.h"
#include "RenderSystem.h"
#include "System.h"
#include <unordered_map>
#include <typeinfo>
#include <vector>
class SystemManager
{
public:
~SystemManager();
void Update(std::vector<GameObject*>* objectList);
void AddSystem(System* newSystem);
private:
using SystemList = std::unordered_map < const std::type_info *, System* >;
SystemList systems;
};<file_sep>/EntityComponentSystem/SystemManager.cpp
#include "SystemManager.h"
SystemManager::~SystemManager()
{
SystemList::iterator it;
for (it = systems.begin(); it != systems.end();)
{
delete it->second;
it++;
}
systems.clear();
}
void SystemManager::Update(std::vector<GameObject*>* objectList)
{
if (systems.count(&typeid(RenderSystem)) != 0)
{
for (int i = 0; i < objectList->size(); i++)
{
GameObject* tempPointer = objectList->at(i);
static_cast<RenderSystem*>(systems[&typeid(RenderSystem)])->Update(tempPointer);
}
}
}
void SystemManager::AddSystem(System* newSystem)
{
systems[&typeid(*newSystem)] = newSystem;
//components.insert(make_pair(&typeid(*newComponent)), newComponent); //#include <utility>
}
<file_sep>/EntityComponentSystem/Game.cpp
#include "Game.h"
Game::Game(sf::RenderWindow* win)
{
window = win;
RenderSystem* tempSys = new RenderSystem();
tempSys->window = win;
systemManager.AddSystem(tempSys);
GameObject* testi = new GameObject;
testi->AddComponent(RenderComponentFactory::GetInstance()->CreateRenderComponent("pslogo.png"));
//testi.GetComponent<Render>()->texture->setSmooth(true);
Transform* tempTransform = new Transform;
tempTransform->origin = sf::Vector2f(32, 32);
tempTransform->position = sf::Vector2f(400, 300);
testi->AddComponent(tempTransform);
gameObjectList.push_back(testi);
player = gameObjectList.at(0);
}
Game::~Game()
{
for (int i = 0; i < gameObjectList.size(); i++)
{
delete gameObjectList[i];
}
gameObjectList.clear();
}
void Game::Update(float dt)
{
UpdateControls(dt);
}
void Game::Draw()
{
systemManager.Update(&gameObjectList);
}
void Game::UpdateControls(float dt)
{
player->GetComponent<Transform>()->rotation += 50 * dt;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q))
player->GetComponent<Transform>()->rotation += 100 * dt;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
player->GetComponent<Transform>()->rotation -= 100 * dt;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
player->GetComponent<Transform>()->scale.x += 10 * dt;
player->GetComponent<Transform>()->scale.y += 10 * dt;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
player->GetComponent<Transform>()->scale.x -= 10 * dt;
player->GetComponent<Transform>()->scale.y -= 10 * dt;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
player->GetComponent<Transform>()->position.x -= 100 * dt;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
player->GetComponent<Transform>()->position.x += 100 * dt;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
player->GetComponent<Transform>()->position.y -= 100 * dt;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
player->GetComponent<Transform>()->position.y += 100 * dt;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
window->close();
}<file_sep>/EntityComponentSystem/RenderSystem.h
#pragma once
#include "GameObject.h"
#include "Render.h"
#include "System.h"
#include "Transform.h"
class RenderSystem : public System
{
public:
void Update(GameObject* obj);
sf::RenderWindow* window;
sf::RenderStates state;
};
<file_sep>/EntityComponentSystem/Transform.h
#pragma once
#include "Component.h"
#include <SFML/System.hpp>
class Transform : public Component
{
public:
Transform();
~Transform();
sf::Vector2f position;
sf::Vector2f scale;
sf::Vector2f origin;
float rotation;
};
<file_sep>/EntityComponentSystem/RenderComponentFactory.cpp
#include "RenderComponentFactory.h"
RenderComponentFactory* RenderComponentFactory::instance = nullptr;
RenderComponentFactory* RenderComponentFactory::GetInstance()
{
if (instance == nullptr)
instance = new RenderComponentFactory;
return instance;
}
Render* RenderComponentFactory::CreateRenderComponent(std::string textureName)
{
Render* tempRender = new Render;
tempRender->texture = new sf::Texture;
tempRender->texture->loadFromFile(textureName);
tempRender->SetSize(sf::Vector2f(64.0, 64.0));
return tempRender;
}
RenderComponentFactory::RenderComponentFactory()
{
}
RenderComponentFactory::~RenderComponentFactory()
{
delete instance;
}
<file_sep>/EntityComponentSystem/RenderSystem.cpp
#include "RenderSystem.h"
void RenderSystem::Update(GameObject* obj)
{
Transform* tempTransform = obj->GetComponent<Transform>();
Render* tempRender = obj->GetComponent<Render>();
if (tempTransform == nullptr)
printf("RenderSystem::Update: Entity has no Transform component");
else if (tempRender == nullptr)
printf("RenderSystem::Update: Entity has no Render component");
else
{
state = state.Default;
state.transform.translate(-tempTransform->origin).rotate(tempTransform->rotation, tempTransform->position + tempTransform->origin).scale(tempTransform->scale, tempTransform->position + tempTransform->origin).translate(tempTransform->position);
state.texture = tempRender->texture;
window->draw(&tempRender->vertices[0], tempRender->vertices.getVertexCount(), sf::Triangles, state);
}
}<file_sep>/EntityComponentSystem/System.h
#pragma once
class System
{
public:
virtual void Update(){};
};<file_sep>/EntityComponentSystem/Transform.cpp
#include "Transform.h"
Transform::Transform() : position(0.0f, 0.0f), scale(1.0f, 1.0f), rotation(0)
{
type = TRANSFORM;
}
Transform::~Transform()
{
}<file_sep>/EntityComponentSystem/GameObject.h
#pragma once
#include "Component.h"
#include <unordered_map>
#include <typeinfo>
class GameObject
{
public:
GameObject();
~GameObject();
void AddComponent(Component* newComponent);
template<typename T> T* GetComponent();
private:
using ComponentList = std::unordered_map < const std::type_info *, Component* > ;
ComponentList components;
};
template<typename T>
T* GameObject::GetComponent()
{
if (components.count(&typeid(T)) != 0)
return static_cast<T*>(components[&typeid(T)]);
else
return nullptr;
//ComponentList::const_iterator position = components.find(&typeid(T));
//if (position != components.end())
// return static_cast<T*>(position->second);
//else
// return nullptr;
}<file_sep>/EntityComponentSystem/Component.h
#pragma once
class Component
{
public:
enum compType{
RENDER,
TRANSFORM
};
Component(){};
virtual ~Component(){};
compType GetType(){ return type; }
compType type;
};
<file_sep>/EntityComponentSystem/GameObject.cpp
#include "GameObject.h"
GameObject::GameObject()
{
}
GameObject::~GameObject()
{
std::unordered_map<const std::type_info *, Component*>::iterator it;
for (it = components.begin(); it != components.end();)
{
delete it->second;
it++;
}
components.clear();
}
void GameObject::AddComponent(Component* newComponent)
{
components[&typeid(*newComponent)] = newComponent;
//components.insert(make_pair(&typeid(*newComponent)), newComponent); //#include <utility>
}
<file_sep>/EntityComponentSystem/Render.cpp
#include "Render.h"
Render::Render()
{
type = RENDER;
for (int i = 0; i < 6; i++)
vertices.append(sf::Vertex());
vertices[0].texCoords = sf::Vector2f(0, 64);
vertices[1].texCoords = sf::Vector2f(64, 64);
vertices[2].texCoords = sf::Vector2f(0, 0);
vertices[3].texCoords = sf::Vector2f(64, 64);
vertices[4].texCoords = sf::Vector2f(0, 0);
vertices[5].texCoords = sf::Vector2f(64, 0);
vertices[0].color = sf::Color::White;
vertices[1].color = sf::Color::White;
vertices[2].color = sf::Color::White;
vertices[3].color = sf::Color::White;
vertices[4].color = sf::Color::White;
vertices[5].color = sf::Color::White;
}
Render::~Render()
{
delete texture;
}
void Render::SetSize(sf::Vector2f size)
{
vertices[0].position = sf::Vector2f(0, size.y);
vertices[1].position = sf::Vector2f(size.x, size.y);
vertices[2].position = sf::Vector2f(0, 0);
vertices[3].position = sf::Vector2f(size.x, size.y);
vertices[4].position = sf::Vector2f(0, 0);
vertices[5].position = sf::Vector2f(size.x, 0);
} | 7ee9389044b0ebcd6e44d4676048c3599be6ffa9 | [
"C++"
] | 17 | C++ | Ikutzu/EntityComponentSystem | b3cefe8917756cb61800b093b0257d6c25c919b0 | 5dbc56856f8032b4d66db7b7b0d90fbe300b4229 |
refs/heads/master | <file_sep>[package]
name = "rust-bot"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
[dependencies]
curl = "0.4.11"
serde_json = "1.0.9"
sha2 = "*"
hmac = "*"
<file_sep>use curl::easy::{Easy, List};
use serde_json;
use serde_json::{Value, Error};
use sha2::Sha512;
use hmac::{Hmac, Mac};
pub struct Bittrex {
api_key: String,
secret: String,
set_sign: bool,
}
//const (
//bittrexMaxOpenOrders = 500
//bittrexMaxOrderCountPerDay = 200000
//
//// Returned messages from Bittrex API
//bittrexAddressGenerating = "ADDRESS_GENERATING"
//bittrexErrorMarketNotProvided = "MARKET_NOT_PROVIDED"
//bittrexErrorInvalidMarket = "INVALID_MARKET"
//bittrexErrorAPIKeyInvalid = "APIKEY_INVALID"
//bittrexErrorInvalidPermission = "INVALID_PERMISSION"
//)
impl Bittrex {
pub fn new() -> Self {
Bittrex {
api_key: "6cde5ce871174660a5e496d55c1d763c".to_string(),
secret: "01eb40e18539435abae46f2f11af9a87".to_string(),
set_sign: false
}
}
pub fn request(&self, url: &str) -> Result<Value, Error> {
let mut buf = Vec::new();
let mut handler = Easy::new();
let url = if self.set_sign == false {
format!("https://bittrex.com/api/v1.1/{}", url)
} else {
let u = format!("https://bittrex.com/api/v1.1/{}&nonce={}", url, "1000");
handler.http_headers(self.add_sign(u.as_ref()).unwrap()).unwrap();
// handler.verbose(true).unwrap();
u
};
handler.url(url.as_ref()).unwrap();
{
let mut transfer = handler.transfer();
transfer.write_function(|new_data| {
buf.extend_from_slice(new_data);
Ok(new_data.len())
}).unwrap();
transfer.perform().unwrap();
}
Ok(serde_json::from_slice(&buf).unwrap())
}
// $apikey='xxx';
// $apisecret='xxx';
// $nonce=time();
// $uri='https://bittrex.com/api/v1.1/market/getopenorders?apikey='.$apikey.'&nonce='.$nonce;
// $sign=hash_hmac('sha512',$uri,$apisecret);
// $ch = curl_init($uri);
// curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
// $execResult = curl_exec($ch);
// $obj = json_decode($execResult);
fn add_sign(&self, url: &str) -> Result<List, Error> {
let mut hmac = Hmac::<Sha512>::new(self.secret.as_bytes()).unwrap();
hmac.input(url.as_bytes());
let sign = hmac.result().code();
let header_api_sign = format!("apisign: {:X}", sign);
let mut list = List::new();
list.append(header_api_sign.as_ref()).unwrap();
Ok(list)
}
}
//// Public requests
//bittrexAPIGetMarkets = "public/getmarkets"
//bittrexAPIGetCurrencies = "public/getcurrencies"
//bittrexAPIGetTicker = "public/getticker"
//bittrexAPIGetMarketSummaries = "public/getmarketsummaries"
//bittrexAPIGetMarketSummary = "public/getmarketsummary"
//bittrexAPIGetOrderbook = "public/getorderbook"
//bittrexAPIGetMarketHistory = "public/getmarkethistory"
pub trait Public {
fn get_markets(&mut self) -> Result<Value, Error>;
fn get_currencies(&mut self) -> Result<Value, Error>;
fn get_ticker(&mut self, market: &str) -> Result<Value, Error>;
fn get_market_summaries(&mut self) -> Result<Value, Error>;
fn get_market_summary(&mut self, market: &str) -> Result<Value, Error>;
fn get_order_book(&mut self, market: &str, m_type: &str) -> Result<Value, Error>;
fn get_market_history(&mut self, market: &str) -> Result<Value, Error>;
}
impl Public for Bittrex {
fn get_markets(&mut self) -> Result<Value, Error> {
self.set_sign = false;
self.request("public/getmarkets")
}
fn get_currencies(&mut self) -> Result<Value, Error> {
self.set_sign = false;
self.request("public/getcurrencies")
}
fn get_ticker(&mut self, market: &str) -> Result<Value, Error> {
self.set_sign = false;
let path = format!("public/getticker?market={}", market);
self.request(path.as_ref())
}
fn get_market_summaries(&mut self) -> Result<Value, Error> {
self.set_sign = false;
self.request("public/getmarketsummaries")
}
fn get_market_summary(&mut self, market: &str) -> Result<Value, Error> {
self.set_sign = false;
let path = format!("public/getmarketsummary?market={}", market);
self.request(path.as_ref())
}
fn get_order_book(&mut self, market: &str, m_type: &str) -> Result<Value, Error> {
self.set_sign = false;
let path = format!("public/getmarketsummary?market={}&type={}", market, m_type);
self.request(path.as_ref())
}
fn get_market_history(&mut self, market: &str) -> Result<Value, Error> {
self.set_sign = false;
let path = format!("public/getmarketsummary?market={}", market);
self.request(path.as_ref())
}
}
//// Market requests
//bittrexAPIBuyLimit = "market/buylimit"
//bittrexAPISellLimit = "market/selllimit"
//bittrexAPICancel = "market/cancel"
//bittrexAPIGetOpenOrders = "market/getopenorders"
pub trait Market {
fn buy_limit(&mut self, market: &str, qty: f32, rate: f32) -> Result<Value, Error>;
fn sell_limit(&mut self, market: &str, qty: f32, rate: f32) -> Result<Value, Error>;
fn cancel(&mut self, uuid: &str) -> Result<Value, Error>;
fn get_open_orders(&mut self, market: &str) -> Result<Value, Error>;
}
impl Market for Bittrex {
// parameter required description
//
// market required a string literal for the market (ex: BTC-LTC)
// quantity required the amount to purchase
// rate required the rate at which to place the order.
fn buy_limit(&mut self, market: &str, qty: f32, rate: f32) -> Result<Value, Error> {
self.set_sign = true;
let path = format!("market/buylimit?apikey={}&market={}&quantity={}&rate={}", self.api_key, market, qty, rate);
self.request(path.as_ref())
}
fn sell_limit(&mut self, market: &str, qty: f32, rate: f32) -> Result<Value, Error> {
self.set_sign = true;
let path = format!("market/selllimit?apikey={}&market={}&quantity={}&rate={}", self.api_key, market, qty, rate);
self.request(path.as_ref())
}
fn cancel(&mut self, uuid: &str) -> Result<Value, Error> {
self.set_sign = true;
let path = format!("market/cancel?apikey={}&uuid={}", self.api_key, uuid);
self.request(path.as_ref())
}
fn get_open_orders(&mut self, market: &str) -> Result<Value, Error> {
self.set_sign = true;
let path = format!("market/cancel?apikey={}&market={}", self.api_key, market);
self.request(path.as_ref())
}
}
//// Account requests
//bittrexAPIGetBalances = "account/getbalances"
//bittrexAPIGetBalance = "account/getbalance"
//bittrexAPIGetDepositAddress = "account/getdepositaddress"
//bittrexAPIWithdraw = "account/withdraw"
//bittrexAPIGetOrder = "account/getorder"
//bittrexAPIGetOrderHistory = "account/getorderhistory"
//bittrexAPIGetWithdrawalHistory = "account/getwithdrawalhistory"
//bittrexAPIGetDepositHistory = "account/getdeposithistory"
pub trait Account {
fn get_balances(&mut self) -> Result<Value, Error>;
fn get_balance(&mut self, currency: &str) -> Result<Value, Error>;
fn get_deposit_address(&mut self, currency: &str) -> Result<Value, Error>;
fn withdraw(&mut self, currency: &str, qty: f32, address: &str) -> Result<Value, Error>;
fn get_order(&mut self, uuid: &str) -> Result<Value, Error>;
fn get_order_history(&mut self, market: &str) -> Result<Value, Error>;
fn get_withdraw_history(&mut self, currency: &str) -> Result<Value, Error>;
fn get_deposit_history(&mut self, currency: &str) -> Result<Value, Error>;
}
impl Account for Bittrex {
fn get_balances(&mut self) -> Result<Value, Error> {
self.set_sign = true;
let path = format!("account/getbalances?apikey={}", self.api_key);
self.request(path.as_ref())
}
fn get_balance(&mut self, currency: &str) -> Result<Value, Error> {
self.set_sign = true;
let path = format!("account/getbalance?apikey={}¤cy={}", self.api_key, currency);
self.request(path.as_ref())
}
fn get_deposit_address(&mut self, currency: &str) -> Result<Value, Error> {
self.set_sign = true;
let path = format!("account/getdepositaddress?apikey={}¤cy={}", self.api_key, currency);
self.request(path.as_ref())
}
fn withdraw(&mut self, currency: &str, qty: f32, address: &str) -> Result<Value, Error> {
self.set_sign = true;
let path = format!("account/withdraw?apikey={}¤cy={}&quantity={}&address={}", self.api_key, currency, qty, address);
self.request(path.as_ref())
}
fn get_order(&mut self, uuid: &str) -> Result<Value, Error> {
self.set_sign = true;
let path = format!("account/getorder?apikey={}&uuid={}", self.api_key, uuid);
self.request(path.as_ref())
}
fn get_order_history(&mut self, market: &str) -> Result<Value, Error> {
self.set_sign = true;
let path = if market == "" {
format!("account/getorderhistory?apikey={}", self.api_key)
} else {
format!("account/getorderhistory?apikey={}&market={}", self.api_key, market)
};
self.request(path.as_ref())
}
fn get_withdraw_history(&mut self, currency: &str) -> Result<Value, Error> {
self.set_sign = true;
let path = if currency == "" {
format!("account/getwithdrawalhistory?apikey={}", self.api_key)
} else {
format!("account/getwithdrawalhistory?apikey={}¤cy={}", self.api_key, currency)
};
self.request(path.as_ref())
}
fn get_deposit_history(&mut self, currency: &str) -> Result<Value, Error> {
self.set_sign = true;
let path = if currency == "" {
format!("account/getdeposithistory?apikey={}", self.api_key)
} else {
format!("account/getdeposithistory?apikey={}¤cy={}", self.api_key, currency)
};
self.request(path.as_ref())
}
}<file_sep>extern crate curl;
extern crate serde_json;
extern crate sha2;
extern crate hmac;
mod httpclient;
use httpclient::{Bittrex, Public, Market, Account};
fn main() {
let mut bittrex = Bittrex::new();
//public methods
// let public_data = bittrex.get_markets().unwrap();
// println!("{:?}", public_data);
// let public_data = bittrex.get_currencies().unwrap();
// println!("{:?}", public_data);
// let public_data = bittrex.get_ticker("BTC-LTC").unwrap();
// println!("{:?}", public_data);
// let public_data = bittrex.get_market_summaries().unwrap();
// println!("{:?}", public_data);
let public_data = bittrex.get_order_book("BTC-LTC", "both").unwrap();
println!("{:?}", public_data);
// let public_data = bittrex.get_market_history("BTC-LTC").unwrap();
// println!("{:?}", public_data);
//market methods
// let market = bittrex.buy_limit("USDT-ETH", 0.1, 0.1).unwrap();
// println!("{:?}", market);
// let market = bittrex.sell_limit("USDT-ETH", 0.1, 0.1).unwrap();
// println!("{:?}", market);
// let market = bittrex.cancel("614c34e4-8d71-11e3-94b5-425861b86ab6").unwrap();
// println!("{:?}", market);
let market = bittrex.get_open_orders("USDT-ETH").unwrap();
println!("{:?}", market);
//account methods
let account = bittrex.get_deposit_history("").unwrap();
println!("{:?}", account);
let account = bittrex.get_order_history("USDT-BTG").unwrap();
println!("{:?}", account);
let account = bittrex.get_order("207b559c-476c-4689-b6d7-e4b62b4831ea").unwrap();
println!("{:?}", account);
let account = bittrex.get_deposit_address("BTC").unwrap();
println!("{:?}", account);
let account = bittrex.get_balance("BTC").unwrap();
println!("{:?}", account);
let account = bittrex.get_balances().unwrap();
println!("{:?}", account);
let account = bittrex.withdraw("ETH", 0.1, "0x3315C11aC4c20250109830267FeD98626bB979Dc").unwrap();
println!("{:?}", account);
}
| af94ffe0fe6c298c716446cf39422af6a1a704b4 | [
"TOML",
"Rust"
] | 3 | TOML | sinyakinilya/bittrex-client | e9be445482c54b9d113d7e6d8814144724396801 | 44a2a35cbede765d2adea10f968489cf0ad13e7d |
refs/heads/master | <file_sep>(function() {
$(document).ready(function() {
$('#secondary').waypoint(function(direction) {
var sectionCopy = $('#secondary .section-copy');
if (direction === 'down') {
sectionCopy
.css('display', 'block')
.addClass('fadeIn');
$('nav').addClass('bg-on');
}
else if (direction === 'up') {
sectionCopy
.removeClass('fadeIn')
.animate({opacity: 0}, function() {
$(this).css({
display: 'none',
opacity: 1
});
});
$('nav').removeClass('bg-on');
}
}, { offset: 300 });
$('#learnMore').waypoint(function(direction) {
var sectionCopy = $('#learnMore .section-copy');
if (direction === 'down') {
sectionCopy
.css('display', 'block')
.addClass('fadeIn');
}
else if (direction === 'up') {
sectionCopy
.removeClass('fadeIn')
.animate({opacity: 0}, function() {
$(this).css({
display: 'none',
opacity: 1
});
});
}
}, { offset: 300 });
$('#locations').waypoint(function(direction) {
var sectionCopy = $('#locations .location-copy');
if (direction === 'down') {
sectionCopy
.css('display', 'block')
.addClass('fadeInLeftBig');
}
else if (direction === 'up') {
sectionCopy
.removeClass('fadeInLeftBig')
.animate({opacity: 0}, function() {
$(this).css({
display: 'none',
opacity: 1
});
});
}
}, { offset: 500 });
});
})(); | 6254c6c9dc4164a3023488b188b054e0faff3839 | [
"JavaScript"
] | 1 | JavaScript | lancasja/startup-pitch-site-2 | 8e40ee6b20d96ff28a65d32de073be7633546bc0 | 6792631627fe210ccf0a0fd87b9e267761092533 |
refs/heads/master | <file_sep>import javax.swing.*;
/**
* @author paulalan
* @create 2019/10/4 11:34
*/
public abstract class MyJPanel extends JPanel
{
protected ManualAlgorithm manualAlgorithm;
public abstract void update();
}
<file_sep>import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author paulalan
* @create 2019/9/27 19:54
*/
public class Terrain extends MyJPanel
{
private int rows;
private int cols;
private JLabel sumLabel;
public Terrain(int rows, int cols,double intelligence)
{
HashMap<JLabel, Integer> terrain = new HashMap<>();
this.rows = rows;
this.cols = cols;
setLayout(new BorderLayout());
JButton autoCal = new JButton();
autoCal.setText("Auto calculate shortest path");
sumLabel = new JLabel();
sumLabel.setVisible(true);
sumLabel.setText("Current Path: ");
sumLabel.setHorizontalAlignment(SwingConstants.CENTER);
sumLabel.setVerticalAlignment(SwingConstants.CENTER);
JPanel terrainPanel = new JPanel();
terrainPanel.setLayout(new GridLayout(rows, cols, 0, 0));
// HashMap<JLabel, Integer> terrain = new HashMap<>();
int[][] array = new int[rows][cols];
for (int i = 1; i <= rows * cols; i++)
{
int randomNumber = (int) (Math.random() * 20 - 5);
JLabel jl = new JLabel(String.valueOf(randomNumber));
terrain.put(jl, i);
jl.setHorizontalAlignment(SwingConstants.CENTER);
jl.setBorder(BorderFactory.createLineBorder(Color.black));
jl.setOpaque(true);
jl.setBackground(Color.white);
ManualAlgorithm ma = new ManualAlgorithm();
this.manualAlgorithm = ma;
this.manualAlgorithm.attach(this);
if (i > (rows - 1) * cols)
{
jl.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
for (int i = (rows - 1) * cols + 1; i <= rows * cols; i++)
{
if (!Util.getKey(terrain, i).equals(jl))
{
Util.getKey(terrain, i).removeMouseListener(
Util.getKey(terrain, i).getMouseListeners()[0]);
}
}
try
{
ma.clickFun(jl, terrain, cols, rows, array,intelligence);
} catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
});
}
terrainPanel.add(jl);
}
for (int i = 1; i <= rows; i++)
{
for (int j = 1 + (i - 1) * cols; j <= cols * i; j++)
{
if (j % cols == 0)
{
array[i - 1][cols - 1] = Integer.parseInt(Util.getKey(terrain, j).getText());
} else
{
array[i - 1][(j % cols) - 1] = Integer.parseInt(Util.getKey(terrain, j).getText());
}
}
}
terrainPanel.setVisible(true);
AutomaticAlgorithm aa = new AutomaticAlgorithm(rows, cols, terrain, array,intelligence);
aa.calShortestPath();
autoCal.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
try
{
aa.showShortestPath();
} catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
});
add(terrainPanel, BorderLayout.CENTER);
add(autoCal, BorderLayout.SOUTH);
add(sumLabel, BorderLayout.NORTH);
setVisible(true);
// System.out.println("Observer: " + manualAlgorithm.getSum());
}
@Override
public void update()
{
sumLabel.setText("Current Path: " + Integer.toString(manualAlgorithm.getSum()));
}
}
<file_sep>/**
* @author paulalan
* @create 2019/10/4 11:00
*/
public abstract class Observer
{
protected Object object;
public abstract void update();
}
<file_sep>import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
/**
* @author paulalan
* @create 2019/9/30 15:47
*/
public class AutomaticAlgorithm
{
private HashMap<Integer, ArrayList> shortestSet = new HashMap<>();
private int staticShortestLength;
private int rows;
private int cols;
private int[][] saveArray;
private HashMap<JLabel, Integer> terrain;
private ArrayList<Integer> shortestPath;
private int temp = 0;
private ArrayList path;
private int shortestLength = 0;
private int count = 0;
private double intelligence;
public AutomaticAlgorithm(int rows, int cols, HashMap<JLabel, Integer> terrain, int[][] array, double intelligence)
{
this.rows = rows;
this.cols = cols;
this.terrain = terrain;
this.saveArray = array;
this.intelligence = intelligence;
}
public void calShortestPath()
{
for (int i = (rows - 1) * cols + 1; i <= rows * cols; i++)
{
shortestPath = new ArrayList<>();
find(i);
shortestSet.put(temp, shortestPath);
}
System.out.println("Shortest path found successfully!");
Object[] temp = shortestSet.keySet().toArray();
Arrays.sort(temp);
shortestLength = (int) temp[0];
path = shortestSet.get(temp[0]);
staticShortestLength = shortestLength;
}
public void showShortestPath() throws InterruptedException
{
System.out.println(path);
for (int len = 0; len < path.size(); len++)
{
JLabel currentLabel = Util.getKey(terrain, (int) path.get(len));
currentLabel.setOpaque(true);
currentLabel.setBackground(Color.blue);
currentLabel.setForeground(Color.yellow);
// Thread.sleep(1000);
}
JOptionPane.showMessageDialog(null,
"Shortest Length is " + shortestLength,
"Automatic Calculate Successful!", JOptionPane.INFORMATION_MESSAGE);
// System.out.println(temp[0]);
}
int minimum(int num1, int num2, int num3)
{
int min = Math.min(num1, num2);
min = Math.min(min, num3);
return min;
}
public void find(int currentNumID)
{
int currentRow;
int currentCol;
int currentNum;
currentRow = ((currentNumID % cols) == 0) ? (currentNumID / cols) : (currentNumID / cols) + 1;
currentCol = ((currentNumID % cols) == 0) ? cols : (currentNumID % cols);
currentNum = saveArray[currentRow - 1][currentCol - 1];
shortestLength += currentNum;
shortestPath.add(currentNumID);
// count++;
// System.out.println("Aa count==" + count);
double temp = Math.ceil((1 - intelligence) * rows);
if (currentRow > (int) (temp) + 1)
{
int topNumID = currentNumID - cols;
if (cols == 1)
{
find(topNumID);
} else if (currentCol == 1)
{
int topRightID = currentNumID - cols + 1;
int min = Math.min(Integer.parseInt(Util.getKey(terrain, topNumID).getText()),
Integer.parseInt(Util.getKey(terrain, topRightID).getText()));
find((min == Integer.parseInt(Util.getKey(terrain, topNumID).getText())) ? topNumID : topRightID);
} else if (currentCol == cols)
{
int topLeftID = currentNumID - cols - 1;
int min = Math.min(Integer.parseInt(Util.getKey(terrain, topNumID).getText()),
Integer.parseInt(Util.getKey(terrain, topLeftID).getText()));
find((min == Integer.parseInt(Util.getKey(terrain, topNumID).getText())) ? topNumID : topLeftID);
} else
{
int topRightID = currentNumID - cols + 1;
int topLeftID = currentNumID - cols - 1;
int min = minimum(Integer.parseInt(Util.getKey(terrain, topNumID).getText()),
Integer.parseInt(Util.getKey(terrain, topRightID).getText()),
Integer.parseInt(Util.getKey(terrain, topLeftID).getText()));
if (min == Integer.parseInt(Util.getKey(terrain, topNumID).getText()))
{
find(topNumID);
} else if (min == Integer.parseInt(Util.getKey(terrain, topRightID).getText()))
{
find(topRightID);
} else
{
find(topLeftID);
}
}
} else
{
System.out.println("Find To Top");
System.out.println(shortestLength);
this.temp = shortestLength;
shortestLength = 0;
}
}
public int getStaticShortestLength()
{
return staticShortestLength;
}
}
<file_sep># ADA_ass2
ADA Ass2, Shortest path
<file_sep>import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* @author paulalan
* @create 2019/9/27 19:53
*/
public class Main
{
private ArrayList<Double> savePart = new ArrayList<>();
public static void main(String[] args)
{
new Main();
}
private void calSavePart(int rowInput)
{
for (int i = 1; i <= rowInput; i++)
{
double temp = (double) i / rowInput;
savePart.add(temp);
}
}
public Main()
{
JFrame frame = new JFrame("Index");
frame.setSize(600, 400);
frame.setLayout(new BorderLayout());
Container currentContainer = frame.getContentPane();
JPanel index = new JPanel();
// index.setLayout(new BorderLayout());
// index.setLayout(new FlowLayout(FlowLayout.LEADING,2,10));
index.setLayout(null);
JLabel rowTip = new JLabel("Row");
rowTip.setVisible(true);
rowTip.setBounds(10, 10, 300, 20);
JLabel colTip = new JLabel("Col");
colTip.setVisible(true);
colTip.setBounds(10, 80, 300, 20);
JLabel intelligentSelectionTip = new JLabel("Intelligent");
intelligentSelectionTip.setVisible(true);
intelligentSelectionTip.setBounds(10, 150, 300, 20);
JTextArea rowInput = new JTextArea(1, 20);
rowInput.setVisible(true);
rowInput.setBounds(10, 45, 300, 20);
JTextArea colInput = new JTextArea(1, 20);
colInput.setVisible(true);
colInput.setBounds(10, 115, 300, 20);
JButton createTerrain = new JButton("Create New Terrain");
createTerrain.setVisible(true);
createTerrain.setBounds(10, 220, 200, 30);
JTextArea intelligentInput = new JTextArea(1, 20);
intelligentInput.setVisible(true);
intelligentInput.setBounds(10, 185, 300, 20);
index.add(rowTip);
index.add(rowInput);
index.add(colTip);
index.add(colInput);
index.add(createTerrain);
index.add(intelligentSelectionTip);
index.add(intelligentInput);
JTabbedPane tab = new JTabbedPane();
tab.addTab("Index", index);
createTerrain.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
if (intelligentInput.getText().equals(""))
{
if (checkInput(rowInput) && checkInput(colInput))
{
Terrain newTerrain = new Terrain(Integer.parseInt(rowInput.getText()),
Integer.parseInt(colInput.getText()), 1);
tab.addTab("Terrain", newTerrain);
rowInput.setText("");
colInput.setText("");
intelligentInput.setText("");
} else
{
JOptionPane.showMessageDialog(null, "Please type number!",
"Caution", JOptionPane.INFORMATION_MESSAGE);
rowInput.setText("");
colInput.setText("");
intelligentInput.setText("");
}
} else
{
if (checkInput(rowInput) && checkInput(colInput))
{
Terrain newTerrain = new Terrain(Integer.parseInt(rowInput.getText()),
Integer.parseInt(colInput.getText()),
Double.parseDouble(intelligentInput.getText()));
tab.addTab("Terrain", newTerrain);
rowInput.setText("");
colInput.setText("");
intelligentInput.setText("");
} else
{
JOptionPane.showMessageDialog(null, "Please type number!",
"Caution", JOptionPane.INFORMATION_MESSAGE);
rowInput.setText("");
colInput.setText("");
intelligentInput.setText("");
}
}
}
});
frame.add(tab, BorderLayout.CENTER);
frame.setResizable(true);
frame.setVisible(true);
int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
frame.setSize((int) (screenWidth * 0.618), (int) (screenHeight * 0.618));
frame.setLocation(screenWidth / 2 - (frame.getWidth()) / 2,
screenHeight / 2 - (frame.getHeight()) / 2);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private boolean checkInput(JTextArea input)
{
if (input.getText().contains("."))
{
return false;
} else
{
Pattern reg = Pattern.compile("^-?\\d+(\\.\\d+)?$");
return reg.matcher(input.getText()).matches();
}
}
}
| 23b1e34b07803accacf151b20cbe7782765a5f9a | [
"Markdown",
"Java"
] | 6 | Java | XeonHis/ADA_ass2 | 0fa550d87d085b2652b6053aa38dbb21a015873c | 062462de2c15d5a80b289dc634f4840a065383d6 |
refs/heads/main | <repo_name>RinorSvarca/data_science_salary_project<file_sep>/data_collection.py
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 01:19:34 2020
@author: Rinor
"""
import glassdoor_scraper as gs
import pandas as pd
path = r"C:/Users/rinor/source/data_science_salary_project/chromedriver.exe"
df = gs.get_jobs('data-scientist', 1000, False, path, 15)
df.to_csv('glassdoor_jobs.csv', index = False) | 0cdd51bfe3571bab81f0238c0834bf2076ad612e | [
"Python"
] | 1 | Python | RinorSvarca/data_science_salary_project | 6fc454fd9a53acfcf3112a1cee504996f08fc945 | 38f38086d64e2e849208d02468121f769f1c8a4a |
refs/heads/master | <file_sep><?php
namespace JackDomino\Elements;
/**
* Domino pool interface
*
* @package JackDomino\Elements
* @author <NAME> <<EMAIL>>
*/
interface DominoPoolInterface
{
/**
* Add a domino to the pool
*
* @param Domino $domino
* @param int $position
* @return Domino[]
*/
public function add(Domino $domino, $position = 0): array;
/**
* Shuffle the domino pool
*
* @return Domino[]
*/
public function shuffle(): array;
/**
* Clear the pool
* @return Domino[]
*/
public function clear(): array;
/**
* Pick random number of items from array
*
* @param int $amount
* @return Domino[]|null
*/
public function pickRandom(int $amount = 1): ? array;
/**
* Pick with value (remove from pool)
*
* @param int $value
* @return Domino|null
*/
public function pickWithValue(int $value): ? Domino;
/**
* Get playable values
*
* @param string $mode
* @return array
*/
public function getPlayableValues(string $mode = 'value'): array;
/**
* Mark a domino as played by value
*
* @param int $value
* @return DominoValue|null
*/
public function markAsPlayed(int $value): ? DominoValue;
/**
* Play the tile
*
* @param Domino
* @param integer $position
* @return Domino|null
*/
public function play(Domino $domino, int $position): ? Domino;
/**
* Get a domino tile by position in the pool
*
* @param int $position
* @return Domino|null
*/
public function getDominoByPosition(int $position): ? Domino;
/**
* Get position by value (only playable)
*
* @param int $value
* @return int|null
*/
public function getPosition(int $value): ? int;
/**
* Get full set
*
* @return Domino[]
*/
public function getFullSet(): array;
}
<file_sep><?php
namespace JackDomino\Elements;
/**
* Domino interface
*
* @package JackDomino\Elements
* @author <NAME> <<EMAIL>>
*/
interface DominoInterface
{
/**
* Reverse the domino
*
* @return DominoValue[]
*/
public function reverse() : array;
/**
* Get values
*
* @return DominoValue[]
*/
public function getValues(): array;
/**
* Get playable values
*
* @param array $playableValues
* @param string $mode
* @return DominoValue[]
*/
public function getPlayableValues(array $playableValues = array(), string $mode = 'value'): array;
/**
* Mark a domino as played by value
*
* @param int $value
* @param int|bool $position
* @return DominoValue|null
*/
public function markAsPlayed(int $value, $position = false):? DominoValue;
}<file_sep><?php
namespace JackDomino\Elements;
/**
* Class DominoValue
*
* @package JackDomino\Elements
* @author <NAME> <<EMAIL>>
*/
interface DominoValueInterface
{
/**
* Get the value
*
* @return int
*/
public function getValue() : int;
/**
* Is this tile playable?
*
* @return bool
*/
public function isPlayable(): bool;
/**
* Mark as played
* @return DominoValue
*/
public function markAsPlayed(): DominoValue;
}<file_sep><?php
namespace JackDomino\Game;
use JackDomino\Elements\DominoPool;
use JackDomino\Elements\Domino;
/**
* Class Game
*
* Main class for starting a game.
* This is not interactive because it was not a requirement in the assessment
*
* @package JackDomino\Game
* @author <NAME> <<EMAIL>>
*/
final class Game implements GameInterface
{
/**
* @var DominoPool $board
*/
private $board;
/**
* @var DominoPool $stack
*/
private $stack;
/**
* @var Player $player1
*/
private $player1;
/**
* @var Player $player2
*/
private $player2;
/**
* Start a new game
*/
public function start()
{
//First we setup a stack
$this->stack = new DominoPool();
$this->stack->getFullSet();
//Get the 7 random items
$pool1 = new DominoPool($this->stack->pickRandom(7));
$pool2 = new DominoPool($this->stack->pickRandom(7));
$this->player1 = new Player('Alice', $pool1);
$this->player2 = new Player('Bob', $pool2);
//Get the first item
$this->board = new DominoPool($this->stack->pickRandom(1));
echo PHP_EOL . 'Game starting with first tile: ' . $this->board . PHP_EOL;
//Make a loop over the full set..
for ($i = 0; $i <= count(DominoPool::FULL_SET); $i++) {
//Even for player2
if ($i % 2 == 0) {
$player = $this->player2;
} else { //Otherwise player1
$player = $this->player1;
}
//Make a turn
$this->turn($player);
//Check if we have a winner
if ($this->hasWon($player)) {
echo PHP_EOL . 'Player ' . $player . ' has won!';
break;
} else if ($this->isBlocked($this->stack)) {
echo PHP_EOL . 'Game is blocked. Stack is empty';
break;
}
}
}
/**
* Make a turn
*
* @param Player $player
* @return bool
*/
public function turn(Player $player) : bool
{
$played = false;
while (!$played) {
//Do we have matching available values?
$matchingValues = array_intersect($this->board->getPlayableValues(), $player->dominoPool->getPlayableValues());
if (count($matchingValues)) {
foreach ($matchingValues as $value) {
//Select the board domino
$position = $this->board->getPosition($value);
if (is_integer($position)) {
$boardDomino = $this->board->getDominoByPosition($position);
//Get the domino of the player
$playerDomino = $player->dominoPool->pickWithValue($value);
$playerDomino = $this->board->play($playerDomino, $position);
if ($position > 0) {
$position++;
}
$this->board->add($playerDomino, $position);
echo PHP_EOL . $player . ' plays ' . $playerDomino . ' to connect to tile ' . $boardDomino . ' on the board';
echo PHP_EOL . 'Board is now ' . $this->board;
$played = true;
break;
}
}
} else {
//Pick a new tile
$newDomino = $this->getTileFromStack($this->stack);
if ($newDomino) {
echo PHP_EOL . $player . ' can\'t play, drawing tile ' . $newDomino;
$player->dominoPool->add($newDomino);
} else {
$played = true;
}
}
}
return $played;
}
/**
* Get tile from stack
*
* @param DominoPool $stack
* @return Domino|null
*/
public function getTileFromStack(DominoPool $stack): ? Domino
{
//Pick a new tile
$newDomino = $stack->pickRandom(1);
if($newDomino) {
$newDomino = $newDomino[0];
}
return $newDomino;
}
/**
* Check if a player has won
*
* @param Player $player
* @return bool
*/
public function hasWon(Player $player): bool
{
if (count($player->dominoPool->getPlayableValues()) == 0) {
return true;
}
return false;
}
/**
* Check if a game is blocked
*
* @param DominoPool $stack
* @return bool
*/
public function isBlocked(DominoPool $stack): bool
{
if (count($stack->getPlayableValues()) == 0) {
return true;
}
return false;
}
}
<file_sep><?php
namespace JackDomino\Elements;
/**
* Class DominoPool
*
* This class is used for creating and managing a domino pool
*
* @package JackDomino\Elements
* @author <NAME> <<EMAIL>>
*/
final class DominoPool implements DominoPoolInterface
{
/**
* @var array
*/
const FULL_SET = array('0,1', '0,2', '0,3', '0,4', '0,5', '0,6', '1,2', '1,3', '1,4', '1,5', '1,6', '2,3', '2,4',
'2,5', '2,6', '3,4', '3,5', '3,6', '4,5', '4,6', '5,6', '0,0', '1,1', '2,2', '3,3', '4,4',
'5,5', '6,6');
/**
* @var Domino[]
*/
private $pool = array();
/**
* DominoPool constructor.
* @param Domino[] $pool
*/
public function __construct(array $pool = array())
{
$this->pool = (function (Domino ...$pool) {
return $pool;
})(...$pool);
}
/**
* Cast pool to string
*/
public function __toString(): string
{
$string = '';
if (count($this->pool)) {
/**
* @var $pool Domino
*/
foreach ($this->pool as $pool) {
$string .= (string)$pool . ' ';
}
$string = rtrim($string);
}
return $string;
}
/**
* Add a domino to the pool
*
* @param Domino $domino
* @param int $position
* @return Domino[]
*/
public function add(Domino $domino, $position = 0): array
{
//Prepend on 0
if ($position <= 0) {
array_unshift($this->pool, $domino);
} else {
$this->pool[$position] = $domino;
}
return $this->pool;
}
/**
* Shuffle the domino pool
*
* @return Domino[]
*/
public function shuffle(): array
{
shuffle($this->pool);
return $this->pool;
}
/**
* Clear the pool
* @return Domino[]
*/
public function clear(): array
{
$this->pool = array();
return $this->pool;
}
/**
* Pick random number of items from array
*
* @param int $amount
* @return Domino[]|null
*/
public function pickRandom(int $amount = 1): ? array
{
if ($amount <= count($this->pool)) {
$this->shuffle();
return array_splice($this->pool, 0, $amount);
}
return null;
}
/**
* Pick with value (remove from pool)
*
* @param int $value
* @return Domino|null
*/
public function pickWithValue(int $value): ? Domino
{
foreach ($this->pool as $key => $domino) {
/**
* @var $domino Domino
*/
if (in_array($value, $domino->getPlayableValues())) {
$domino = array_splice($this->pool, $key, 1);
//Return a single domino
return $domino[0];
}
}
return null;
}
/**
* Get playable values
*
* @param string $mode
* @return array
*/
public function getPlayableValues(string $mode = 'value'): array
{
$playableValues = array();
foreach ($this->pool as $domino) {
$playableValues = $domino->getPlayableValues($playableValues, $mode);
}
return $playableValues;
}
/**
* Mark a domino as played by value
*
* @param int $value
* @return DominoValue|null
*/
public function markAsPlayed(int $value): ? DominoValue
{
foreach ($this->pool as $key => $domino) {
if (in_array($value, $domino->getPlayableValues())) {
return $domino->markAsPlayed($value);
}
}
return null;
}
/**
* Play the tile
*
* @param Domino
* @param integer $position
* @return Domino|null
*/
public function play(Domino $domino, int $position): ? Domino
{
//Loop through the playable values..
foreach ($domino->getPlayableValues() as $dominoValue) {
if (in_array($dominoValue, $this->getPlayableValues('object'))) {
//Mark the domino in the pool as played
$this->markAsPlayed((int)$dominoValue);
//Mark the given domino as played
$domino->markAsPlayed((int)$dominoValue, $position);
return $domino;
}
}
return null;
}
/**
* Get a domino tile by position in the pool
*
* @param int $position
* @return Domino|null
*/
public function getDominoByPosition(int $position): ? Domino
{
if (array_key_exists($position, $this->pool)) {
return $this->pool[$position];
}
return null;
}
/**
* Get position by value (only playable)
*
* @param int $value
* @return int|null
*/
public function getPosition(int $value): ? int
{
foreach ($this->pool as $key => $domino) {
/**
* @var $domino Domino
*/
if (in_array($value, $domino->getPlayableValues())) {
return $key;
}
}
return null;
}
/**
* Get full set
*
* @return Domino[]
*/
public function getFullSet(): array
{
$this->clear();
foreach ($this::FULL_SET as $item) {
$values = explode(',', $item);
$domino = new Domino((int)$values[0], (int)$values[1]);
$this->add($domino);
}
return $this->pool;
}
}
<file_sep># Technical assessment Domino Game
First install vendor files with composer
```php
composer install
```
To run the game you can simply use the cli command
```php
php game.php
```
You can run the tests with phpunit:
```php
./vendor/bin/phpunit
```
<file_sep><?php
namespace JackDomino\Elements;
/**
* Class DominoValue
*
* Each domino consists of two domino values.
*
* @package JackDomino\Elements
* @author <NAME> <<EMAIL>>
*/
final class DominoValue implements DominoValueInterface
{
/**
* @var int
*/
protected $value;
/**
* @var bool
*/
protected $playable;
/**
* DominoValue constructor.
*
* @param int $value
* @param bool $playable
*/
public function __construct(int $value, bool $playable = true)
{
$this->value = $value;
$this->playable = $playable;
}
/**
* Return value as string
*
* @return string
*/
public function __toString(): string
{
return (string)$this->value;
}
/**
* Get the value
*
* @return int
*/
public function getValue(): int
{
return $this->value;
}
/**
* Is this tile playable?
*
* @return bool
*/
public function isPlayable(): bool
{
return $this->playable;
}
/**
* Mark as played
* @return DominoValue
*/
public function markAsPlayed(): DominoValue
{
$this->playable = false;
return $this;
}
}
<file_sep><?php
namespace JackDomino\Game;
use JackDomino\Elements\DominoPool;
/**
* Class Player
*
* Use this class to create a player for a nice game of domino's
*
* @package JackDomino\Game
* @author <NAME> <<EMAIL>>
*/
final class Player implements PlayerInterface
{
/**
* @var string
*/
private $name;
/**
* @var DominoPool
*/
public $dominoPool;
/**
* Initialize a player
*
* @param string $name
* @param DominoPool $dominoPool
*/
public function __construct(string $name, DominoPool $dominoPool)
{
$this->name = $name;
$this->dominoPool = $dominoPool;
}
/**
* Get the ployer name
*
* @return string
*/
public function __toString(): string
{
return $this->name;
}
/**
* Show hand
*
* @return string
*/
public function showHand(): string
{
return (string)$this->dominoPool;
}
}
<file_sep><?php
use PHPUnit\Framework\TestCase;
use JackDomino\Elements\DominoPool;
use JackDomino\Elements\Domino;
use JackDomino\Game\Player;
class PlayerTest extends TestCase
{
/**
* @covers Player::showHand()
*/
public function testShowHand()
{
$domino1 = new Domino(1, 2);
$dominoPool = new DominoPool();
$dominoPool->add($domino1);
$player = new Player('Player 1',$dominoPool);
$this->assertEquals('<1:2>',$player->showHand());
}
}<file_sep><?php
use PHPUnit\Framework\TestCase;
use JackDomino\Elements\Domino;
class DominoTest extends TestCase
{
/**
* @covers Domino::reverse()
*/
public function testReverse()
{
$domino = new Domino(1, 2);
$result = $domino->reverse();
$this->assertSame($result[0]->getValue(), 2);
$this->assertSame($result[1]->getValue(), 1);
}
/**
* @covers Domino::getValues()
*/
public function testGetValues()
{
$domino = new Domino(3, 4);
$values = $domino->getValues();
$this->assertSame($values[0]->getValue(), 3);
$this->assertSame($values[1]->getValue(), 4);
}
/**
* @covers Domino::getPlayableValues()
*/
public function testGetPlayableValues()
{
$domino = new Domino(3, 4);
$domino->getValues()[0]->markAsPlayed();
$playable = $domino->getPlayableValues(array(), 'object');
$this->assertSame($playable[0]->getValue(), 4);
$playable = $domino->getPlayableValues();
$this->assertSame($playable[0], (string)4);
}
/**
* @covers Domino::markAsPlayed()
*/
public function testMarkAsPlayed()
{
$domino = new Domino(1, 2);
$played = $domino->getValues()[0]->markAsPlayed();
$this->assertSame($played->isPlayable(), false);
}
}<file_sep><?php
namespace JackDomino\Game;
use JackDomino\Elements\DominoPool;
use JackDomino\Elements\Domino;
/**
* Interface GameInterface
*
* @package JackDomino\Game
* @author <NAME> <<EMAIL>>
*/
interface GameInterface
{
/**
* Start a new game
*/
public function start();
/**
* Make a turn
*
* @param Player $player
* @return bool
*/
public function turn(Player $player) : bool;
/**
* Get tile from stack
*
* @param DominoPool $stack
* @return Domino|null
*/
public function getTileFromStack(DominoPool $stack): ? Domino;
/**
* Check if a player has won
*
* @param Player $player
* @return bool
*/
public function hasWon(Player $player): bool;
/**
* Check if a game is blocked
*
* @param DominoPool $stack
* @return bool
*/
public function isBlocked(DominoPool $stack): bool;
}
<file_sep><?php
namespace JackDomino\Game;
use JackDomino\Elements\DominoPool;
/**
* Interface PlayerInterface
*
* @package JackDomino\Game
* @author <NAME> <<EMAIL>>
*/
interface PlayerInterface
{
/**
* Show hand
*
* @return string
*/
public function showHand(): string;
}<file_sep><?php
use PHPUnit\Framework\TestCase;
use JackDomino\Elements\DominoPool;
use JackDomino\Elements\Domino;
class DominoPoolTest extends TestCase
{
/**
* @covers DominoPool::add()
*/
public function testAdd()
{
$domino1 = new Domino(1, 2);
$dominoPool = new DominoPool();
$dominoPool->add($domino1);
$this->assertEquals(2, count($dominoPool->getPlayableValues()));
$domino2 = new Domino(3, 4);
$dominoPool->add($domino2,0);
$this->assertEquals($domino2,$dominoPool->getDominoByPosition(0));
$domino3 = new Domino(5, 6);
$dominoPool->add($domino3,2);
$this->assertEquals($domino3,$dominoPool->getDominoByPosition(2));
}
/**
* @covers DominoPool::clear()
*/
public function testClear()
{
$dominoPool = new DominoPool();
$domino1 = new Domino(1, 2);
$dominoPool->add($domino1);
$dominoPool->clear();
$this->assertEquals(0, count($dominoPool->getPlayableValues()));
}
/**
* @covers DominoPool::pickWithValue()
*/
public function testPickWithValue()
{
$dominoPool = new DominoPool();
$domino1 = new Domino(1, 2);
$domino2 = new Domino(3, 4);
$dominoPool->add($domino1);
$dominoPool->add($domino2);
$this->assertEquals($domino2, $dominoPool->pickWithValue(4));
}
/**
* @covers DominoPool::getPlayableValues()
*/
public function testGetPlayableValues()
{
$dominoPool = new DominoPool();
$domino1 = new Domino(1, 2);
$domino2 = new Domino(3, 4);
$domino2->markAsPlayed(4);
$dominoPool->add($domino1);
$dominoPool->add($domino2);
$this->assertEquals(3, count($dominoPool->getPlayableValues()));
}
/**
* @covers DominoPool::play()
*/
public function testPlay()
{
$dominoPool = new DominoPool();
$domino1 = new Domino(1, 2);
$domino2 = new Domino(2, 4);
$dominoPool->add($domino1);
$playedDomino = $dominoPool->play($domino2,0);
$this->assertEquals(1, count($playedDomino->getPlayableValues()));
$this->assertEquals(1, count($dominoPool->getPlayableValues()));
}
/**
* @covers DominoPool::getDominoByPosition()
*/
public function testGetDominoByPosition()
{
$dominoPool = new DominoPool();
$domino1 = new Domino(1, 2);
$dominoPool->add($domino1);
$domino2 = new Domino(3, 4);
$dominoPool->add($domino2,1);
$this->assertEquals($domino2,$dominoPool->getDominoByPosition(1));
}
/**
* @covers DominoPool::getPosition()
*/
public function testGetPosition()
{
$dominoPool = new DominoPool();
$domino1 = new Domino(1, 2);
$dominoPool->add($domino1);
$domino2 = new Domino(3, 4);
$dominoPool->add($domino2,1);
$this->assertEquals($dominoPool->getPosition(4),1);
}
/**
* @covers DominoPool::getFulSet()
*/
public function testGetFullSet()
{
$dominoPool = new DominoPool();
$this->assertEquals(28,count($dominoPool->getFullSet()));
}
}<file_sep><?php
use PHPUnit\Framework\TestCase;
use JackDomino\Elements\DominoPool;
use JackDomino\Elements\Domino;
use JackDomino\Game\Game;
use JackDomino\Game\Player;
class GameTest extends TestCase
{
/**
* @covers Game:getTileFromStack()
*/
public function testGetTileFromStack()
{
$stack = new DominoPool();
$domino = new Domino(1,2);
$stack->add($domino);
$game = new Game();
$dominoFromStack = $game->getTileFromStack($stack);
$this->assertEquals($domino,$dominoFromStack);
}
/**
* @covers Game::hasWon()
*/
public function testHasWon()
{
$dominoPool = new DominoPool();
$player = new Player('Player 1',$dominoPool);
$game = new Game();
$this->assertEquals(true,$game->hasWon($player));
}
/**
* @covers Game::isBlocked()
*/
public function testIsBlocked()
{
$stack = new DominoPool();
$game = new Game();
$this->assertEquals(true,$game->isBlocked($stack));
}
}<file_sep><?php
use PHPUnit\Framework\TestCase;
use JackDomino\Elements\DominoValue;
class DominoValueTest extends TestCase
{
/**
* @covers DominoValue::getValue()
*/
public function testGetValue()
{
$dominoValue = new DominoValue(1, true);
$this->assertSame($dominoValue->getValue(), 1);
}
/**
* @covers DominoValue::isPlayable()
*/
public function testIsPlayable()
{
$dominoValue = new DominoValue(1, false);
$this->assertSame($dominoValue->isPlayable(), false);
}
/**
* @covers DominoValue::markAsPlayed()
*/
public function testMarkAsPlayed()
{
$dominoValue = new DominoValue(1, true);
$dominoValue->markAsPlayed();
$this->assertSame($dominoValue->isPlayable(), false);
}
}<file_sep><?php
use JackDomino\Game\Game;
require_once __DIR__ . '/vendor/autoload.php';
$game = new Game();
$game->start();<file_sep><?php
namespace JackDomino\Elements;
/**
* Class Domino
*
* Main class for generating a domino
*
* @package JackDomino\Elements
* @author <NAME> <<EMAIL>>
*/
final class Domino implements DominoInterface
{
/**
* @var string
*/
const TILE = '<%s:%s>';
/**
* @var DominoValue[]
*/
private $values = array();
/**
* Domino constructor.
* @param int $head
* @param int $tail
*/
public function __construct(int $head, int $tail)
{
$this->values[] = new DominoValue($head);
$this->values[] = new DominoValue($tail);
}
/**
* Get the domino head, tail pair name
*
* @return string
*/
public function __toString(): string
{
return sprintf($this::TILE, $this->values[0], $this->values[1]);
}
/**
* Reverse the domino
*
* @return DominoValue[]
*/
public function reverse(): array
{
$this->values = array_reverse($this->values);
return $this->values;
}
/**
* Get values
*
* @return DominoValue[]
*/
public function getValues(): array
{
return $this->values;
}
/**
* Get playable values
*
* @param array $playableValues
* @param string $mode
* @return DominoValue[]
*/
public function getPlayableValues(array $playableValues = array(), string $mode = 'value'): array
{
foreach ($this->values as $key => $value) {
if ($value->isPlayable()) {
if ($mode == 'object') {
$playableValues[] = $value;
} else {
$playableValues[] = (string)$value;
}
}
}
return $playableValues;
}
/**
* Mark a domino as played by value
*
* @param int $value
* @param int|bool $position
* @return DominoValue|null
*/
public function markAsPlayed(int $value, $position = false):? DominoValue
{
//Loop through the playable values
foreach ($this->getPlayableValues(array(), 'object') as $key => $dominoValue) {
if ($value == $dominoValue->getValue()) {
//Reverse the domino when it is in the wrong position
if (($position === 0 && $key == 0) || ($position > 0 && $key == 1)) {
$this->reverse();
}
$dominoValue->markAsPlayed();
return $dominoValue;
}
}
return null;
}
}
| 760a057536f8d0bfeb2272753a4a818ddf8fa537 | [
"Markdown",
"PHP"
] | 17 | PHP | jkwakman/JackDomino | e736864c266343f1ef422c9ca7fa85a274d84680 | d666f777280df25e414c7b369acd31f8b425a869 |
refs/heads/master | <repo_name>LiliCecilia23/work-day-scheduler<file_sep>/assets/script.js
$(document).ready(function(){
$('#currentDay').text(moment().format('dddd, MMMM Do'));
let currentHour = moment().hours();
$(".hBlock").each(function (){
let hour = parseInt($(this).attr("id"));
console.log(hour);
if (hour === currentHour) {
$(this).addClass("present");
$(this).removeClass("future");
$(this).removeClass("past");
}
else if (hour > currentHour) {
$(this).addClass("future");
$(this).removeClass("present");
$(this).removeClass("past");
}
else {
$(this).addClass("past");
$(this).removeClass("future");
$(this).removeClass("present");
}
});
$(".save").click(function(){
var input = $(this).siblings(".hBlock").val()
var whichHour = $(this).siblings(".hBlock").attr("id")
localStorage.setItem(whichHour, input);
});
$("#9").val(localStorage.getItem("9"))
$("#10").val(localStorage.getItem("10"))
$("#11").val(localStorage.getItem("11"))
$("#12").val(localStorage.getItem("12"))
$("#13").val(localStorage.getItem("13"))
$("#14").val(localStorage.getItem("14"))
$("#15").val(localStorage.getItem("15"))
$("#16").val(localStorage.getItem("16"))
$("#17").val(localStorage.getItem("17"))
});<file_sep>/README.md
# ⏰ Workday Scheduler
<img src="./assets/screenshot1.png" alt="screenshot of workday scheduler">
This app is a workday scheduler that allows you to input events from 9AM-6PM each day. It is powered by Moment.js and local storage capabilities.
<hr>
⏰ [GitHub Repo]("https://github.com/LiliCecilia23/work-day-scheduler")
⏰ [Deployed App]("https://lilicecilia23.github.io/work-day-scheduler/")
<hr>
## Usage Instructions
Upon navigating to the page, each hour block is color coded to indicate past, present, and future according to when the user is accessing the app. Users are only able to edit hour blocks for their current hour or later. The user can save the contents of each input field with the save/lock button on the right side of its hour block, which saves them to local storage so they will still be there even if the user refreshes the page.
## Technologies Used
* HTML5
* CSS3
* JavaScript
* jQuery
* Bootstrap
* Moment.js
* Local Storage
## Contact
* [LinkedIn]("linkedin.com/in/lili-clift/")
* [GitHub]("github.com/LiliCecilia23")
## License
Copyright (c) 2021 <NAME> Licensed under the MIT license.
| b36ebe1a193336cf6b81622a75f08f651cef11f3 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | LiliCecilia23/work-day-scheduler | b12ddd1b5bd8cf9c70a1d3f1b011d1ed1497b35a | 0da051b5104c1775b331a798c2c3b4bbb9ff6402 |
refs/heads/main | <file_sep>import { createClient } from "@supabase/supabase-js";
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_KEY || "";
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || "";
export const supabaseClient = createClient(supabaseUrl, supabaseKey);
| 7f7d3aaaba4cbbe62fe7a47e416f41a4d7517ba3 | [
"TypeScript"
] | 1 | TypeScript | in-felipe-gom/todos | d6f34d2c1ea209e84f31be21879466ace19dd774 | 4444e92d798ce2fcdd368b8527292d8d04e219c2 |
refs/heads/master | <file_sep>puts "donne un nombre"
print "> "
user_number = gets.chomp
user_number = Integer(user_number)
n=0
user_number.times do |i|
puts i
end
<file_sep>"Il y a X ans, tu avais Y ans"
puts "donne ton age"
print "> "
user_number = gets.chomp
user_number = Integer(user_number)
n=0
nn=0
while (user_number >= 0)
print "il y à "
print user_number
print " ans Tu avais "
print n
puts " ans"
nn=user_number - n
print "nn est égale à : "
puts nn
if (nn==0)
print "Il y a , "
print user_number
puts " ans tu avais la moitié de l'âge que tu as aujourd'hui "
end
if (nn==1)
print "Il y a , "
print user_number
puts " ans tu avais presque la moitié de l'âge que tu as aujourd'hui (ton age est un nombre impair tu ne peux donc pas avoir la moitié de ton age sur un entier)"
end
user_number += -1
n+=1
end<file_sep>puts "On va compter le nombre d'heures de travail à THP" #print de la phrase ...
puts "Travail : #{10 * 5 * 11}" #print de travail 10*5*11 (550)
puts "En minutes ça fait : #{10 * 5 * 11 * 60}" # print de en minute ça fait 33000
puts "Et en secondes ?" #print de la phrase ...
puts 10 * 5 * 11 * 60 * 60 #print de la valeur 1980000...
puts "Est-ce que c'est vrai que 3 + 2 < 5 - 7 ?"#print de la phrase ...
puts 3 + 2 < 5 - 7#print "false"
puts "Ça fait combien 3 + 2 ? #{3 + 2}"#print de la phrase ...+ résultat (5)
puts "Ça fait combien 5 - 7 ? #{5 - 7}"#print de la phrase ...+ résultat (-2)
puts "Ok, c'est faux alors !"#print de la phrase ...
puts "C'est drôle ça, faisons-en plus :"#print de la phrase ...
puts "Est-ce que 5 est plus grand que -2 ? #{5 > -2}"#print de la phrase ...+ true
puts "Est-ce que 5 est supérieur ou égal à -2 ? #{5 >= -2}"#print de la phrase ...+ true
puts "Est-ce que 5 est inférieur ou égal à -2 ? #{5 <= -2}"#print de la phrase ... + false<file_sep>puts "donne un nombre"
print "> "
user_number = gets.chomp
user_number = Integer(user_number)
n=0
while (n <= user_number)
puts n
n += 1
end
<file_sep>arr = []
50.times do |i|
arr << "<EMAIL>"
end
puts arr
<file_sep>puts "donne ton age"
print "> "
user_number = Integer(gets.chomp)
user_number.times do |i|
puts "il y à #{user_number-i} tu avais #{i} ans"
end<file_sep>"Il y a X ans, tu avais Y ans"
puts "donne ton age"
print "> "
user_number = gets.chomp
user_number = Integer(user_number)
n=0
while (user_number >= 0)
print "il y à "
print user_number
print " ans Tu avais "
print n
puts " ans"
user_number += -1
n+=1
end<file_sep>puts "donne un nombre"
print "> "
user_number = Integer(gets.chomp)+1
user_number.times do |i|
puts user_number-i-1
end
<file_sep>n=0
str1="jean.dupont"
str2="<EMAIL>"
arr = []
50.times do |i|
str3=(n+1).to_s
str4=str1+str3+str2
arr << str4
n+=1
end
print arr
<file_sep>puts "nombre"
print "> "
n = Integer(gets.chomp)+1
n.times do |i|
puts "#"*i
end
<file_sep>puts "nombre"
print "> "
n = gets.chomp
n = Integer(n)
nn=0
while (nn <= n)
nnn=nn
nnnn=n-nn
while (nnnn>0)
print " "
nnnn+=-1
end
while (nnn>0)
print "#"
nnn+=-1
end
puts ""
nn+=1
end<file_sep>puts "année de naissance ?"
print "> "
user_number = gets.chomp
user_number = Integer(user_number)
n=0
while (user_number <= 2020)
puts user_number
user_number += 1
end
<file_sep>n=0
str1="jean.dupont"
str2="<EMAIL>.fr"
arr = []
i=0
50.times do |i|
str3=(n).to_s
str4=str1+str3+str2
arr << str4
n+=1
end
arr.each do |ar|
if i.even? then
puts ar
end
i=i+1
end
<file_sep>puts "donne ta date de naissance"
print "> "
user_number = Integer(gets.chomp)
(2020-user_number).times do |i|
puts "en #{user_number+i} tu avais #{i} ans"
end<file_sep>puts "donne un nombre"
print "> "
user_number = gets.chomp
user_number = Integer(user_number)
user_number.times do
puts "salut ça farte ?"
end
<file_sep>puts "donne un nombre"
print "> "
user_number = gets.chomp
user_number = Integer(user_number)
n=0
while (user_number <= 2020)
print "en "
print user_number
print " Tu avais "
print n
puts ""
user_number += 1
n+=1
end<file_sep>puts "année de naissance ?"
print "> "
user_number = gets.chomp
user_number = Integer(user_number)
n=0
user_number.times do |i|
puts user_number+i
end
<file_sep>puts "année naissance"
print "> "
user_born = gets.chomp
user_born = Integer(user_born)
print "en 2017 tu avais "
puts 2017-user_born<file_sep>puts "nombre"
print "> "
n = gets.chomp
n = Integer(n)
nn=0
while (nn <= n)
nnn=nn
while (nnn>0)
print "#"
nnn+=-1
end
puts ""
nn+=1
end<file_sep>puts "c'est quoi ton blase ?"
print "> "
user_name = gets.chomp
puts "c'est quoi ton nom de famille ?"
print "> "
user_name_last = gets.chomp
print "Bonjour "
puts user_name+ " "+user_name_last<file_sep>puts "donne un nombre"
print "> "
user_number = gets.chomp
user_number = Integer(user_number)
n=0
while (user_number >= 0)
puts n
user_number += -1
n+=1
end
<file_sep>puts "donne un nombre"
print "> "
user_number = gets.chomp
user_number = Integer(user_number)
while (user_number > 0)
puts "salut ça farte ?"
user_number += -1
end
| 5e39b132e0bf95ba8a076c1ab6c0c0ab75211890 | [
"Ruby"
] | 22 | Ruby | matthieuBA/ex1 | e1126a75063b134cc1dcc8e1a2b0af62c9bbc9ca | 7cd5d89b69d2b76404cf5b3129f9907e5b5c3d21 |
refs/heads/master | <repo_name>BullThistle/sinatra_template<file_sep>/spec/template_spec.rb
require 'template'
require 'rspec'
describe 'template' do
it("returns '3' if the inputs are 1 and 2") do
sum = Numbers.new(1, 2)
expect(sum.add).to(eq(3))
end
it("returns '3' if the inputs are 1 and 2") do
sum = Numbers.new(4, 5)
expect(sum.add).to(eq(9))
end
it("returns '3' if the inputs are 1 and 2") do
sum = Numbers.new(5, 3)
expect(sum.add).to(eq(8))
end
end
| 875df54de25434b0257e210ebd28602d165a9b1a | [
"Ruby"
] | 1 | Ruby | BullThistle/sinatra_template | 296b680a5354d51445c75440e5c987e0890f3062 | 08284dd237f9aed0db4ee3a16d5259020d36d28a |
refs/heads/main | <repo_name>zeta1999/lexy<file_sep>/include/lexy/_detail/string_view.hpp
// Copyright (C) 2020 <NAME> <<EMAIL>>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef LEXY_DETAIL_STRING_VIEW_HPP_INCLUDED
#define LEXY_DETAIL_STRING_VIEW_HPP_INCLUDED
#include <lexy/_detail/assert.hpp>
#include <lexy/_detail/config.hpp>
namespace lexy::_detail
{
template <typename CharT>
class basic_string_view
{
public:
using char_type = CharT;
//=== constructor ===//
constexpr basic_string_view() noexcept : _begin(nullptr), _end(nullptr) {}
constexpr basic_string_view(const char_type* str) noexcept : _begin(str), _end(str)
{
while (*_end)
++_end;
}
constexpr basic_string_view(const char_type* ptr, std::size_t size) noexcept
: _begin(ptr), _end(ptr + size)
{}
constexpr basic_string_view(const char_type* begin, const char_type* end) noexcept
: _begin(begin), _end(end)
{}
//=== access ===//
using iterator = const char_type*;
constexpr iterator begin() const noexcept
{
return _begin;
}
constexpr iterator end() const noexcept
{
return _end;
}
constexpr bool empty() const noexcept
{
return _begin == _end;
}
constexpr std::size_t size() const noexcept
{
return static_cast<std::size_t>(_end - _begin);
}
constexpr std::size_t length() const noexcept
{
return static_cast<std::size_t>(_end - _begin);
}
constexpr char_type operator[](std::size_t i) const noexcept
{
LEXY_PRECONDITION(i <= size());
return _begin[i];
}
constexpr char_type front() const noexcept
{
LEXY_PRECONDITION(!empty());
return *_begin;
}
constexpr char_type back() const noexcept
{
LEXY_PRECONDITION(!empty());
return *(_end - 1);
}
constexpr const char_type* data() const noexcept
{
return _begin;
}
//=== operations ===//
static constexpr std::size_t npos = std::size_t(-1);
constexpr void remove_prefix(std::size_t n) noexcept
{
LEXY_PRECONDITION(n <= size());
_begin += n;
}
constexpr void remove_suffix(std::size_t n) noexcept
{
LEXY_PRECONDITION(n <= size());
_end -= n;
}
constexpr basic_string_view substr(std::size_t pos, std::size_t length = npos) const noexcept
{
LEXY_PRECONDITION(pos < size());
if (length >= size() - pos)
return basic_string_view(_begin + pos, _end);
else
return basic_string_view(_begin + pos, _begin + pos + length);
}
constexpr std::size_t find(basic_string_view str, std::size_t pos = 0) const noexcept
{
for (auto i = pos; i < length(); ++i)
{
if (substr(i, str.length()) == str)
return i;
}
return npos;
}
constexpr std::size_t find(CharT c, std::size_t pos = 0) const noexcept
{
return find(basic_string_view(&c, 1), pos);
}
//=== comparison ===//
friend constexpr bool operator==(basic_string_view<CharT> lhs,
basic_string_view<CharT> rhs) noexcept
{
if (lhs.size() != rhs.size())
return false;
for (auto a = lhs.begin(), b = rhs.begin(); a != lhs.end(); ++a, ++b)
if (*a != *b)
return false;
return true;
}
friend constexpr bool operator!=(basic_string_view<CharT> lhs,
basic_string_view<CharT> rhs) noexcept
{
return !(lhs == rhs);
}
protected:
const CharT* _begin;
const CharT* _end;
};
using string_view = basic_string_view<char>;
} // namespace lexy::_detail
#endif // LEXY_DETAIL_STRING_VIEW_HPP_INCLUDED
<file_sep>/include/lexy/result.hpp
// Copyright (C) 2020 <NAME> <<EMAIL>>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef LEXY_RESULT_HPP_INCLUDED
#define LEXY_RESULT_HPP_INCLUDED
#include <lexy/_detail/assert.hpp>
#include <lexy/_detail/config.hpp>
#include <new>
namespace lexy
{
struct result_value_t
{};
/// Tag value to indicate result success.
constexpr auto result_value = result_value_t{};
struct result_error_t
{};
/// Tag value to indiciate result error.
constexpr auto result_error = result_error_t{};
} // namespace lexy
namespace lexy
{
struct nullopt;
template <typename T, typename E>
struct _result_storage_trivial
{
using value_type = T;
using error_type = E;
bool _has_value;
union
{
T _value;
E _error;
};
template <typename... Args>
constexpr _result_storage_trivial(result_value_t, Args&&... args)
: _has_value(true), _value(LEXY_FWD(args)...)
{}
template <typename... Args>
constexpr _result_storage_trivial(result_error_t, Args&&... args)
: _has_value(false), _error(LEXY_FWD(args)...)
{}
};
template <typename T, typename E>
struct _result_storage_non_trivial
{
using value_type = T;
using error_type = E;
bool _has_value;
union
{
T _value;
E _error;
};
template <typename... Args>
_result_storage_non_trivial(result_value_t, Args&&... args)
: _has_value(true), _value(LEXY_FWD(args)...)
{}
template <typename... Args>
_result_storage_non_trivial(result_error_t, Args&&... args)
: _has_value(false), _error(LEXY_FWD(args)...)
{}
#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ == 9
// GCC 9 crashes when trying to convert nullopt to a value here.
template <typename Nullopt,
typename = std::enable_if_t<std::is_same_v<std::decay_t<Nullopt>, nullopt>>>
_result_storage_non_trivial(result_value_t, Nullopt&&) : _has_value(true), _value()
{}
template <typename Nullopt,
typename = std::enable_if_t<std::is_same_v<std::decay_t<Nullopt>, nullopt>>>
_result_storage_non_trivial(result_error_t, Nullopt&&) : _has_value(false), _error()
{}
#endif
_result_storage_non_trivial(_result_storage_non_trivial&& other) noexcept
: _has_value(other._has_value)
{
if (_has_value)
::new (static_cast<void*>(&_value)) T(LEXY_MOV(other._value));
else
::new (static_cast<void*>(&_error)) E(LEXY_MOV(other._error));
}
~_result_storage_non_trivial() noexcept
{
if (_has_value)
_value.~T();
else
_error.~E();
}
_result_storage_non_trivial& operator=(_result_storage_non_trivial&& other) noexcept
{
if (_has_value && other._has_value)
{
_value = LEXY_MOV(other._value);
}
else if (_has_value && !other._has_value)
{
_value.~T();
::new (static_cast<void*>(&_error)) E(LEXY_MOV(other._error));
_has_value = false;
}
else if (!_has_value && other._has_value)
{
_error.~E();
::new (static_cast<void*>(&_value)) T(LEXY_MOV(other._value));
_has_value = true;
}
else // !_has_value && !other._has_value
{
_error = LEXY_MOV(other._error);
}
return *this;
}
};
template <typename T, typename E>
using _result_storage_impl
= std::conditional_t<std::is_trivially_copyable_v<T> && std::is_trivially_copyable_v<E>,
_result_storage_trivial<T, E>, _result_storage_non_trivial<T, E>>;
template <typename T, typename E>
using _result_storage
= _result_storage_impl<std::conditional_t<std::is_void_v<T>, result_value_t, T>,
std::conditional_t<std::is_void_v<E>, result_error_t, E>>;
} // namespace lexy
namespace lexy
{
/// Stores a T or an E.
/// Supports `void` for either one of them meaning "none".
template <typename T, typename E>
class result : _result_storage<T, E>
{
static constexpr auto optional_tag = [] {
if constexpr (std::is_void_v<T>)
return result_error;
else
return result_value;
}();
public:
using value_type = typename _result_storage<T, E>::value_type;
using error_type = typename _result_storage<T, E>::error_type;
//=== constructor ===//
constexpr result() : _result_storage<T, E>(result_error) {}
template <typename... Args>
constexpr result(result_value_t, Args&&... args)
: _result_storage<T, E>(result_value, LEXY_FWD(args)...)
{}
template <typename... Args>
constexpr result(result_error_t, Args&&... args)
: _result_storage<T, E>(result_error, LEXY_FWD(args)...)
{}
/// Conversion from an errored result with a different value type.
template <typename U>
constexpr explicit result(const result<U, E>& other) : result(result_error, other.error())
{}
template <typename U>
constexpr explicit result(result<U, E>&& other) : result(result_error, LEXY_MOV(other).error())
{}
/// Construct a value without tag if we don't have an error.
template <typename Arg, typename = std::enable_if_t<
(std::is_constructible_v<T, Arg> || std::is_constructible_v<E, Arg>)
|| (std::is_void_v<T> || std::is_void_v<E>)>>
constexpr explicit result(Arg&& arg) : result(optional_tag, LEXY_FWD(arg))
{}
//=== access ===//
constexpr explicit operator bool() const noexcept
{
return this->_has_value;
}
constexpr bool has_value() const noexcept
{
return this->_has_value;
}
constexpr bool has_error() const noexcept
{
return !this->_has_value;
}
static constexpr bool has_void_value() noexcept
{
return std::is_same_v<T, void>;
}
static constexpr bool has_void_error() noexcept
{
return std::is_same_v<E, void>;
}
constexpr value_type& value() & noexcept
{
LEXY_PRECONDITION(has_value());
return this->_value;
}
constexpr const value_type& value() const& noexcept
{
LEXY_PRECONDITION(has_value());
return this->_value;
}
constexpr value_type&& value() && noexcept
{
LEXY_PRECONDITION(has_value());
return LEXY_MOV(this->_value);
}
constexpr const value_type&& value() const&& noexcept
{
LEXY_PRECONDITION(has_value());
return LEXY_MOV(this->_value);
}
constexpr error_type& error() & noexcept
{
LEXY_PRECONDITION(has_error());
return this->_error;
}
constexpr const error_type& error() const& noexcept
{
LEXY_PRECONDITION(has_error());
return this->_error;
}
constexpr error_type&& error() && noexcept
{
LEXY_PRECONDITION(has_error());
return LEXY_MOV(this->_error);
}
constexpr const error_type&& error() const&& noexcept
{
LEXY_PRECONDITION(has_error());
return LEXY_MOV(this->_error);
}
};
} // namespace lexy
#endif // LEXY_RESULT_HPP_INCLUDED
<file_sep>/tests/lexy/dsl/punctuator.cpp
// Copyright (C) 2020 <NAME> <<EMAIL>>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#include <lexy/dsl/punctuator.hpp>
#include <doctest/doctest.h>
TEST_CASE("dsl punctuators")
{
CHECK(std::is_same_v<const decltype(LEXY_LIT(".")), decltype(lexy::dsl::period)>);
CHECK(std::is_same_v<const decltype(LEXY_LIT(",")), decltype(lexy::dsl::comma)>);
CHECK(std::is_same_v<const decltype(LEXY_LIT(":")), decltype(lexy::dsl::colon)>);
CHECK(std::is_same_v<const decltype(LEXY_LIT(";")), decltype(lexy::dsl::semicolon)>);
CHECK(std::is_same_v<const decltype(LEXY_LIT("-")), decltype(lexy::dsl::hyphen)>);
CHECK(std::is_same_v<const decltype(LEXY_LIT("/")), decltype(lexy::dsl::slash)>);
CHECK(std::is_same_v<const decltype(LEXY_LIT("\\")), decltype(lexy::dsl::backslash)>);
CHECK(std::is_same_v<const decltype(LEXY_LIT("'")), decltype(lexy::dsl::apostrophe)>);
CHECK(std::is_same_v<const decltype(LEXY_LIT("#")), decltype(lexy::dsl::hash_sign)>);
CHECK(std::is_same_v<const decltype(LEXY_LIT("$")), decltype(lexy::dsl::dollar_sign)>);
CHECK(std::is_same_v<const decltype(LEXY_LIT("@")), decltype(lexy::dsl::at_sign)>);
}
<file_sep>/tests/CMakeLists.txt
# Copyright (C) 2020 <NAME> <<EMAIL>>
# This file is subject to the license terms in the LICENSE file
# found in the top-level directory of this distribution.
# Fetch doctest.
include(FetchContent)
FetchContent_Declare(doctest GIT_REPOSITORY https://github.com/onqtam/doctest)
FetchContent_MakeAvailable(doctest)
# A generic test target.
add_library(lexy_test_base INTERFACE)
target_sources(lexy_test_base INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/doctest_main.cpp)
target_link_libraries(lexy_test_base INTERFACE foonathan::lexy::dev foonathan::lexy::file doctest)
target_compile_definitions(lexy_test_base INTERFACE DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING=1 LEXY_TEST)
# Add code coverage options to our test target.
if(${CMAKE_CXX_COMPILER_ID} MATCHES "GNU|Clang")
if(NOT "${CMAKE_CXX_SIMULATE_ID}" STREQUAL "MSVC")
target_compile_options(lexy_test_base INTERFACE -O0 -g --coverage)
target_link_options(lexy_test_base INTERFACE --coverage)
endif()
endif()
# Add the individual tests.
add_subdirectory(lexy)
add_subdirectory(examples)
add_test(NAME unit_tests COMMAND lexy_test)
add_test(NAME email COMMAND lexy_test_email)
add_test(NAME json COMMAND lexy_test_json)
add_test(NAME shell COMMAND lexy_test_shell)
add_test(NAME xml COMMAND lexy_test_xml)
| a20299828cec887c226e947be341156a023ff27f | [
"CMake",
"C++"
] | 4 | C++ | zeta1999/lexy | e82030f326f4def228b78b11dc1ca54b95eb8aae | 30acbcccd339ff3ad7e7887e4b348b10e3bd2a81 |
refs/heads/master | <file_sep>aiohttp==3.6.2
async-timeout==3.0.1
attrs==19.3.0
chardet==3.0.4
discord.py==1.3.3
idna==2.9
idna-ssl==1.1.0
iso8601==0.1.11
multidict==4.7.5
-e git+http://github.com/russ-/pychallonge@bc202d7140cb08d11d345564f721c2f57129b84f#egg=pychallonge
python-dateutil==2.4.2
six==1.14.0
typing-extensions==3.7.4.2
websockets==8.1
yarl==1.4.2
<file_sep># fitbot
discord bot for fit battles, written in python.
## Prerequisites
Python 3.5+
A discord [bot](https://github.com/reactiflux/discord-irc/wiki/Creating-a-discord-bot-&-getting-a-token)
## How to install/run
`pip install -r requirements.txt`
`python3 bot.py`
<file_sep>#imports
import challonge
import config
import discord
from discord.ext import commands
import asyncio
# Enter your API keys here. Its recommended you use something else to hide
# the keys rather than placing them into file.
# Todo: hide API keys
challonge.set_credentials(config.challgone_api_name, config.challgone_api_key)
DISCORD_TOKEN = config.discord_api_token
BOT_PREFIX = ("!")
bot = commands.Bot(command_prefix=BOT_PREFIX)
#global bracket
battle_queue = {
"active": False,
"queued": 0,
"slots": 0,
"players": [],
}
def start_queue(leader, leaderId):
"""figure out if a fit battle can happen"""
global battle_queue
if battle_queue.get("active"):
return False
else:
new_queue = {
"active": True,
"leader": leader,
"leaderId": leaderId,
"queued": 1,
"slots": 2,
"players":[leader],
"playerIds":[leaderId],
"round": 0,
}
battle_queue = new_queue.copy()
print(battle_queue)
return True
#say hi
@bot.command()
async def hello(ctx):
msg = "hi!"
await ctx.send(msg)
#check whos waiting
@bot.command()
async def queue(ctx):
if battle_queue.get("active") == False:
msg = 'There currently isn''t a battle queued! ''!battle'' to start one.'
else:
msg = 'there are currently ' + ' (' + str(battle_queue.get("queued"))+ '/' + str(battle_queue.get("slots")) +')' + ' members waiting to start!'
await ctx.send(msg)
#start a new bracket
@bot.command()
async def battle(ctx):
leader = ctx.message.author.name
leaderId = ctx.message.author.id
if(start_queue(leader, leaderId)):
msg = '{0.author.mention} started a fit battle!'.format(ctx) + ' (' + str(battle_queue.get("queued"))+ '/' + str(battle_queue.get("slots")) +')'
await ctx.send(msg)
else:
msg = 'Sorry a fit battle is currently active please wait for the current battle to conclude.'
await ctx.send(msg)
#add to the queue
@bot.command()
async def add(ctx):
if ctx.message.author.name in battle_queue.values():
msg = '{0.author.mention} you are already in queue...dumbass'.format(ctx) + ' (' + str(battle_queue.get("queued"))+ '/' + str(battle_queue.get("slots")) +')'
else:
battle_queue["queued"] = battle_queue.get("queued") + 1
battle_queue["players"].append(ctx.message.author.name)
battle_queue["playerIds"].append(ctx.message.author.id)
#if the queue matches the current slots remind the leader to
# start the game if they want
if(battle_queue.get("queued") == battle_queue.get("slots")):
msg = '{0.author.mention} added to the queue!'.format(ctx) + ' <@'+str(battle_queue.get("leaderId")) + '> you can start or wait for more players!' + ' (' + str(battle_queue.get("queued"))+ '/' + str(battle_queue.get("slots")) +')'
elif (battle_queue.get("queued") > battle_queue.get("slots")):
battle_queue["slots"] = battle_queue.get("slots") * 2
msg = '{0.author.mention} added to the queue!'.format(ctx) + ' (' + str(battle_queue.get("queued"))+ '/' + str(battle_queue.get("slots")) +')'
else:
msg = '{0.author.mention} added to the queue!'.format(ctx) + ' (' + str(battle_queue.get("queued"))+ '/' + str(battle_queue.get("slots")) +')'
print(battle_queue)
await ctx.send(msg)
#start
#take the current playerlist and find their id
#DM them and tell them to send a photo for the first round
#once everyone has sent a photo run the routine to create the challong bracket
#this is the hard part i think
@bot.group()
async def start(ctx):
#check if the person who invoked is the leader
if ctx.author.id != battle_queue.get("leaderId"):
msg = 'Sorry <@'+str(battle_queue.get("leaderId")) + '> must start the battle.'
await ctx.send(msg)
else:
#increment the round
battle_queue["round"] = battle_queue.get("round") + 1
#roll call and send out DM
for i in battle_queue.get("playerIds"):
msg = 'You queued for ' + str(battle_queue.get("leader")) + "'s fit battle. Please upload a fit for Round " + str(battle_queue["round"])
user = bot.get_user(i)
await user.send(msg)
bot.run(DISCORD_TOKEN)
| 60aabbd6d3e401360fa3b99b586ed9985f7d217f | [
"Markdown",
"Python",
"Text"
] | 3 | Text | ofnlut/fitbot | 9eb39ee1da23d4289ac87b6ccf93c85e971f7516 | 4a4ab8a219a365f81c581e3b4b5fc60897b16cf3 |
refs/heads/master | <file_sep># pushups
Server side rendering with preact and firebase. [Video demo](https://www.useloom.com/share/83f7f32e777f4859bc5b1e21613198fa)
## Setting Up Firebase
* [Follow Firebase onboarding and create a new project](https://firebase.google.com)
* Copy the `config` object from Authentication -> Web Setup into `firebaseConfig.js` and make sure to `module.exports =` it.
* Set the project's database to be publicly available under database -> rules
<img src="http://i.imgur.com/4w9rETO.png">
<file_sep>const { Component, h, render } = require('preact');
const { db } = require('./firebase');
class App extends Component {
constructor() {
super();
this.state = {
timeline: [],
formData: {}
};
}
componentDidMount() {
this.timeline = db.ref('timeline');
this.people = db.ref('people');
this.timelineDisplay = this.timeline.orderByChild('createdAt');
this.timelineDisplay.on('child_added', v => {
this.setState(Object.assign({}, this.state, {
timeline: [v.val()].concat(this.state.timeline)
}));
});
this.timelineDisplay.on('child_removed', v => {
v = v.val();
this.setState(Object.assign({}, this.state, {
timeline: this.state.timeline.filter(item => item.firebaseId !== v.firebaseId)
}));
});
this.people.on('value', v =>
this.setState(Object.assign({}, this.state, { people: v.val() })));
}
componentWillUnmount() {
this.timeline.off();
this.timelineDisplay.off();
this.people.off();
delete this.timeline;
delete this.people;
}
setForm(prop) {
return ev => {
this.setState(Object.assign({}, this.state, {
formData: Object.assign({}, this.state.formData, {
[prop]: ev.target.value
})
}));
}
}
isFormInvalid() {
return !this.state.formData.person ||
!this.state.formData.number ||
!this.state.formData.reason;
}
add(ev) {
ev.preventDefault();
const _ref = this.timeline.push();
_ref.set(Object.assign({}, this.state.formData, {
completed: false,
createdAt: new Date(),
firebaseId: _ref.key
}));
const { person, number } = this.state.formData;
const people = this.state.people || {};
people[person] = people[person] || {};
db.ref(`people/${person}`).update({
total: (people[person].total || 0) + parseFloat(number)
});
this.setState(Object.assign({}, this.state, { formData: {} }));
}
complete(key, name, number) {
return () => {
this.timeline.child(key).remove();
db.ref(`people/${name}`).update({
total: this.state.people[name].total - number
});
};
}
render(props, state) {
let { people, timeline, formData } = state;
if (props.people) {
people = Object.assign({}, people, props.people);
}
if (props.timeline) {
timeline = timeline.concat(props.timeline);
}
const names = Object.keys(people || {});
return (
<div>
<div>
<h1>
Pushups
</h1>
<div>
<ul>
{
names.map(name => (<li>{name} owes {people[name].total} pushups</li>))
}
</ul>
</div>
<h2>Add New</h2>
<form onSubmit={this.add.bind(this)}>
<div>
<input
type="text"
value={formData.person || ''}
onChange={this.setForm('person')}
placeholder="Name" />
<input
type="number"
value={formData.number || null}
onChange={this.setForm('number')}
placeholder="# Pushups" />
<input
type="text"
value={formData.reason || ''}
onChange={this.setForm('reason')}
placeholder="Reason" />
<button disabled={this.isFormInvalid()}>Add</button>
</div>
</form>
</div>
<div>
<h2>Timeline</h2>
<ul>
{
(timeline || []).map(item => (
<li>
<span>
{item.person} owes {item.number} pushups for {item.reason}
</span>
<button onClick={this.complete(item.firebaseId, item.person, item.number)}>Complete</button>
</li>
))
}
</ul>
</div>
</div>
);
}
}
module.exports = App;
if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
const container = document.getElementById('container');
render(<App />, container, container.lastChild);
}
<file_sep>const firebase = require('firebase/app');
require('firebase/database');
const firebaseApp = firebase.initializeApp(require('./firebaseConfig.js'));
const db = firebaseApp.database();
module.exports = { db };
| e3b4e040adb83a0fa44ae6393c0dfe0880ae17ae | [
"Markdown",
"JavaScript"
] | 3 | Markdown | vkarpov15/pushups | 02d9e8bf88e70f251ce130786202c9ade0f5c075 | 37d9e469faa2aebd5c1a302e854cc3958b7e29c4 |
refs/heads/master | <file_sep>#!/bin/bash
DATE=$(echo $(ping -c 1 192.168.10.25) | grep -v Unreachable)
echo "*${DATE}*"
<file_sep>#!/bin/bash
#Simple Pingsweep Script
#read -p "Please enter the subnet: " SUBNET
SUBNET="192.168.212"
HOSTS=()
INDEX=0
for IP in $(seq 184 185); do
echo $SUBNET.$IP
HOSTS[$INDEX]="$(ping -c 1 $SUBNET.$IP)"
INDEX=$((INDEX+1))
done
for HOST in $(seq 0 $INDEX); do
echo "New line"
EXIST=$(echo "${HOSTS[$HOST]}" | grep -v Unreachable)
echo $EXIST
EXIST=$(echo $EXIST | grep PING | cut -c1-4 )
echo $EXIST
if [ $EXIST="PING" ]; then
echo "${HOSTS[$HOST]}"
fi
done
<file_sep>#!/bin/bash
for NAME in $(cat names.txt); do
echo "The names are: $NAME"
done
<file_sep>#!/bin/bash
NAME="hojang"
echo "My name is $NAME"
SPORT="Foot"
echo "The most popular sport is ${SPORT}ball"
STUDENT_01="John"
<file_sep>#!/bin/bash
read -p "Please enter your username: " NAME
if [ "$NAME" = "Elliot" ];
then
echo "Welcome Elliot"
else
echo "Please register"
fi
<file_sep>#!/bin/bash
#This is how we define function
function test_shadow(){
if [ -e /etc/shadow ]; then
echo "It exist"
test_password
else
echo "The file does not exist"
fi
}
function test_password(){
if [ -e /etc/passwd ]; then
echo "Yes It exist"
else
echo "The file does not exist"
fi
}
test_shadow
<file_sep>#!/bin/bash
if [ -e /etc/shadow ];
then
echo "Yes it exist"
else
echo "The file does not exist"
fi
<file_sep>#!/bin/bash
echo "Execution of script: $0"
echo "Please enter the name of the user:$1"
#Adding user
if [ $1 = "Y" ]; then
adduser --home /home/$2 $2
else
echo "If you want to create user set 1 paramether to Y"
fi
<file_sep>#!/bin/bash
#Simple Password Generator
read -p "Enter lenght of password: " PASS_LENGHT
for PASSWORD in $(seq 1 5);
do
openssl rand -base64 48 | cut -c1-$PASS_LENGHT
done
<file_sep>#!/bin/bash
echo "Please enter your full name: "
read FNAME LNAME
echo "Your name is $FNAME $LNAME"
<file_sep>#!/bin/bash
#User Input
read -p "Enter your name: " NAME
echo "Your name is $NAME"
<file_sep>#!/bin/bash
echo "Do you want to install this softwar?"
CHOICES="y n"
select OPTION in $CHOICES; do
echo "The selected option is $REPLY"
echo "The selected choice is $OPTION"
done
<file_sep>#!/bin/bash
#========================================================================
# Obì¹enec 1.1
# Copyright (C) 2002-2003 <NAME>
#------------------------------------------------------------------------
# E-mail: <EMAIL>
# Web: http://www.seif.cz
#------------------------------------------------------------------------
# Poslední modifikace: 12.11. 2003
# Znaková sada: ISO-8859-2
#------------------------------------------------------------------------
# Tento program je volné programové vybavení; mù¾ete jej ¹íøit a
# modifikovat podle ustanovení Obecné veøejné licence GNU, vydávané Free
# Software Foundation; a to buï verze 2 této licence anebo (podle va¹eho
# uvá¾ení) kterékoli pozdìj¹í verze.
#------------------------------------------------------------------------
# Tento program je roz¹iøován v nadìji, ¾e bude u¾iteèný, av¹ak BEZ
# JAKÉKOLI ZÁRUKY; neposkytují se ani odvozené záruky PRODEJNOSTI anebo
# VHODNOSTI PRO URÈITÝ ÚÈEL.
# Dal¹í podrobnosti hledejte v Obecné veøejné licenci GNU.
#------------------------------------------------------------------------
# Kopii Obecné veøejné licence GNU jste mìl obdr¾et spolu s tímto
# programem; pokud se tak nestalo, napi¹te o ni Free Software Foundation,
# Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#========================================================================
PID_OBESENCE=$$
etc="/usr/local/etc"
share="/usr/local/share/obesenec"
function napoveda() {
echo "obesenec.sh:"
echo "-h, --help vypí¹e nápovìdu"
echo "-d zapne xtrace"
} # napoveda()
if [ "$1" == "-d" ]; then
set -o xtrace
elif [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
napoveda
exit 0
elif [ "$1" ]; then
echo "Neznámý pøepínaè: $1"
napoveda
exit 0
fi
function cas_vyprsel() {
konec=10
vypis_prohra
} # cas_vyprsel()
trap 'cas_vyprsel' TERM
function stopky_start() {
if [ "$time" != "0" ]; then
"${share}/stopky.sh" $PID_OBESENCE $time &
PID_STOPEK=$!
fi
} # stopky_start()
function stopky_stop() {
if [ "$time" != "0" ] &&
[ "$PID_STOPEK" ] &&
[ $(ps -p $PID_STOPEK -o pid | wc -l) -ge 2 ]; then
kill -SIGTERM $PID_STOPEK
fi
} # stopky_stop()
function vypis_hlavicka() {
echo "_________"
echo " Pøíkazy "
echo "~~~~~~~~~"
echo "nh - nová hra"
echo "end - konec programu"
echo "licence - licenèní úmluvy"
echo "__________"
echo " Obì¹enec "
echo "~~~~~~~~~~"
} # vypis_hlavicka()
function vypis_konec() {
stopky_start
echo -n "Zadej znak nebo pøíkaz: "
read retezec
} # vypis_konec()
function vypis_prohra() {
clear
vypis_hlavicka
head -n130 "${share}/obesenec.obr" | tail -n13
echo
echo "Tipované slovo (vìta): $slovo"
echo "Prohrál(a) jsi."
sleep 2
echo
echo -n "Stiskni ENTER"
} # vypis_prohra()
function vypis_vyhra() {
clear
vypis_hlavicka
echo "Tipované slovo (vìta): $slovo"
echo "Vyhrál(a) jsi."
echo -n "Zadej pøíkaz: ";
read retezec
} # vypis_vyhra()
function obes() {
pozice=$(($chyba * 13))
head -n$pozice "${share}/obesenec.obr" | tail -n13
} # obes()
function pridej_znaky() {
znak_dia=""
znak_vel=""
if [ "$rozliseni" == "nic" ] || [ "$rozliseni" == "velikost" ]; then
znak_dia=$(echo $retezec_por | tr 'riseztcyundao' 'øí¹ì¾»èýùòïáó')
znak_dia="$znak_dia$(echo $retezec_por | tr 'riseztcyundao' 'ØÍ©Ì®«ÈÝÙÒÏÁÓ')"
znak_dia="$znak_dia$(echo $retezec_por | tr 'ue' 'úé')"
znak_dia="$znak_dia$(echo $retezec_por | tr 'ue' 'ÚÉ')"
fi
if [ "$rozliseni" == "nic" ] || [ "$rozliseni" == "diakritika" ]; then
znak_vel=$(echo "$retezec_por" | tr [:lower:] [:upper:])
fi
echo "$znak_dia$znak_vel"
} # pridej_znaky()
function kontrola() {
if [ "$konec" -eq "10" ]; then
vypis_hlavicka
echo -n "Zadej pøíkaz: "
read retezec
else
vypis_hlavicka
if [ $(expr index "$slovo_por" $retezec_por) -eq 0 ]; then
chyba=$(($chyba + 1))
chybne_znaky="$chybne_znaky$retezec"
if [ "$chyba" -eq "10" ]; then
konec=10
vypis_prohra
return;
fi
else
if [ $(expr index "$nalezene_znaky" $retezec_por) -eq 0 ]; then
nalezene_znaky="$nalezene_znaky$retezec_por"
znak_pri=$(pridej_znaky)
nalezene_znaky="$nalezene_znaky$znak_pri"
slovo_tip=$(echo $slovo | sed "s/[^$nalezene_znaky]/-/g")
if [ $(expr index "$slovo_tip" "-") -eq 0 ]; then
konec=10
vypis_vyhra
return;
fi
fi
fi
obes
echo
echo "Nalezené znaky: $nalezene_znaky"
echo "Tipované slovo (vìta): $slovo_tip"
if ! $([ -z "$chybne_znaky" ]); then
echo "Slovo neobsahuje: $chybne_znaky"
fi
vypis_konec
fi
} # kontrola()
function modifikace() {
if [ "$rozliseni" == "nic" ]; then
echo $(echo "$1" | tr [:upper:] [:lower:] | tr 'øí¹ì¾»èýùòúïáéó' 'riseztcyunudaeo')
elif [ "$rozliseni" == "velikost" ]; then
echo $(echo "$1" | tr 'øí¹ì¾»èýùòúïáéóØÍ©Ì®«ÈÝÙÒÚÏÁÉÓ' 'riseztcyunudaeoRISEZTCYUNUDAEO')
elif [ "$rozliseni" == "diakritika" ]; then
echo $(echo "$1" | tr [:upper:] [:lower:])
elif [ "$rozliseni" == "all" ]; then
echo $1
fi
} # modifikace()
function nova_hra() {
stopky_stop
cislo=$(($RANDOM % $(($typ + 1))))
nahodny_radek=$(($RANDOM % $(wc -l "${share}/obesenec${cislo}.dat" | sed 's/^ *\([0123456789]\+\).*$/\1/')))
if [ "$nahodny_radek" -eq "0" ]; then
nahodny_radek=1
fi
slovo=$(head -n$nahodny_radek "${share}/obesenec${cislo}.dat" | tail -n1)
slovo_delka=${#slovo}
slovo_por=$(modifikace "$slovo")
slovo_tip=$(echo "$slovo" | sed 's/[^ .!?,]/-/g')
nalezene_znaky=".!?, "
chybne_znaky=""
chyba=0
konec=0
vypis_hlavicka
echo "Tipované slovo (vìta): $slovo_tip"
vypis_konec
} # nova_hra()
function soubory_existence() {
soubor_neni=0
i=0
while [ $i -le 9 ]; do
if ! $([ -e "${share}/obesenec${i}.dat" ]); then
soubor_neni=1
echo "Soubor ${share}/obesenec${i}.dat neexistuje!"
fi
i=$(($i + 1))
done
if ! $([ -e "${share}/obesenec.obr" ]); then
soubor_neni=1
echo "Soubor ${share}/obesenec.obr neexistuje!"
fi
if ! $([ -e "${etc}/obesenec.conf" ]); then
soubor_neni=1
echo "Soubor ${etc}/obesenec.conf neexistuje!"
fi
if ! $([ -e "${share}/stopky.sh" ]); then
soubor_neni=1
echo "Soubor stopky neexistuje!"
fi
if [ "$soubor_neni" -eq "1" ]; then
exit 1
fi
} # soubory_existence()
function konfigurace() {
typ=0
rozliseni=nic
time=0
typ=$(cat "${etc}/obesenec.conf" | sed -n 's/^typ=\(.\+\)$/\1/p')
rozliseni=$(cat "${etc}/obesenec.conf" | sed -n 's/^rozliseni=\(.\+\)$/\1/p')
time=$(cat "${etc}/obesenec.conf" | sed -n 's/^time=\(.\+\)$/\1/p')
} # konfigurace()
clear
soubory_existence
konfigurace
echo "_______________________________________________________"
echo " Obì¹enec verze 1.1, Copyright (C) 2002-2003 <NAME> "
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo " Obì¹enec je ABSOLUTNÌ BEZ ZÁRUKY; podrobnosti se dozvíte zadáním"
echo "pøíkazu licence. Jde o volné programové vybavení a jeho ¹íøení za"
echo "jistých podmínek je vítáno; podrobnosti získáte zadáním pøíkazu licence."
nova_hra
while :
do
clear
if [ -z "$retezec" ]; then
vypis_hlavicka
if [ "$konec" -eq "10" ]; then
echo -n "Zadej pøíkaz: "
else
echo -n "Zadej znak nebo pøíkaz: "
fi
read retezec
else
retezec_por=$(modifikace "$retezec")
case "$retezec" in
"nh" )
clear
nova_hra;;
"end" )
exit 0
;;
"cheat" )
vypis_vyhra;;
"licence" )
if [ -e "${share}/licence.cs" ]
then
less "${share}/licence.cs"
clear
else
echo "Soubor ${share}/licence.cs nebyl nalezen!!!"
echo
fi
nova_hra
;;
[a-z] | [A-Z] )
stopky_stop
kontrola
;;
* )
vypis_hlavicka
echo "Zadal(a) jsi nepovolený znak èi pøíkaz!!!"
echo -n "Zadej znak nebo pøíkaz: "
read retezec
;;
esac
fi
done
exit 0
| 71f20dd6963d64df467141b1a8db3e6b72a418f0 | [
"Shell"
] | 13 | Shell | Hojang2/shell_scripting | 692f8456d2b856d6dde61b2efba27c62083f62af | da7bfdc99644f545cb0fd5ad00e6e4efc5d48c62 |
refs/heads/master | <repo_name>IanMercado/JuegoTragamonedas<file_sep>/TragamonedasFINAL/src/formularios/form1.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package formularios;
import java.awt.Color;
import java.util.Random;
import javafx.scene.layout.Background;
import javax.swing.*;
/**
*
* @author Cristian
*/
public class form1 extends javax.swing.JFrame {
/**
* Creates new form form1
*/
public form1() {
initComponents();
this.getContentPane().setBackground(Color.orange);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jDialog1 = new javax.swing.JDialog();
jDialog2 = new javax.swing.JDialog();
jToggleButton1 = new javax.swing.JToggleButton();
jTextField1 = new javax.swing.JTextField();
p1 = new javax.swing.JLabel();
p2 = new javax.swing.JLabel();
p3 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
sel = new javax.swing.JComboBox<>();
jButton2 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
jDialog1.getContentPane().setLayout(jDialog1Layout);
jDialog1Layout.setHorizontalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog1Layout.setVerticalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jDialog2Layout = new javax.swing.GroupLayout(jDialog2.getContentPane());
jDialog2.getContentPane().setLayout(jDialog2Layout);
jDialog2Layout.setHorizontalGroup(
jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog2Layout.setVerticalGroup(
jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
jToggleButton1.setText("jToggleButton1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("<NAME>");
setBackground(new java.awt.Color(0, 0, 0));
setLocation(new java.awt.Point(400, 300));
jTextField1.setEditable(false);
jTextField1.setBackground(new java.awt.Color(255, 204, 204));
jTextField1.setFont(new java.awt.Font("Arial", 0, 48)); // NOI18N
jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField1.setText("100");
jTextField1.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(255, 204, 204), new java.awt.Color(255, 204, 204)));
jTextField1.setFocusable(false);
jTextField1.setOpaque(false);
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
p1.setBackground(new java.awt.Color(255, 255, 255));
p1.setMaximumSize(new java.awt.Dimension(165, 165));
p1.setMinimumSize(new java.awt.Dimension(165, 165));
p1.setPreferredSize(new java.awt.Dimension(165, 165));
p2.setBackground(new java.awt.Color(255, 255, 255));
p2.setMaximumSize(new java.awt.Dimension(165, 165));
p2.setMinimumSize(new java.awt.Dimension(165, 165));
p2.setPreferredSize(new java.awt.Dimension(165, 165));
p3.setBackground(new java.awt.Color(255, 255, 255));
p3.setMaximumSize(new java.awt.Dimension(165, 165));
p3.setMinimumSize(new java.awt.Dimension(165, 165));
p3.setPreferredSize(new java.awt.Dimension(165, 165));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/giphy-1 - unscreen.gif"))); // NOI18N
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/fondo_png_con_nieve__by_baastysmiler_d4moevp-fullview.png"))); // NOI18N
jButton1.setBorderPainted(false);
jButton1.setContentAreaFilled(false);
jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Yu Gothic Medium", 1, 20)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Apuesta");
jLabel3.setFont(new java.awt.Font("Yu Gothic", 3, 36)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 51));
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("¡Apuesta para ganar!");
jLabel3.setToolTipText("");
jButton3.setText("Retirar");
jButton3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
sel.setFont(new java.awt.Font("Yu Gothic Medium", 0, 18)); // NOI18N
sel.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "20", "40", "100", "500", "1000" }));
sel.setToolTipText("");
sel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
sel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selActionPerformed(evt);
}
});
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/reset (2).png"))); // NOI18N
jButton2.setBorderPainted(false);
jButton2.setContentAreaFilled(false);
jButton2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton4.setText("Menu");
jButton4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/fondo_tragamonedas (2).jpg"))); // NOI18N
jLabel4.setPreferredSize(new java.awt.Dimension(738, 446));
jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/mano.png"))); // NOI18N
jLabel5.setText("jLabel5");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(230, 230, 230)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 474, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(124, 124, 124)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGap(190, 190, 190)
.addComponent(p1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25)
.addComponent(p2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25)
.addComponent(p3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(125, 125, 125)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(860, 860, 860)
.addComponent(sel, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(320, 320, 320)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(360, 360, 360)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(360, 360, 360)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 1000, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel5))))
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(p1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(p2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(p3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(130, 130, 130)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(5, 5, 5)
.addComponent(sel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(90, 90, 90)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton4)
.addGap(7, 7, 7)
.addComponent(jButton3))
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(layout.createSequentialGroup()
.addGap(500, 500, 500)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 605, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
}//GEN-LAST:event_jTextField1ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
Random rnd = new Random();
int Dis, Ap, rpa1, rpa2, rpa3, Fin = 0;
int[] panels = new int[3];
Dis = Integer.parseInt(jTextField1.getText());
Ap = Integer.parseInt(sel.getSelectedItem().toString());
p1.setVisible(true);
p2.setVisible(true);
p3.setVisible(true);
if (Ap > Dis || Ap < 0) {
jLabel3.setText("No tenés suficiente dinero");
}
for (int i = 0; i < panels.length; i++) {
panels[i] = rnd.nextInt(5);
}
jButton2.setVisible(false);
if (Dis >= 20 && Ap <= Dis) {
for (int i = 0; i < panels.length; i++) {
switch (panels[i]) {
case 0:
if (i == 0) {
p1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/cerezas.png")));
} else if (i == 1) {
p2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/cerezas.png")));
} else if (i == 2) {
p3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/cerezas.png")));
}
break;
case 1:
if (i == 0) {
p1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/7.png")));
} else if (i == 1) {
p2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/7.png")));
} else if (i == 2) {
p3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/7.png")));
}
break;
case 2:
if (i == 0) {
p1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/sandia.png")));
} else if (i == 1) {
p2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/sandia.png")));
} else if (i == 2) {
p3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/sandia.png")));
}
break;
case 3:
if (i == 0) {
p1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/uvas.png")));
} else if (i == 1) {
p2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/uvas.png")));
} else if (i == 2) {
p3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/uvas.png")));
}
break;
case 4:
if (i == 0) {
p1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/limon.png")));
} else if (i == 1) {
p2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/limon.png")));
} else if (i == 2) {
p3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/limon.png")));
}
break;
}
}
jLabel3.setText("Perdiste $" + Ap);
if (panels[1] == panels[2] && panels[0] == panels[1]) {
Dis += Ap * 2;
jLabel3.setText("Ganaste $" + Ap * 3);
} else if (panels[0] == panels[1] || panels[0] == panels[2] || panels[2] == panels[1]) {
Dis += (Ap / 2);
jLabel3.setText("Recuperaste $" + (Ap / 2));
} else {
Dis -= Ap;
}
} else if (Dis < 20) {
jLabel3.setText("No tienes fondos suficientes");
p1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/game_over_1.png")));
p2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/game_over_2.png")));
p3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/game_over_3.png")));
}
jTextField1.setText(String.valueOf(Dis));
Fin = Integer.parseInt(jTextField1.getText());
if (Fin < 20) {
jLabel3.setText("Perdiste");
jButton2.setVisible(true);
jTextField1.setText("0");
p1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/game_over_1.png")));
p2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/game_over_2.png")));
p3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/game_over_3.png")));
}
}//GEN-LAST:event_jButton1ActionPerformed
private void selActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_selActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
int Dis;
Dis = Integer.parseInt(jTextField1.getText());
if (Dis < 20) {
jTextField1.setText("100");
jLabel3.setText("Has reiniciado");
p1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/null.png")));
p2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/null.png")));
p3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/null.png")));
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
int Dis;
Dis = Integer.parseInt(jTextField1.getText());
jLabel3.setText("Has retirado: " + Dis);
jTextField1.setText("0");
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
form2 f2 = new form2();
f2.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton4ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(form1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(form1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(form1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(form1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new form1().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JDialog jDialog1;
private javax.swing.JDialog jDialog2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField jTextField1;
private javax.swing.JToggleButton jToggleButton1;
private javax.swing.JLabel p1;
private javax.swing.JLabel p2;
private javax.swing.JLabel p3;
private javax.swing.JComboBox<String> sel;
// End of variables declaration//GEN-END:variables
}
| 6bd1b254f9f5bed46e88cc8553350d34e963c811 | [
"Java"
] | 1 | Java | IanMercado/JuegoTragamonedas | 945079e9f391d1176637a26c638d4c32db88e4c3 | 389651b4804dc60f997fdd11609eb0a01134a8dc |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class App extends Component {
render() {
return (
<Link className="btn btn-primary" to="/print">Request PrintOuts</Link>
)
}
}
export default App;
<file_sep>import React, { Component } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { Redirect } from 'react-router-dom';
class PrintCenterOptions extends Component {
constructor(props) {
super(props);
this.state = {
deliverTo: '',
instructions : '',
options: [],
color: [],
fileNames: [],
redirect: false
};
this.handleRadioChange = this.handleRadioChange.bind(this);
this.handlePrintChange = this.handlePrintChange.bind(this);
this.handleColorChange = this.handleColorChange.bind(this);
this.handleCancel = this.handleCancel.bind(this);
this.handleTextAreaChange = this.handleTextAreaChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
axios.get('https://demo3662581.mockable.io/documents').then(res => {
const fileNames = res.data.documents.filename;
this.setState({fileNames})
});
}
handleRadioChange(event) {
this.setState({
deliverTo : event.target.value
});
}
handleCancel() {
axios.delete('https://demo3662581.mockable.io/print_jobs');
}
handlePrintChange(event) {
const element = event.target;
if(element.checked) {
this.state.options.push(element);
}
}
handleColorChange(event) {
const element = event.target;
if(element.checked) {
this.state.color.push(element);
}
}
handleTextAreaChange(event) {
this.setState({
instructions : event.target.value
});
}
handleSubmit(e) {
e.preventDefault();
var tableData = [];
this.state.options.forEach(option =>
{
var inputVal = document.getElementsByClassName(`${option.name}-inputValue`)[0],
colorVal = document.getElementsByClassName(`${option.name}-color`)[0],
inputInnerValue = inputVal.value,
colorValue = colorVal.checked,
printOption = {
filename: option.name,
color: colorValue,
notes: inputInnerValue
}
return (tableData.push(printOption));
}
)
const data = {
deliverTo : this.state.deliverTo,
instructions: this.state.instructions,
documents: {
document: tableData
}
}
axios.put('https://demo3662581.mockable.io/print_jobs', data).then(function(response){
console.log('saved successfully');
});
this.setState({
redirect: true
})
}
isCheckedPrint(fileName) {
if (this.state.options.indexOf(fileName) > -1) {true} else {false}
}
isCheckedColor(fileName) {
if (this.state.color.indexOf(fileName) > -1) {true} else {false}
}
handleDisabled(fileName) {
const fileExtensionValue = fileName.split('.').pop();
if(fileExtensionValue === 'zip') {
return true;
} else {
return false;
}
}
render() {
if (this.state.redirect === true) {
return <Redirect to='/success' />
}
return (
<form onSubmit={this.handleSubmit}>
<div>
<h1>Print Center Options</h1>
<p>In order for the print center to best serve you, please fill in the information below.</p>
<div>
<h3>Deliver to</h3>
<div>
<label>
<input className="radioButton" type="radio" value="owner" checked={this.state.deliverTo==="owner"} onChange={this.handleRadioChange} />
Meeting Owner
</label>
</div>
<div>
<label>
<input className="radioButton" type="radio" value="room" checked={this.state.deliverTo==="room"} onChange={this.handleRadioChange} />
Meeting Room
</label>
</div>
</div>
<div>
<textarea className="textArea" placeholder="If you have any specific instructions please enter here" value={this.state.instructions} onChange={this.handleTextAreaChange} cols={100} rows={3} />
</div>
<table className="table table-bordered">
<thead className="table-header">
<tr>
<th>File</th>
<th>Print</th>
<th>Color</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
{this.state.fileNames.map(fileName =>
<tr key={fileName} disabled={this.handleDisabled(fileName)}>
<td>{fileName}<sup className={`disabled-${this.handleDisabled(fileName)}`}>*</sup></td>
<td><input disabled={this.handleDisabled(fileName)} type="checkbox" value={fileName} name={fileName} checked={this.isCheckedPrint(fileName)} onChange={this.handlePrintChange} /></td>
<td><input className={`${fileName}-color`} disabled={this.handleDisabled(fileName)} type="checkbox" value={fileName} name={fileName} checked={this.isCheckedColor(fileName)} onChange={this.handleColorChange} /></td>
<td><input disabled={this.handleDisabled(fileName)} className={`${fileName}-inputValue`} type="text" placeholder="Notes" /></td>
</tr>
)}
</tbody>
</table>
<div className="row">
<div className="col-md-6">
<p><sup>*</sup>File is not compatible with Print Center</p>
</div>
<div className="col-md-6 text-xs-right">
<button type="submit" className="btn btn-custom">Submit</button>
<Link to="/" className="btn btn-custom" onClick={this.handleCancel}>Cancel</Link>
</div>
</div>
</div>
</form>
);
}
}
export default PrintCenterOptions;
<file_sep>Print Center
Assumptions - The file with Zip is only not compatible
No service failures
<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class SuccessMessage extends Component {
render() {
return (
<h1>Successfully submitted the form</h1>
)
}
}
export default SuccessMessage;
| 4e18db59eaccda4690b71ce12367fad25038d242 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | sravya19c/PrintCenter | c8c081867d8bea5ccfd5b187d1c848a3ee546cbb | 4fa17ef08e2dd06e40fab36648d7446bb2d60745 |
refs/heads/master | <repo_name>Space0726/vimrc<file_sep>/.script/tips/replace_file_content.sh
# Find tab in file contents and print their file name
# grep -n is printing number line option so if it doesn't needed, remove it
tab=`echo -e "\t"`
grep --include=*.* --exclude=a.out --exclude-dir=.git -rw '.' -e "${tab}" | awk -F: '{ print $1 }' | uniq
# Replace tab to space 4 in file content
# -- means that no more flags next
sed -i -- 's/\t/ /g' foo.txt
# Using together - Find and replace tab to space 4 all file in current directory (including subdirectory files)
sed -i -- 's/\t/ /g' `grep --include=*.* --exclude=a.out --exclude-dir=.git -rw '.' -e "${tab}" | awk -F: '{ print $1 }' | uniq`
<file_sep>/.script/rn
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Usage: run file..."
exit 1
fi
for name in "$@"
do
case "$name" in
*.java)
java -classpath "$(dirname "$name")" "$(basename "${name%.*}")"
;;
*.py)
python3 "${name}"
;;
*.c)
"${name%.*}"
;;
*.cc)
"${name%.*}"
;;
*.cpp)
"${name%.*}"
;;
*.rs)
"${name%.*}"
;;
*)
"${name}"
;;
esac
done
| 84ea8b5909375dbe69f57fb51f6caa93faabf3b1 | [
"Shell"
] | 2 | Shell | Space0726/vimrc | 323af382c7fd7156a4f4e72c583f704a1df12bea | 9ab9178df4984e279403cb717f96ce15e8e5fadf |
refs/heads/master | <file_sep>#ifndef OPTIONS_H
#define OPTIONS_H
/**
* options.h
*/
enum option_type {
OPTION_TYPE_NO_OPTION = 0,
OPTION_TYPE_NUMERIC = 1, // INT
OPTION_TYPE_STRING = 2
};
/* option_match() return codes. */
#define OPTION_FOUND 0
#define OPTION_UNKNOWN_OPTION -1 // option not set call to options_parse()
#define OPTION_INVALID_ARGUMENT -2 // next arg is not int or string
#define OPTION_MISSING_ARGUMENT -3 // Run out of cmd line args.
struct option_str {
char *long_option;
char *short_option;
enum option_type type;
/* If is_set = 1 then the option was found in the command line
* and the argument set, or, if the option takes no argument, the
* option was in the command line. If the command takes an argument
* (type == NUMBER || STRING) then we look at the value which is
* guaranteed to be set; string is nul-teminated; strlen(string) can
* be 0, though, if '' is given).
*
* And is is_set = 0 kilo will skip it.
*/
int is_set;
union {
int numeric;
char *string;
} value;
struct option_str *next;
};
typedef struct option_str Option;
/**
* Returns a pointer to a list of option(s) or NULL (no options).
* The list is linked.
*
* Updates &next to be the next unprocessed command line argument
* (eg file name). Note: -- is a recognized opion - end of options
* which is gobbled.
*
* Supports long ("--file") and short ("-f") options. Options can
* have 0 or 1 parameters: integer or string.
*
* The options call parameter has the following format:
* "O(,O)*" where O = long|s(:i|s)?
*
* "file|f:s" => --file options.c | -f options.c
* "count|c:i => --count 67 | -c 67
* "help|h" => --help | -h
*
* An empty / NULL options string is valid. It matches to 0 or 1 "--".
*/
Option *
options_parse(int argc, char **argv, char *options, int *next);
/**
*
*/
int
options_find(int argc, char **argv, Option *list, int *index);
#endif
<file_sep>#ifndef HELP_H
#define HELP_H
#include "const.h"
#define KILO_HELP "\r\n\r\nkilo is a simple text editor.\r\n" \
"Basic Commands:\r\n" \
"\tCtrl-Q quit\r\n" \
"\tCtrl-F find\r\n" \
"\tCtrl-S save\r\n" \
"\tCtrl-K kill/copy full line to clipboard\r\n" \
"\tCtrl-Y yank clipboard\r\n" \
"\tCtrl-SPC set mark\r\n" \
"\tCtrl-W kill region from mark to clipboard\r\n" \
"\tEsc-W copy region from mark to clipboard\r\n" \
"\tCtrl-U undo last command\r\n" \
"\tCtrl-G goto line\r\n" \
"\tCtrl-O open file\r\n" \
"\tCtrl-N new buffer\r\n" \
"\tEsc-N next buffer\r\n" \
"\tEsc-P previous buffer\r\n" \
"\tCtrl-L refresh screen (center to cursor row)\r\n" \
"\tEsc-C clear the modification flag\r\n" \
"\tEsc-X <command> (see below)\r\n" \
"\r\n" \
"Movement:\r\n" \
"\tArrow keys\r\n" \
"\tPage Down/Ctrl-V Page Down\r\n" \
"\tPage Up/Esc-V Page Up\r\n" \
"\tHome/Ctrl-A Beginning of line\r\n" \
"\tEnd/Ctrl-E End of line\r\n" \
"\tEsc-A Beginning of file\r\n" \
"\tEsc-E End of file\r\n" \
"\r\n" \
"Esc-X <command> to run commands, where <command> is one of:\r\n" \
"\tset-tab-stop, set-auto-indent, set-hard-tabs, set-soft-tabs,\r\n" \
"\tsave-buffer-as, open-file, undo, set-mode, goto-line\r\n" \
"\tcreate-buffer, next-buffer, previous-buffer, delete-buffer\r\n" \
"\tmark, copy-region, kill-region, insert-char, delete-char\r\n" \
"\tgoto-beginning, goto-end, refresh\r\n" \
"\r\n" \
"The supported higlighted file modes are (M-x set-mode <mode>):\r\n" \
"Awk, Bazel, C, Chapel, C#, Docker, Elm, Erlang, Go, Groovy, Haxe,\r\n" \
"Java, JavaScript, Kotlin, Lua, Makefile, nginx, Perl, PHP, Python,\r\n" \
"R, Ruby, Scala, Shell, SQL & Text.\r\n" \
"Usage: kilo [--help|-h|--version|-v|--ascii|-a] [--] [file] [file] ...\r\n" \
"\t--ascii allows only ascii characters.\r\n"
void display_help();
#endif
<file_sep>#ifndef CONST_H
#define CONST_H
#define KILO_VERSION "kilo -- a simple editor version 0.4.15"
#define WELCOME_STATUS_BAR "Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find | kilo --help for more info"
#define DEFAULT_KILO_TAB_STOP 8
/* Default: soft tabs. */
#define HARD_TABS (1<<2)
#define KILO_QUIT_TIMES 3
#define STATUS_MESSAGE_ABORTED "Aborted."
#define DEFAULT_SEARCH_PROMPT "Search: %s (Use ESC/Arrows/Enter)"
#define UNSAVED_CHANGES_WARNING "WARNING!!! File has unsaved changes. " \
"Press Ctrl-Q %d more times to quit."
#define DEBUG_UNDOS (1<<0)
#define DEBUG_COMMANDS (1<<1)
#define DEBUG_CURSOR (1<<2)
#endif
<file_sep>#include "clipboard.h"
#include <stdlib.h>
#include <string.h>
struct clipboard C; /* Defined here, declared in clipboard.h. */
extern struct editor_config *E;
void
clipboard_clear() {
int i;
if (C.row != NULL) { /* C.row is an array of clipboard_rows containing char *row. */
for (i = 0; i < C.numrows; i++) {
if (C.row[i].row != NULL) {
free(C.row[i].row);
}
}
free(C.row);
}
C.row = NULL;
C.numrows = 0;
C.is_full = 0;
}
void
clipboard_add_line_to_clipboard() {
if (E->cy < 0 || E->cy >= E->numrows)
return;
if (C.is_full) {
clipboard_clear();
}
erow *row = &E->row[E->cy];
// Append to the end.
C.row = realloc(C.row, sizeof(clipboard_row) * (C.numrows + 1));
C.row[C.numrows].row = malloc(row->size);
memcpy(C.row[C.numrows].row, row->chars, row->size);
C.row[C.numrows].size = row->size;
C.row[C.numrows].orig_x = E->cx;
C.row[C.numrows].orig_y = E->cy;
C.row[C.numrows].is_eol = 1;
C.numrows++;
editor_del_row(E->cy);
}
// XXX
void
clipboard_add_region_to_clipboard(int command) { // FIXME command out of here.
/* Depending on whether the mark if before or after C-W or M-W either
the first or last row may not be whole. So, a partial row is added / extracted. */
/*
if (command == COMMAND_COPY_REGION) {
// Don't delete copied region.
} else {
// Delete/kill.
}
*/
}
/* An easy command to implement. */
void
command_mark(char *success /*struct command_str *c*/) {
E->mark_x = E->cx;
E->mark_y = E->cy;
editor_set_status_message(/*c->*/success);
}
/* mode: Esc-W, Ctrl-W. First one only copies, second one also deletes the marked region.
mode == c->command. */
void
command_copy_from_mark() { // char *success, char *error/*struct command_str *c*/) {
/* No explicit mark, no kill from mark. */
if ((E->mark_x == -1 && E->mark_y == -1)
|| (E->mark_x == E->cx && E->mark_y == E->cy)) {
//editor_set_status_message(c->error_status);
return;
}
// TODO
// from_x_&_y to to_x_&_y
}
void
command_kill_from_mark() {
//command_copy_from_mark(command_get_by_key(COMMAND_KILL_REGION));
}
void
clipboard_yank_lines(char *success /*struct command_str *c*/) {
int j = 0;
for (j = 0; j < C.numrows; j++) {
editor_insert_row(E->cy++, C.row[j].row, C.row[j].size);
}
editor_set_status_message(/*c->*/success);
}
void
undo_clipboard_kill_lines(struct clipboard *copy) {
int j = 0;
if (copy == NULL) {
editor_set_status_message("Unable to undo kill lines.");
return;
}
for (j = 0; j < copy->numrows; j++) {
editor_insert_row(E->cy++, copy->row[j].row, copy->row[j].size);
}
E->cx = copy->row[copy->numrows-1].orig_x;
E->cy = copy->row[copy->numrows-1].orig_y;
editor_set_status_message("Undo kill lines!");
}
struct clipboard *
clone_clipboard() {
int i = 0;
struct clipboard *copy = malloc(sizeof(struct clipboard));
if (copy == NULL) {
editor_set_status_message("Failed to create clipboard to the undo stack.");
return NULL;
}
copy->is_full = 1;
copy->numrows = C.numrows;
copy->row = malloc(C.numrows * sizeof(struct clipboard_row));
if (copy->row == NULL) {
editor_set_status_message("Failed to create clipboard rows to the undo stack.");
return NULL;
}
for (i = 0; i < C.numrows; i++) {
clipboard_row *from = &C.row[i];
clipboard_row *to = ©->row[i];
to->row = malloc(from->size);
memcpy(to->row, from->row, from->size);
to->size = from->size;
to->orig_x = from->orig_x;
to->orig_y = from->orig_y;
to->is_eol = from->is_eol;
}
return copy;
}
<file_sep>#ifndef DATA_H
#define DATA_H
/**
* data.h
*
* Contains data structures for
* - text row
* - editor config
* - editor (buffer/file) syntax
*/
#include <ctype.h>
#include <time.h>
/* From row.h */
typedef struct erow {
int idx;
int size;
int rsize;
char *chars;
char *render;
unsigned char *hl;
int hl_open_comment;
} erow;
struct editor_config {
int cx, cy;
int rx;
int rowoff;
int coloff;
int numrows;
erow *row;
int dirty;
char *filename;
char *absolute_filename;
char *basename;
char statusmsg[256];
time_t statusmsg_time;
struct editor_syntax *syntax;
int is_new_file;
int is_banner_shown; /* If shown once do not show again. */
int is_soft_indent;
int is_auto_indent;
int tab_stop;
int debug;
/* Set by COMMAND_MARK. Default values -1. */
int mark_x, mark_y;
int ascii_only;
};
struct editor_syntax {
char *filetype; // The Mode name
char **filematch; // A list of file extensions.
char **executables; // The basename executable in #!
char **keywords;
char *singleline_comment_start;
char *multiline_comment_start;
char *multiline_comment_end;
int flags; // HARD_TAB here
int tab_stop;
int is_auto_indent;
};
/* Defined here. Points to current_buffer->E. */
struct editor_config *E;
#endif
<file_sep>#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include "const.h"
#include "syntax.h"
#include "output.h"
#include "highlight.h"
#include "filetypes.h"
/* Defined in config.h */
extern struct editor_config *E;
/* Defined in filetypes.h */
extern struct editor_syntax HLDB[];
/*** syntax highlighting ***/
int
is_separator(char c) {
return isspace(c) || c == '\0' || strchr(",.(){}+-/*=~%<>[];:", c) != NULL;
}
void
syntax_update(erow *row) {
int i = 0;
int prev_sep = 1;
int in_string = 0;
int in_comment = 0; //(row->idx > 0 && E.row[row->idx - 1].hl_open_comment);
char prev_char = '\0'; /* JK */
char *scs;
char *mcs;
char *mce;
int mcs_len;
int mce_len;
int scs_len;
char **keywords; // = E.syntax->keywords;
int changed;
row->hl = realloc(row->hl, row->rsize);
memset(row->hl, HL_NORMAL, row->rsize);
if (E->syntax == NULL)
return;
in_comment = (row->idx > 0 && E->row[row->idx - 1].hl_open_comment);
keywords = E->syntax->keywords;
scs = E->syntax->singleline_comment_start;
mcs = E->syntax->multiline_comment_start;
mce = E->syntax->multiline_comment_end;
scs_len = scs ? strlen(scs) : 0;
mcs_len = mcs ? strlen(mcs) : 0;
mce_len = mce ? strlen(mce) : 0;
while (i < row->rsize) {
char c = row->render[i];
unsigned char prev_hl = (i > 0) ? row->hl[i - 1] : HL_NORMAL;
if (scs_len && !in_string && !in_comment) {
if (!strncmp(&row->render[i], scs, scs_len)) {
memset(&row->hl[i], HL_COMMENT, row->rsize - i);
break;
}
}
/* multiline comment end found while in mlcomment */
if (mcs_len && mce_len && !in_string) {
if (in_comment) {
row->hl[i] = HL_MLCOMMENT;
if (!strncmp(&row->render[i], mce, mce_len)) {
memset(&row->hl[i], HL_MLCOMMENT, mce_len);
i += mce_len;
in_comment = 0;
prev_sep = 1;
continue;
} else {
i++;
continue;
}
} else if (!strncmp(&row->render[i], mcs, mcs_len)) {
memset(&row->hl[i], HL_MLCOMMENT, mcs_len);
i += mcs_len;
in_comment = 1;
continue;
}
}
if (E->syntax->flags & HL_HIGHLIGHT_STRINGS) {
if (in_string) {
row->hl[i] = HL_STRING;
if (c == '\\' && i+ 1 < row->rsize) {
row->hl[i + 1] = HL_STRING;
i += 2;
continue;
}
if (c == in_string) /* Closing quote char. */
in_string = 0;
i++;
prev_sep = 1;
continue;
} else {
if (c == '"' || c == '\'') {
in_string = c;
row->hl[i] = HL_STRING;
i++;
continue;
}
}
}
if (E->syntax->flags & HL_HIGHLIGHT_NUMBERS) {
if ((isdigit(c) && (prev_sep || prev_hl == HL_NUMBER))
|| (c == '.' && prev_hl == HL_NUMBER)) {
row->hl[i] = HL_NUMBER;
i++;
prev_sep = 0;
prev_char = c;
continue;
}
}
if (prev_sep) {
int j;
for (j = 0; keywords[j]; j++) {
int klen = strlen(keywords[j]);
int is_keyword2 = keywords[j][klen - 1] == '|';
if (is_keyword2)
klen--;
if (!strncmp(&row->render[i], keywords[j], klen)
&& is_separator(row->render[i + klen])) {
memset(&row->hl[i], is_keyword2 ? HL_KEYWORD2 : HL_KEYWORD1, klen);
i += klen;
break;
}
}
if (keywords[j] != NULL) {
prev_sep = 0;
continue;
}
}
prev_sep = is_separator(c);
if (isspace(c) && i > 0 && prev_char == '.' && prev_hl == HL_NUMBER)
row->hl[i - 1] = HL_NORMAL; /* Denormalize sentence ending colon. */
prev_char = c;
i++;
}
changed = (row->hl_open_comment != in_comment);
row->hl_open_comment = in_comment;
if (changed && row->idx + 1 < E->numrows) {
syntax_update(&E->row[row->idx + 1]);
}
}
int
syntax_to_colour(int hl) {
switch(hl) {
case HL_COMMENT:
case HL_MLCOMMENT: return 36;
case HL_KEYWORD1: return 33;
case HL_KEYWORD2: return 32;
case HL_NUMBER: return 31;
case HL_STRING: return 35;
case HL_MATCH: return 34;
default: return 37;
}
}
/**
syntax_set() -- sets symtax for the entire file.
*/
void
syntax_set(struct editor_syntax *syntax) {
int filerow;
E->syntax = syntax;
E->tab_stop = E->syntax->tab_stop; // TODO refactor E->tab_stop away
E->is_soft_indent = ! (E->syntax->flags & HARD_TABS);
E->is_auto_indent = E->syntax->is_auto_indent;
for (filerow = 0; filerow < E->numrows; filerow++) {
syntax_update(&E->row[filerow]);
}
}
char *
last_match(char *filename, char *extension) {
char *match = NULL;
char *previous = NULL;
while ((match = strstr(filename, extension)) != NULL) {
previous = match;
filename = match+strlen(filename);;
}
// The last match.
return previous;
}
/**
* A helper function. Returns 1 if mode is set, 0 otherwise.
*/
int
is_syntax_mode_set() {
return E->syntax != NULL;
}
int
syntax_set_mode_by_filename_extension(int silent) {
return syntax_select_highlight(NULL, silent);
}
/**
* An alias to syntax_select_highlight(char *mode)
*/
int
syntax_set_mode_by_name(char *mode, int silent) {
return syntax_select_highlight(mode, silent);
}
/**
* Sets file mode for syntax highlighting.
*
* If mode == NULL try to match filename extension.
* if mode != NULL tries to find the corresponding match (see filetypes.c)
*
* if silent, suppress messages.
*
* return 0 ok, 1 = no file, mode, -1 = error
*/
int
syntax_select_highlight(char *mode, int silent) {
unsigned int j;
int entries = hldb_entries();
//int mode_found = 0;
char *p = NULL ;
E->syntax = NULL;
if (E->filename == NULL && mode == NULL)
return 1;
for (j = 0; j < entries; j++) {
struct editor_syntax *s = &HLDB[j];
unsigned int i = 0;
/* Set explicitely based on cmd line option
or M-x set-command-mode (& another prompt for the mode). */
if (mode != NULL) {
/* set-mode <mode> or -*- <mode> -*- */
if (s->filetype
&& !strcasecmp(mode, s->filetype)) {
syntax_set(s);
if (! silent) {
editor_set_status_message("Mode set to '%s'",
s->filetype);
}
return 0;
}
/* mode is #! executable ? */
while (s->executables[i]) {
// Or just a strncmp()? python37 vs python?
p = strstr(mode, s->executables[i]);
if (p != NULL) {
syntax_set(s);
return 0;
}
i++;
}
} else { /* mode == NULL, set it based on the filematch. */
while (s->filematch[i]) {
p = last_match(E->filename, s->filematch[i]);
//p = strstr(E->filename, s->filematch[i]);
if (p != NULL) {
int patlen = strlen(s->filematch[i]);
if (p[patlen] == '\0') {
//s->filematch[i][0] != '.' || p[patlen] == '\0') {
syntax_set(s);
return 0;
}
}
i++;
}
}
}
// Mode was not found.
if (mode != NULL) {
if (! silent)
editor_set_status_message("Unknown mode '%s'", mode);
return -1;
}
return 0;
}
<file_sep>#ifndef OUTPUT_H
#define OUTPUT_H
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include "const.h"
#include "data.h"
#include "row.h"
#include "terminal.h"
#include "highlight.h"
struct abuf {
char *b;
int len;
};
#define ABUF_INIT { NULL, 0 }
void ab_append(struct abuf *ab, const char *s, int len);
void ab_free(struct abuf *ab);
/* TODO editor -> output */
void editor_scroll();
void editor_draw_rows(struct abuf *ab);
void editor_refresh_screen();
void editor_set_status_message(const char *fmt, ...);
void editor_draw_message_bar(struct abuf *ab);
void editor_draw_status_bar(struct abuf *ab);
void editor_draw_rows(struct abuf *ab);
void debug_cursor(); /* TODO maybe in debug.[ch] */
#endif
<file_sep>#ifndef SYNTAX_H
#define SYNTAX_H
/**
syntax.h
*/
#include "data.h"
#include "filetypes.h"
int is_separator(char c);
void syntax_update(erow *row);
int syntax_to_colour(int hl);
void syntax_set(struct editor_syntax *syntax);
int is_syntax_mode_set(); // a wrapper for E->syntax != NULL
int syntax_set_mode_by_name(char *name, int silent); // An alias for syntax_select_hightlight(mode)
int syntax_set_mode_by_filename_extension(int silent); // Note: E->filename already set.
int syntax_select_highlight(char *mode, int silent);
#endif
<file_sep>/*
kilo -- lightweight editor
Based on the kilo project (https://github.com/antirez/kilo):
Copyright (c) 2016, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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.
*/
#include "kilo.h"
#include "output.h"
#include "options.h"
/** buffers **/
void
handle_resize(int dummy) {
char msg[80];
if (get_window_size(&TERMINAL.screenrows, &TERMINAL.screencols) == -1)
die("get_window_size@handle_resize");
TERMINAL.screenrows -= 2; /* status & message bars */
sprintf(msg, "Resized to %d rows and %d columns.",
TERMINAL.screenrows, TERMINAL.screencols);
editor_scroll();
editor_set_status_message(msg);
editor_refresh_screen();
}
void
open_argument_files(int argc, char **argv, int index) {
struct command_str *c = command_get_by_key(COMMAND_OPEN_FILE);
if (index >= argc)
return;
/* We have already called init_buffer() once before argument parsing. */
command_open_file(argv[index]);
while (++index < argc) {
(void) create_buffer(BUFFER_TYPE_FILE, 0, c->success, COMMAND_NO_CMD);
command_open_file(argv[index]);
}
}
void
parse_options(int argc, char **argv) {
int file_index = 0; // Start index of file names.
Option *list = options_parse(argc, argv, "version|v,help|h,debug|d:i,ascii|a", &file_index);
while (list != NULL) { // options_parse can return NULL
if (list->is_set) {
if (! strcmp(list->long_option, "debug")
|| ! strcmp(list->short_option, "d")) {
E->debug = list->value.numeric;
} else if (! strcmp(list->long_option, "ascii")
|| ! strcmp(list->short_option, "a")) {
E->ascii_only = 1;
} else if (! strcmp(list->long_option, "version")
|| ! strcmp(list->short_option, "v")) {
print_version();
exit(0);
} else if (! strcmp(list->long_option, "help")
|| ! strcmp(list->short_option, "h")) {
display_help();
exit(0);
}
}
list = list->next;
}
if (file_index < argc)
open_argument_files(argc, argv, file_index);
}
#if 0
void
old_parse_options(int argc, char **argv) {
struct command_str *c = command_get_by_key(COMMAND_OPEN_FILE);
if (argc >= 3) {
if (!strcmp(argv[1], "-d") || !strcmp(argv[1], "--debug")) {
E->debug = atoi(argv[2]);
/* TODO multiple files: create buffers & open. */
if (argc >= 4) {
open_argument_files(3, argc, argv, c->success);
}
} else {
open_argument_files(1, argc, argv, c->success);
}
} else if (argc >= 2) {
if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
print_version();
exit(0);
} else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
display_help();
exit(0);
} else if (!strcmp(argv[1], "-a") || !strcmp(argv[1], "--ascii")) {
E->ascii_only = 1;
} else {
open_argument_files(1, argc, argv, c->success);
}
}
}
#endif
int
main(int argc, char **argv) {
enable_raw_mode();
buffer = create_buffer(BUFFER_TYPE_FILE, 0, "", COMMAND_NO_CMD);
init_editor();
parse_options(argc, argv); // Also opens file.
editor_set_status_message(WELCOME_STATUS_BAR);
signal(SIGWINCH, handle_resize);
while (1) {
editor_refresh_screen();
editor_process_keypress();
}
return 0;
}
<file_sep>#ifndef BUFFER_H
#define BUFFER_H
#include "data.h"
#include "terminal.h"
#include "clipboard.h"
#include "undo.h"
#include "output.h"
#include "init.h"
#include "command.h"
/** buffer */
enum buffer_type {
BUFFER_TYPE_FILE = 0,
BUFFER_TYPE_READONLY,
BUFFER_TYPE_COMMAND
};
struct buffer_str {
int type; /* file, command, read (*Help*, for example) */
struct editor_config E;
struct undo_str *undo_stack;
struct buffer_str *prev;
struct buffer_str *next;
};
#define EDITOR_CONFIG ¤t_buffer->E
struct buffer_str *buffer; /* Definition here. */
struct buffer_str *current_buffer; /* Definition here.*/
/** */
struct buffer_str *create_buffer(int type, int verbose, char *success, int init_undo_command);
void command_next_buffer(); /* TODO circular. */
void command_previous_buffer(); /* TODO circular. */
void delete_current_buffer();
#endif
<file_sep>#ifndef VERSION_H
#define VERSION_H
/**
version.h
*/
void print_version();
#endif
<file_sep>#include "undo.h"
#include "buffer.h"
#include "clipboard.h"
extern struct buffer_str *current_buffer;
extern struct buffer_str *buffer;
/*** undo ***/
struct undo_str *
init_undo_stack(int default_command) {
struct undo_str *undo_stack = malloc(sizeof(struct undo_str));
if (undo_stack == NULL)
die("undo stack");
undo_stack->undo_command_key = default_command; //COMMAND_NO_CMD;
undo_stack->command_key = default_command; //COMMAND_NO_CMD; // The terminus, new stack entries on top of this.
undo_stack->cx = 0;
undo_stack->cy = 0;
undo_stack->orig_value = 0;
undo_stack->clipboard = NULL;
undo_stack->next = NULL;
return undo_stack;
}
void
undo_debug_stack() {
struct undo_str *p = current_buffer->undo_stack;
char *debug = NULL;
int i = 1;
int currlen = 0;
int from = 0;
if (!(E->debug & DEBUG_UNDOS))
return;
while (p != NULL) {
char *entry = malloc(80);
int len = sprintf(entry, "|%d={%d,%d,%d}", i++, p->command_key, p->undo_command_key, p->orig_value);
debug = realloc(debug, currlen + len + 1);
memcpy(&debug[currlen], entry, len);
debug[currlen + len] = '\0';
currlen += len;
free(entry);
p = p->next;
}
if (currlen > TERMINAL.screencols)
from = currlen - TERMINAL.screencols;
else
from = 0;
editor_set_status_message(&debug[from]);
}
struct undo_str *
alloc_and_init_undo(int command_key) {
struct undo_str *undo = malloc(sizeof(struct undo_str));
if (undo == NULL)
die("alloc_and_init_undo");
undo->cx = E->cx;
undo->cy = E->cy;
undo->command_key = command_key;
undo->clipboard = NULL;
undo->next = current_buffer->undo_stack;
current_buffer->undo_stack = undo;
return undo;
}
/* no args for commands. */
void
undo_push_simple(int command_key, int undo_command_key) {
// if (current_buffer->undo_stack == NULL)
// current_buffer->undo_stack = init_undo_stack();
struct undo_str *undo = alloc_and_init_undo(command_key);
undo->undo_command_key = undo_command_key;
undo->orig_value = -1;
undo_debug_stack();
}
void
undo_push_one_int_arg(int command_key, int undo_command_key, int orig_value) {
struct undo_str *undo = alloc_and_init_undo(command_key);
undo->undo_command_key = undo_command_key;
undo->orig_value = orig_value;
undo_debug_stack();
}
void
undo_push_clipboard() {
struct clipboard *copy = clone_clipboard();
struct undo_str *undo = alloc_and_init_undo(COMMAND_KILL_LINE);
undo->undo_command_key = COMMAND_YANK_CLIPBOARD;
undo->clipboard = copy;
undo->orig_value = -999;
undo_debug_stack();
}
void
undo() {
if (current_buffer->undo_stack == NULL) {
current_buffer->undo_stack = init_undo_stack(COMMAND_NO_CMD);
return;
}
if (current_buffer->undo_stack->command_key == COMMAND_NO_CMD)
return;
struct undo_str *top = current_buffer->undo_stack;
current_buffer->undo_stack = top->next;
undo_debug_stack();
switch(top->undo_command_key) {
case COMMAND_MOVE_CURSOR_UP:
key_move_cursor(ARROW_UP);
break;
case COMMAND_MOVE_CURSOR_DOWN:
key_move_cursor(ARROW_DOWN);
break;
case COMMAND_MOVE_CURSOR_LEFT:
key_move_cursor(ARROW_LEFT);
break;
case COMMAND_MOVE_CURSOR_RIGHT:
key_move_cursor(ARROW_RIGHT);
break;
case COMMAND_SET_TAB_STOP:
E->tab_stop = top->orig_value;
break;
case COMMAND_SET_HARD_TABS:
E->is_soft_indent = 0;
break;
case COMMAND_SET_SOFT_TABS:
E->is_soft_indent = 1;
break;
case COMMAND_SET_AUTO_INDENT:
E->is_auto_indent = top->orig_value;
break;
case COMMAND_DELETE_CHAR:
editor_del_char(1);
break;
case COMMAND_INSERT_CHAR:
if (top->orig_value == '\r')
editor_insert_newline();
else
editor_insert_char(top->orig_value);
break;
case COMMAND_DELETE_INDENT_AND_NEWLINE: {
// Undoes command_insert_newline().
int del = top->orig_value;
while (del-- > 0)
editor_del_char(1);
break;
}
case COMMAND_YANK_CLIPBOARD:
undo_clipboard_kill_lines(top->clipboard);
free(top->clipboard->row);
free(top->clipboard);
break;
case COMMAND_GOTO_LINE:
E->cy = top->orig_value;
command_refresh_screen();
break;
case COMMAND_NEXT_BUFFER:
command_next_buffer();
break;
case COMMAND_PREVIOUS_BUFFER:
command_previous_buffer();
break;
default:
break;
}
top->next = NULL;
free(top);
}
<file_sep>#include "buffer.h"
/* Multiple buffers. Editor config and undo stack are buffer specific;
clipboard and editor syntax aren't.
Buffer types: file (like now), readonly (*Help), command (M-x compile, M-x repl?)
TODO: macros to handle buffer->E....blaa. ?
TODO commands: open-file (C-x C-f), create-buffer, switch-buffer,
close-buffer(-and-save?), kill-buffer (?).
*/
/* create_buffer() - Becomes the current buffer. Cannot be undone. */
struct buffer_str *
create_buffer(int type, int verbose, char *success, int initial_undo_command) {
struct editor_config *old_E = E;
//struct command_str *c = command_get_by_key(COMMAND_CREATE_BUFFER);
struct buffer_str *p = malloc(sizeof(struct buffer_str));
if (p == NULL)
die("new buffer");
p->type = type;
p->undo_stack = init_undo_stack(initial_undo_command);
p->prev = NULL;
p->next = NULL;
init_config(&p->E);
if (current_buffer != NULL) {
while (current_buffer->next != NULL)
current_buffer = current_buffer->next;
current_buffer->next = p;
p->prev = current_buffer;
current_buffer = p;
if (verbose)
editor_set_status_message(success);
} else {
// This is a call to init_buffer();
current_buffer = p;
}
E = ¤t_buffer->E;
if (old_E != NULL)
E->debug = old_E->debug;
return current_buffer;
}
/** to command.c */
void
command_next_buffer() {
if (current_buffer->next != NULL) {
struct command_str *c = command_get_by_key(COMMAND_NEXT_BUFFER);
current_buffer = current_buffer->next;
E = ¤t_buffer->E;
editor_scroll();
undo_push_simple(COMMAND_NEXT_BUFFER, COMMAND_PREVIOUS_BUFFER);
if (c != NULL)
editor_set_status_message(c->success);
}
}
void
command_previous_buffer() {
if (current_buffer->prev != NULL) {
struct command_str *c = command_get_by_key(COMMAND_PREVIOUS_BUFFER);
current_buffer = current_buffer->prev;
E = ¤t_buffer->E;
editor_scroll();
undo_push_simple(COMMAND_PREVIOUS_BUFFER, COMMAND_NEXT_BUFFER);
if (c != NULL)
editor_set_status_message(c->success);
}
}
/* Cannot be undone.*/
void
delete_current_buffer() {
struct buffer_str *new_current = NULL;
struct undo_str *u = NULL;
struct undo_str *n = NULL;
struct command_str *c = command_get_by_key(COMMAND_DELETE_BUFFER);
if (current_buffer == NULL)
return;
if (current_buffer->prev == NULL && current_buffer->next == NULL) {
editor_set_status_message("Only buffer -- cannot be deleted.");
return; // Cannot delete the only buffer.
}
// Not so fast: are there any unsaved changes?
// Ok, this is a quick and dirty solution for this buffer only.
if (E->dirty) {
editor_set_status_message(c->error_status);
return;
}
// Free undo_stack.
u = current_buffer->undo_stack;
while (u != NULL) {
if (u->clipboard != NULL) { /* clipboard */
if (u->clipboard->row != NULL) {
int i = 0;
for (i = 0; i < u->clipboard->numrows; i++) {
struct clipboard_row *r = &u->clipboard->row[i];
if (r->row != NULL)
free(r->row);
}
free(u->clipboard->row); // clipboard_row * (a realloc'd chunk)
}
free(u->clipboard);
}
n = u->next;
free(u);
u = n;
}
if (current_buffer->prev != NULL) {
current_buffer->prev->next = current_buffer->next;
new_current = current_buffer->prev; /* Prev has priority. */
}
if (current_buffer->next != NULL) {
current_buffer->next->prev = current_buffer->prev;
if (new_current == NULL) /* If no prev the set current to next. */
new_current = current_buffer->next;
}
if (new_current == NULL)
die("new current");
free(current_buffer);
current_buffer = new_current;
E = ¤t_buffer->E;
editor_set_status_message(c->success);
}
<file_sep>#ifndef FILETYPES_H
#define FILETYPES_H
/**
filetypes.h
*/
int hldb_entries();
#endif
<file_sep># kilo
kilo is a simple text editor that understands ascii.
It is based on the kilo project (https://github.com/antirez/kilo):
Copyright (c) 2016, <NAME> <antirez at gmail dot com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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.
# Basic Commands:
Ctrl-Q quit
Ctrl-F find
Ctrl-S save
Ctrl-K kill/copy full line to clipboard
Ctrl-Y yank clipboard
Ctrl-SPC set mark
Ctrl-W kill region from mark to clipboard
Esc-W copy region from mark to clipboard
Ctrl-U undo last command
Ctrl-G goto line
Ctrl-O open file
Ctrl-N new buffer
Esc-N next buffer
Esc-P previous buffer
Ctrl-L refresh screen (center to cursor row)
Esc-C clear the modification flag
Esc-X <command> (see below)
# Movement:
Arrow keys
Page Down/Ctrl-V Page Down
Page Up/Esc-V Page Up
Home/Ctrl-A Beginning of line
End/Ctrl-E End of line
Esc-A Beginning of file
Esc-E End of file
# Commands:
Esc-X <command>, where <command> is one of the following:
set-tab-stop, set-auto-indent, set-hard-tabs, set-soft-tabs,
save-buffer-as, open-file, undo, set-mode, goto-line
create-buffer, next-buffer, previous-buffer, delete-buffer
mark, copy-region, kill-region, insert-char, delete-char
goto-beginning, goto-end, refresh
The supported higlighted file modes are (M-x set-mode <mode>):
Awk, Bazel, C, Chapel, C#, Docker, Elm, Erlang, Go, Groovy, Java, JavaScript,
Kotlin, Lua, Makefile, nginx, Perl, PHP, Python, R, Ruby, Scala, Shell, SQL & Text.
Usage: kilo [--help|-h|--version|-v|--debug level|-d|-ascii|-a] [--] [file] [file] ...
--ascii or -a allows only for ascii characters.
<file_sep>#ifndef FIND_H
#define FIND_H
/**
find.h
*/
void editor_find_callback(char *query, int key);
void editor_find();
char *editor_prompt(char *prompt, void (*callback) (char *, int));
#endif
<file_sep>#include "token.h"
#include <string.h>
#include <ctype.h>
/**
* token.c
*
*/
/*** row operations ***/
/*
is_indent(row, triggers)
Note: Erlang's "->" is reduced to ">"
row the row the cursor is on
triggers char[] of single triggers eg, ">" or ":" or "}"
*/
int
is_indent(char *row, char *triggers, int line_len) {
int i;
unsigned int j;
if (row == NULL || triggers == NULL || strlen(triggers) == 0)
return 0;
for (i = line_len-1; i >= 0; i--) {
/* Check if the char in row belongs to trigger chars. */
for (j = 0; j < strlen(triggers); j++) {
if (row[i] == triggers[j])
return 1;
}
/* Not a trigger char. Continue only if white space. */
if (!isspace(row[i])) {
return 0;
}
}
return 0;
}
int
is_whitespace_between(char *start, char *p) {
while (start < p && isspace(*start))
start++;
return start == p;
}
/* */
int
is_whitespace_to_end(char *p) {
while (isspace(*p))
p++;
return *p == '\0';
}
/**
* Fails with ^(WHITESPACE*)<< comment >>(WHITESPACE*)token
*/
int
is_first_token(char *row, char *token) {
if (row == NULL || token == NULL)
return 0;
char *p = strstr(row, token);
if (p == NULL)
return 0;
char *start = row;
while (start < p && isspace(*start))
start++;
return start == p;
}
int
is_last_token(char *row, char *token) {
if (row == NULL || token == NULL)
return 0;
char *p = strstr(row, token);
if (p == NULL)
return 0;
p += strlen(token);
return is_whitespace_to_end(p);
}
<file_sep>#include "options.h"
#include "help.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* options.h
*/
/**
*
* Side effects: 1/ *index points to the next argument to be preocessed
* after the function call; The contents of the list may be updated.
*
* return 0 if there was a match
*/
int
options_find(int argc, char **argv, Option *list, int *index) {
char *p = argv[*index];
while (*p && *p == '-')
p++;
Option *opt = list;
do {
if (strcmp(opt->short_option, p) == 0
|| strcmp(opt->long_option, p) == 0) {
if (opt->type == OPTION_TYPE_NO_OPTION) {
opt->is_set = 1;
return OPTION_FOUND;
}
if (opt->type == OPTION_TYPE_STRING
|| opt->type == OPTION_TYPE_NUMERIC) {
if (*index < argc - 1) {
*index = *index + 1;
if (opt->type == OPTION_TYPE_STRING) {
opt->value.string = strdup(argv[*index]);
} else {
// TODO ERROR HANDLING
opt->value.numeric = atoi(argv[*index]);
}
opt->is_set = 1;
return OPTION_FOUND;
}
return OPTION_MISSING_ARGUMENT;
}
}
opt = opt->next;
} while (opt != NULL);
//
return OPTION_UNKNOWN_OPTION;
}
Option *
options_parse(int argc, char **argv, char *options, int *next) {
/* There are no command line arguments to process. */
if (argc == 1) {
*next = 1;
return NULL;
}
if (options == NULL || strlen(options) == 0) {
if (argc > 1) {
/* Gobble '--'. */
if (! strcmp(argv[1], "--")) {
*next = 2;
return NULL;
}
}
/* argc == 1, nothing to process. */
*next = 1;
return NULL;
}
// char *options is a comma-separated list of options.
Option *list = NULL;
char *options_copy = strdup(options);
char *token = strtok(options_copy, ",");
while (token != NULL) {
char *long_option = NULL;
char *short_option = NULL;
enum option_type type = OPTION_TYPE_NO_OPTION;
// parse 'long|short[:i|s]'
char *p = token;
while (p && *p && *p != '|')
p++;
// Can long_option length == 1?
long_option = strndup(token, p-token);
if (!*p) {
*next = -1; // TODO BAD ERROR MECH.
free(options_copy);
return NULL;
}
p++;
char *start_of_s = p;
while (*p && *p != ':')
p++;
short_option = strndup(start_of_s, p-start_of_s);
if (*p == ':' && *(p+1)) {
p++;
if (*p == 'i') {
type = OPTION_TYPE_NUMERIC;
} else if (*p == 's') {
type = OPTION_TYPE_STRING;
} else {
*next = -1; // TODO BAD ERROR MECH.
free(options_copy);
return NULL;
}
}
Option *opt = malloc(sizeof (Option));
opt->long_option = long_option;
opt->short_option = short_option;
opt->type = type;
opt->is_set = 0;
opt->next = NULL;
if (list == NULL) {
list = opt;
} else {
opt->next = list->next;
list->next = opt;
}
token = strtok(NULL, ",");
}
free(options_copy);
// Finally, parse arguments.
// Store the argument to the same list: Option.value.
// Remove unused options, allow only one value per option.
// Barf and die is there is an unknown option. Or call for help.
int parsed = 0;
int i = 1;
do {
/* No dealing with '-'. */
if (! strcmp(argv[i], "-")) {
printf("Unknown option - (STDIN read not yet implemented).\r\n\r\n");
display_help();
exit(1);
}
/* '--' ends option parsing. */
if (! strcmp(argv[i], "--")) {
// No more options. Advance next.
parsed = 1;
i++;
} else {
// TODO How to deduce that the argument is actually a file?
// We have to backtrack, ie --i so that the file gets opened.
// If -- is optional, then files starting with - or -- can't
// be recognized unless prepended by './'.
if (strlen(argv[i]) >= 1 && argv[i][0] == '-') {
/* We don't deal with a single '-', so no STDIN read yet
(when forth is added then we can manipulate text like sed?)
i = last processed index
*/
int rc = options_find(argc, argv, list, &i);
if (rc == OPTION_UNKNOWN_OPTION) {
printf("Unknown option: %s.\r\n\r\n",
argv[i]);
display_help();
exit(1);
} else if (rc == OPTION_INVALID_ARGUMENT) {
printf("Invalid argument to option %s: '%s'\r\n\r\n",
argv[i-1], argv[i]);
display_help();
exit(1);
} else if (rc == OPTION_MISSING_ARGUMENT) {
printf("Missing argument for option %s\r\n\r\n",
argv[i]);
display_help();
exit(1);
}
i++;
// Ok. go on.
} else {
// The argument does not start with -, so end parsing.
parsed = 1;
}
}
} while (i < argc && ! parsed);
/* int *next points to the next index in argv after the command
* options have been processed. Note: if *next == argc then there
* are not files (=command line arguments) to process.
*
* In other words:
* The i++ expression at the end of the do-while loop makes sure
* that next is the next unparsed command line argument (or == argc,
* in which case nothing to process.)
*/
*next = i;
//options_remove_unused(list);
return list;
}
<file_sep>#include "help.h"
#include <stdio.h>
void
display_help() {
printf(KILO_VERSION);
printf(KILO_HELP);
}
<file_sep>#include "key.h"
/* Defined in config.h */
extern struct editor_config *E;
/** key_read() */
int
key_read() {
int nread;
char c;
while ((nread = read(STDIN_FILENO, &c, 1)) != 1) {
if (nread == -1 && errno != EAGAIN) die("read");
}
if (c == '\x1b') {
char seq[3];
if (read(STDIN_FILENO, &seq[0], 1) != 1) return c; //'\x1b'; /* vy!c?*/
if (seq[0] == 'v' || seq[0] == 'V') {
return PAGE_UP;
} else if (seq[0] == 'c' || seq[0] == 'C') {
return CLEAR_MODIFICATION_FLAG_KEY;
} else if (seq[0] == 'x' || seq[0] == 'X') {
return COMMAND_KEY;
} else if (seq[0] == 'n' || seq[0] == 'N') {
return NEXT_BUFFER_KEY;
} else if (seq[0] == 'p' || seq[0] == 'P') {
return PREVIOUS_BUFFER_KEY;
} else if (seq[0] == 'w' || seq[0] == 'W') {
return COPY_REGION_KEY;
} else if (seq[0] == 'a' || seq[0] == 'A') {
return GOTO_BEGINNING_OF_FILE_KEY;
} else if (seq[0] == 'e' || seq[0] == 'E') {
return GOTO_END_OF_FILE_KEY;
}
if (read(STDIN_FILENO, &seq[1], 1) != 1) return c; //'\x1b'; /*ditto*/
if (seq[0] == '[') {
if (seq[1] >= '0' && seq[1] <= '9') {
if (read(STDIN_FILENO, &seq[2], 1) != 1) return c;
if (seq[2] == '~') { // <esc>5~ and <esc>6~
switch (seq[1]) {
case '1': return HOME_KEY;
case '3': return DEL_KEY;
case '4': return END_KEY;
case '5': return PAGE_UP;
case '6': return PAGE_DOWN;
case '7': return HOME_KEY;
case '8': return END_KEY;
}
}
} else {
switch (seq[1]) {
case 'A': return ARROW_UP;
case 'B': return ARROW_DOWN;
case 'C': return ARROW_RIGHT;
case 'D': return ARROW_LEFT;
case 'H': return HOME_KEY;
case 'F': return END_KEY;
}
}
} else if (seq[0] == 'O') {
switch (seq[1]) {
case 'H': return HOME_KEY;
case 'F': return END_KEY;
}
}
}
return c;
}
/**
*/
int
key_normalize(int c) {
if (c == CTRL_KEY('v'))
c = PAGE_DOWN;
else if (c == CTRL_KEY('y'))
c = YANK_KEY;
else if (c == CTRL_KEY('k'))
c = KILL_LINE_KEY;
else if (c == CTRL_KEY('e'))
c = END_KEY;
else if (c == CTRL_KEY('a'))
c = HOME_KEY;
else if (c == CTRL_KEY('q'))
c = QUIT_KEY;
else if (c == CTRL_KEY('s'))
c = SAVE_KEY;
else if (c == CTRL_KEY('f'))
c = FIND_KEY;
else if (c == CTRL_KEY('u'))
c = COMMAND_UNDO_KEY;
else if (c == CTRL_KEY('g'))
c = GOTO_LINE_KEY;
else if (c == CTRL_KEY(' '))
c = MARK_KEY;
else if (c == CTRL_KEY('w'))
c = KILL_REGION_KEY; // M-W = COPY_REGION_KEY
else if (c == CTRL_KEY('l'))
c = REFRESH_KEY;
else if (c == CTRL_KEY('n'))
c = NEW_BUFFER_KEY;
else if (c == CTRL_KEY('o'))
c = OPEN_FILE_KEY;
return c;
}
void
key_move_cursor(int key) {
int rowlen;
erow *row = (E->cy >= E->numrows) ? NULL : &E->row[E->cy];
switch (key) {
case ARROW_LEFT:
if (E->cx != 0) {
E->cx--;
if (E->coloff > 0)
E->coloff--;
} else if (E->cy > 0) {
E->cy--;
E->cx = E->row[E->cy].size;
}
break;
case ARROW_RIGHT:
//if (E.cx != E.screencols - 1)
if (row && E->cx < row->size) {
E->cx++;
} else if (row && E->cx == row->size) {
E->cy++;
E->cx = 0;
}
break;
case ARROW_UP:
if (E->cy != 0) {
E->cy--;
if (E->cx > E->row[E->cy].size) {
E->cx = E->row[E->cy].size;
E->coloff = 0;
}
}
break;
case ARROW_DOWN:
if (E->cy < E->numrows) {
E->cy++;
if (E->cx > E->row[E->cy].size) {
E->cx = E->row[E->cy].size;
E->coloff = 0;
}
}
break;
default:
break;
}
row = (E->cy >= E->numrows) ? NULL : &E->row[E->cy];
rowlen = row ? row->size : 0;
if (E->cx > rowlen) {
E->cx = rowlen;
}
}
<file_sep>
#include "output.h"
void
ab_append(struct abuf *ab, const char *s, int len) {
char *new = realloc(ab->b, ab->len + len);
if (new == NULL)
return;
memcpy(&new[ab->len], s, len); /* ! */
ab->b = new;
ab->len += len;
}
void
ab_free(struct abuf *ab) {
free(ab->b);
}
void
editor_scroll() {
E->rx = 0;
if (E->cy < E->numrows)
E->rx = editor_row_cx_to_rx(&E->row[E->cy], E->cx);
if (E->cy < E->rowoff)
E->rowoff = E->cy;
if (E->cy >= E->rowoff + TERMINAL.screenrows)
E->rowoff = E->cy - TERMINAL.screenrows + 1;
if (E->rx < E->coloff)
E->coloff = E->rx;
if (E->rx >= E->coloff + TERMINAL.screencols)
E->coloff = E->rx - TERMINAL.screencols + 1;
}
void
editor_draw_rows(struct abuf *ab) {
int y;
int filerow;
for (y = 0; y < TERMINAL.screenrows; y++) {
filerow = y + E->rowoff;
if (filerow >= E->numrows) {
if (!E->is_banner_shown && E->numrows == 0 && y == TERMINAL.screenrows / 3) {
int padding = 0;
char welcome[80];
int welcomelen = snprintf(welcome, sizeof(welcome),
"%s", KILO_VERSION);
if (welcomelen > TERMINAL.screencols)
welcomelen = TERMINAL.screencols;
padding = (TERMINAL.screencols - welcomelen) / 2;
if (padding) {
ab_append(ab, "~", 1);
padding--;
}
while (padding--)
ab_append(ab, " ", 1);
ab_append(ab, welcome, welcomelen);
} else { // / 3
ab_append(ab, "~", 1);
}
} else {
char *c;
unsigned char *hl;
int j;
int current_colour = -1;
int len = E->row[filerow].rsize - E->coloff;
if (len < 0)
len = 0;
if (len > TERMINAL.screencols)
len = TERMINAL.screencols;
c = &E->row[filerow].render[E->coloff];
hl = &E->row[filerow].hl[E->coloff];
for (j = 0; j < len; j++) {
if (iscntrl(c[j])) {
char sym = (c[j] <= 26) ? '@' + c[j] : '?';
ab_append(ab, "\x1b[7m", 4);
ab_append(ab, &sym, 1);
ab_append(ab, "\x1b[m", 3);
if (current_colour != -1) {
char buf[16];
int clen = snprintf(buf, sizeof(buf), "\x1b[%dm", current_colour);
ab_append(ab, buf, clen);
}
} else if (hl[j] == HL_NORMAL) {
if (current_colour != -1) {
ab_append(ab, "\x1b[39m", 5); /* Text colours 30-37 (0=blak, 1=ref,..., 7=white. 9=reset*/
current_colour = -1;
}
ab_append(ab, &c[j], 1);
} else {
int colour = syntax_to_colour(hl[j]);
if (colour != current_colour) {
char buf[16];
int clen = snprintf(buf, sizeof(buf), "\x1b[%dm", colour);
ab_append(ab, buf, clen);
current_colour = colour;
}
ab_append(ab, &c[j], 1);
}
}
ab_append(ab, "\x1b[39m", 5); /* Final reset. */
}
ab_append(ab, "\x1b[K", 3); /* K = erase line */
ab_append(ab, "\r\n", 2);
}
}
#define ESC_PREFIX "\x1b["
#define ESC_PREFIX_LEN 2
#define APPEND_ESC_PREFIX(ab) (ab_append(ab, ESC_PREFIX, ESC_PREFIX_LEN))
enum esc_codes {
ESC_BOLD = 1,
ESC_DIM = 2,
ESC_UNDERLINED = 4,
ESC_BLINK = 5,
ESC_REVERSE = 7,
ESC_HIDDEN = 8,
ESC_RESET_ALL = 0,
ESC_RESET_BOLD = 21,
ESC_RESET_DIM = 22,
ESC_RESET_UNDERLINED = 24,
ESC_RESET_BLINK = 25,
ESC_RESET_REVERSE = 27,
ESC_RESET_HIDDEN = 28
};
void
esc_invert(struct abuf *ab) {
APPEND_ESC_PREFIX(ab);
ab_append(ab, "7m", 2);
}
void
esc_bold(struct abuf *ab) {
APPEND_ESC_PREFIX(ab);
ab_append(ab, "1m", 2);
}
void
esc_reset_all(struct abuf *ab) {
APPEND_ESC_PREFIX(ab);
ab_append(ab, "0m", 2);
}
void
editor_draw_status_bar(struct abuf *ab) {
int len = 0;
int rlen = 0;
char status[80], rstatus[80];
//ab_append(ab, "\x1b[7m", 4);
esc_invert(ab);
//len = snprintf(status, sizeof(status), "-- %.48s %s - %d lines %s",
len = snprintf(status, sizeof(status), "-- %.48s %s %s",
E->basename ? E->basename : "[No name]",
E->is_new_file ? "(New file)" : "",
// E->numrows,
E->dirty ? "(modified)" : "");
rlen = snprintf(rstatus, sizeof(rstatus), "%s | %d/%d",
E->syntax != NULL ? E->syntax->filetype : "no ft", E->cy + 1, E->numrows);
if (len > TERMINAL.screencols)
len = TERMINAL.screencols;
ab_append(ab, status, len);
while (len < TERMINAL.screencols) {
if (TERMINAL.screencols - len == rlen) {
ab_append(ab, rstatus, rlen);
break;
} else {
ab_append(ab, " ", 1);
len++;
}
}
esc_reset_all(ab);
//ab_append(ab, "\x1b[m", 3);
ab_append(ab, "\r\n", 2);
}
void
debug_cursor() {
char cursor[80];
snprintf(cursor, sizeof(cursor), "cx=%d rx=%d cy=%d len=%d coloff=%d screencols=%d",
E->cx, E->rx, E->cy, E->row[E->cy].size, E->coloff, TERMINAL.screencols);
editor_set_status_message(cursor);
}
void
editor_draw_message_bar(struct abuf *ab) {
int msglen;
ab_append(ab, "\x1b[K", 3);
if (E->debug & DEBUG_CURSOR) {
debug_cursor();
}
msglen = strlen(E->statusmsg);
if (msglen > TERMINAL.screencols)
msglen = TERMINAL.screencols;
if (msglen && time(NULL) - E->statusmsg_time < 5)
ab_append(ab, E->statusmsg, msglen);
}
/**
The first byte is \x1b, which is the escape character,
or 27 in decimal. (Try and remember \x1b, we will be using it a lot.)
The other three bytes are [2J.
We are writing an escape sequence to the terminal.
Escape sequences always start with an escape character (27)
followed by a [ character.
Escape sequences instruct the terminal to do various text
formatting tasks, such as coloring text, moving the cursor around,
and clearing parts of the screen.
We are using the J command (Erase In Display) to clear the screen.
Escape sequence commands take arguments, which come before the command.
In this case the argument is 2, which says to clear the entire screen.
<esc>[1J would clear the screen up to where the cursor is,
and <esc>[0J would clear the screen from the cursor up to the end of the screen.
Also, 0 is the default argument for J, so just <esc>[J by itself would also clear
the screen from the cursor to the end.
*/
void
editor_refresh_screen() {
char buf[32];
struct abuf ab = ABUF_INIT;
editor_scroll();
ab_append(&ab, "\x1b[?25l", 6); /* cursor off (l = reset mode) */
ab_append(&ab, "\x1b[H", 3);
editor_draw_rows(&ab);
editor_draw_status_bar(&ab);
editor_draw_message_bar(&ab);
snprintf(buf, sizeof(buf), "\x1b[%d;%dH",
(E->cy - E->rowoff) + 1, (E->rx + E->coloff) + 1);
ab_append(&ab, buf, strlen(buf));
ab_append(&ab, "\x1b[?25h", 6); /* cursor on (h = set mode) */
write(STDOUT_FILENO, ab.b, ab.len);
ab_free(&ab);
}
void
editor_set_status_message(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vsnprintf(E->statusmsg, sizeof(E->statusmsg), fmt, ap);
va_end(ap);
E->statusmsg_time = time(NULL);
}
<file_sep>#include "init.h"
void
init_config(struct editor_config *cfg) {
cfg->cx = 0;
cfg->cy = 0;
cfg->rx = 0;
cfg->numrows = 0;
cfg->rowoff = 0;
cfg->coloff = 0;
cfg->dirty = 0;
cfg->row = NULL;
cfg->filename = NULL;
cfg->absolute_filename = NULL;
cfg->basename = NULL;
cfg->statusmsg[0] = '\0';
cfg->statusmsg_time = 0;
cfg->syntax = NULL;
cfg->is_new_file = 0;
cfg->is_banner_shown = 0;
cfg->tab_stop = DEFAULT_KILO_TAB_STOP;
cfg->is_soft_indent = 0;
cfg->is_auto_indent = 0;
cfg->debug = 0;
cfg->mark_x = -1;
cfg->mark_y = -1;
}
/*
void
init_buffer(int init_command_key) {
buffer = create_buffer(BUFFER_TYPE_FILE, 0, init_command_key); // FIXME -- get rid of init_buffer()
}
*/
void
init_editor() {
//init_buffer(); // Side effect: sets E.
init_clipboard(); // C
/* XXX TODO Need global terminal settings for new buffer config initialization. */
if (get_window_size(&TERMINAL.screenrows, &TERMINAL.screencols) == -1)
die("get_window_size");
/* TODO BACK TO current_buffer->E at some point as E will be tied to a buffer, TERMINAL is global */
TERMINAL.screenrows -= 2; /* Room for the status bar & status messages. */
}
void
init_clipboard() {
clipboard_clear();
}
<file_sep>#include "terminal.h"
/**
terminal.c
*/
void
die(const char *s) {
/* Clear the screen. */
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
perror(s);
exit(1);
}
void
disable_raw_mode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &TERMINAL.orig_termios) == -1)
die("tcsetattr");
}
void
enable_raw_mode() {
struct termios raw;
if (tcgetattr(STDIN_FILENO, &TERMINAL.orig_termios) == -1)
die("tcgetattr");
atexit(disable_raw_mode);
raw = TERMINAL.orig_termios;
/* c_lflags are local flags. */
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 4; /* 4 = 400ms so we can catch <esc>-<key> better. */
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
die ("tcsetattr");
}
int
get_cursor_position(int *rows, int *cols) {
char buf[32];
unsigned int i = 0;
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4)
return -1;
/*
The reply is an escape sequence! It’s an escape character (27),
followed by a [ character, and then the actual response: 24;80R,
or similar.
We’re going to have to parse this response. But first, let’s read
it into a buffer. We’ll keep reading characters until we get to
the R character.
*/
while (i < sizeof(buf) - 1) {
if (read(STDIN_FILENO, &buf[i], 1) != 1) break;
if (buf[i] == 'R') break;
i++;
}
/*
When we print out the buffer, we don’t want to print the '\x1b' character,
because the terminal would interpret it as an escape sequence and wouldn’t
display it. So we skip the first character in buf by passing &buf[1] to
printf().
*/
buf[i] = '\0';
if (buf[0] != '\x1b' || buf[1] != '[')
return -1;
if (sscanf(&buf[2], "%d;%d", rows, cols) != 2)
return -1;
return 0;
}
int
get_window_size(int *rows, int *cols) {
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12)
return -1;
return get_cursor_position(rows, cols);
} else {
*cols = ws.ws_col;
*rows = ws.ws_row;
return 0;
}
}
<file_sep>#ifndef TERMINAL_H
#define TERMINAL_H
/**
terminal.h
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <termios.h>
/* Global terminal information. Separated from editor_config which is tied to buffer. */
struct term_config {
int screenrows;
int screencols;
struct termios orig_termios;
};
struct term_config TERMINAL;
void die(const char *s);
void disable_raw_mode();
void enable_raw_mode();
int get_cursor_position(int *rows, int *cols);
int get_window_size(int *rows, int *cols);
#endif
<file_sep>#ifndef ROW_H
#define ROW_H
#include <ctype.h>
#include "data.h"
#include "syntax.h"
/**
row.h
A row of text.
TODO Implement a more efficient data structure.
*/
int editor_row_cx_to_rx(erow *row, int cx);
int editor_row_rx_to_cx(erow *row, int rx);
void editor_update_row(erow *row);
void editor_insert_row(int at, char *s, size_t len);
void editor_free_row(erow *row);
void editor_del_row(int at);
int editor_row_insert_char(erow *row, int at, char c);
void editor_row_append_string(erow *row, char *s, size_t len);
int editor_row_del_char(erow *row, int at);
/** editor operations, maybe an own source file? */
void editor_insert_char(int c);
int calculate_indent(erow *row);
int editor_insert_newline();
void editor_del_char(int undo); /** XXX command delete char */
#endif
<file_sep>#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "row.h"
#include "output.h"
#include "token.h"
extern struct editor_config *E;
/*** row operations ***/
#if 0
/*
is_indent(row, triggers)
Note: Erlang's "->" is reduced to ">"
row the row the cursor is on
triggers char[] of single triggers eg, ">" or ":" or "}"
*/
int
is_indent(erow *row, char *triggers) {
int i;
unsigned int j;
if (row == NULL || triggers == NULL || strlen(triggers) == 0)
return 0;
for (i = E->cx-1; i >= 0; i--) {
/* Check if the char in row belongs to trigger chars. */
for (j = 0; j < strlen(triggers); j++) {
if (row->chars[i] == triggers[j])
return 1;
}
/* Not a trigger char. Continue only if white space. */
if (!isspace(row->chars[i])) {
return 0;
}
}
return 0;
}
/*
* [start, p[
*
* return 1 is only whitespace between start and p-1, 0 otherwise.
*/
int
is_whitespace_between(char *start, char *p) {
while (start < p && isspace(*start))
start++;
return start == p;
}
/* */
int
is_whitespace_to_end(char *p) {
while (isspace(*p))
p++;
return *p == '\0';
}
/**
* Fails with ^(WHITESPACE*)<< comment >>(WHITESPACE*)token
*/
int
is_first_token(erow *row, char *token) {
if (row == NULL || row->chars == NULL || token == NULL)
return 0;
char *p = strstr(row->chars, token);
if (p == NULL)
return 0;
char *start = row->chars;
while (start < p && isspace(*start))
start++;
return start == p;
}
int
is_last_token(erow *row, char *token) {
if (row == NULL || row->chars == NULL || token == NULL)
return 0;
char *p = strstr(row->chars, token);
if (p == NULL)
return 0;
p += strlen(token);
return is_whitespace_to_end(p);
}
#endif
int
editor_row_cx_to_rx(erow *row, int cx) {
int rx = 0;
int j;
for (j = 0; j < cx; j++) {
if (row->chars[j] == '\t')
rx += (E->tab_stop - 1) - (rx % E->tab_stop);
rx++;
}
return rx;
}
int
editor_row_rx_to_cx(erow *row, int rx) {
int cur_rx = 0;
int cx;
for (cx = 0; cx < row->size; cx++) {
if (row->chars[cx] == '\t')
cur_rx = (E->tab_stop - 1) - (cur_rx % E->tab_stop);
cur_rx++;
if (cur_rx > rx)
return cx;
}
return cx;
}
void
editor_update_row(erow *row) {
int j;
int idx = 0;
int tabs = 0;
for (j = 0; j < row->size; j++) { // There may always be tabs.
if (row->chars[j] == '\t')
tabs++;
}
free(row->render);
row->render = malloc(row->size + tabs * (E->tab_stop - 1) + 1);
for (j = 0; j < row->size; j++) {
if (row->chars[j] == '\t') {
row->render[idx++] = ' ';
while (idx % E->tab_stop != 0)
row->render[idx++] = ' ';
} else {
row->render[idx++] = row->chars[j];
}
}
row->render[idx] = '\0';
row->rsize = idx;
syntax_update(row);
}
void
editor_insert_row(int at, char *s, size_t len) {
int j;
if (at < 0 || at > E->numrows > 0)
return;
E->row = realloc(E->row, sizeof(erow) * (E->numrows + 1));
memmove(&E->row[at + 1], &E->row[at], sizeof(erow) * (E->numrows - at));
for (j = at + 1; j <= E->numrows; j++)
E->row[j].idx++;
E->row[at].idx = at;
E->row[at].size = len;
E->row[at].chars = malloc(len + 1);
memcpy(E->row[at].chars, s, len);
E->row[at].chars[len] = '\0';
E->row[at].rsize = 0;
E->row[at].render = NULL;
E->row[at].hl = NULL;
E->row[at].hl_open_comment = 0;
editor_update_row(&E->row[at]);
E->numrows++;
E->dirty++;
}
void
editor_free_row(erow *row) {
free(row->render);
free(row->chars);
free(row->hl);
}
void
editor_del_row(int at) {
int j;
if (at < 0 || at > E->numrows)
return;
editor_free_row(&E->row[at]);
memmove(&E->row[at], &E->row[at + 1], sizeof(erow) * (E->numrows - at - 1));
for (j = at; j < E->numrows - 1; j++)
E->row[j].idx--;
E->numrows--;
E->dirty++;
}
int
editor_row_insert_char(erow *row, int at, char c) {
int insert_len = 0;
int i = 0;
int no_of_spaces = 0;
if (at < 0 || at > row->size)
at = row->size;
if (c == '\t' && E->is_soft_indent) {
/*
* Calculate the number of spaces until the next tab stop.
* Add E.tab_stop number of spaces if we are at the stop.
*/
no_of_spaces = E->tab_stop - (at % E->tab_stop);
if (no_of_spaces == 0)
no_of_spaces = E->tab_stop;
insert_len = no_of_spaces;
c = ' '; /* Tabs to spaces; swords to plows. */
} else {
/* Not a tab char or hard tabs set. */
insert_len = 1;
}
row->chars = realloc(row->chars, row->size + insert_len + 1); /* plus 1 is \0 */
memmove(&row->chars[at + insert_len], &row->chars[at], row->size - at + 1);
for (i = 0; i < insert_len; i++) {
row->size++;
row->chars[at++] = c;
}
editor_update_row(row);
E->dirty++;
return insert_len;
}
void
editor_row_append_string(erow *row, char *s, size_t len) {
row->chars = realloc(row->chars, row->size + len + 1);
memcpy(&row->chars[row->size], s, len);
row->size += len;
row->chars[row->size] = '\0';
editor_update_row(row);
E->dirty++;
}
/**
* at = E.cx - 1
*/
int
editor_row_del_char(erow *row, int at) {
int len = 1; /* Default del len. */
int i = 0;
int enough_spaces_to_the_left = 1;
if (at < 0 || at >= row->size)
return 0;
if (E->is_auto_indent) {
if ((at+1) % E->tab_stop == 0) {
/* There has to be at least E.tab_stop spaces to the left of 'at'.
Note: start counting from TAB_STOP below & upwards. */
for (i = at + 1 - E->tab_stop; enough_spaces_to_the_left && i >= 0 && i < at; i++) {
if ((E->is_soft_indent && row->chars[i] != ' ')
|| (!E->is_soft_indent && row->chars[i] != '\t')) {
enough_spaces_to_the_left = 0;
}
}
if (enough_spaces_to_the_left)
len = E->tab_stop;
} else
enough_spaces_to_the_left = 0;
}
memmove(&row->chars[at + 1 - len], &row->chars[at + 1], row->size - at + 1);
row->size -= len;
editor_update_row(row);
E->dirty++;
return len;
}
/*** editor operations ***/
void
editor_insert_char(int c) {
if (E->cy == E->numrows) {
editor_insert_row(E->numrows, "", 0);
}
/* If soft_indent, we may insert more than one character. */
E->cx += editor_row_insert_char(&E->row[E->cy], E->cx, c);
}
/**
* @return 1 if mode matches; 0 otherwise
*/
int
is_mode(char *mode) {
if (! strcasecmp(E->syntax->filetype, mode))
return 1;
else
return 0;
}
/**
* If auto_indent is on then we calculate the number of indents.
* Here you can add language/mode specific indents.
*/
int
calculate_indent(erow *row) {
int iter = 0;
int no_of_chars_to_indent = 0;
int i = 0;
if (E->is_auto_indent) {
iter = 1;
// Cutoff point is cursor == E.cx
for (i = 0; iter && i < E->cx; i++) {
if ((row->chars[i] == ' ' && E->is_soft_indent)
|| (row->chars[i] == '\t' && !E->is_soft_indent)) {
no_of_chars_to_indent++;
} else {
iter = 0;
}
}
if (E->is_soft_indent
&& (no_of_chars_to_indent % E->tab_stop == 0)) {
if (is_mode("Python")) { /* Little extra for Python mode. */
no_of_chars_to_indent += is_indent(row->chars, ":\\", E->cx) * E->tab_stop;
} else if (is_mode("Erlang")) {
no_of_chars_to_indent += is_indent(row->chars, ">", E->cx) * E->tab_stop; // > not ->
} else if (is_mode("Elm")) {
no_of_chars_to_indent += is_indent(row->chars, "=", E->cx) * E->tab_stop;
} else if (is_mode("Bazel")) {
no_of_chars_to_indent += is_indent(row->chars, "([", E->cx) * E->tab_stop;
} else if (is_mode("nginx")
|| is_mode("Java")
|| is_mode("JavaScript")
|| is_mode("Scala")
|| is_mode("Groovy")
|| is_mode("R")
|| is_mode("go")
|| is_mode("Haxe")
|| is_mode("Awk")
|| is_mode("C")
|| is_mode("C#")) {
no_of_chars_to_indent += is_indent(row->chars, "{", E->cx) * E->tab_stop;
} else if (is_mode("Kotlin")) {
no_of_chars_to_indent += is_indent(row->chars, "{>", E->cx) * E->tab_stop;
// TODO add "->": change is_indent()'s 2nd arg as char ** ("}", "->")
} else if (is_mode("Lua")) {
// do, then, else, elseif and ) in a function row
if (is_last_token(row->chars, "do")
|| is_last_token(row->chars, "then")
|| is_last_token(row->chars, "else")
|| is_last_token(row->chars, "elseif")) {
// The last character of each keyword. A hack.
no_of_chars_to_indent += is_indent(row->chars, "onef", E->cx) * E->tab_stop;
} else if (is_first_token(row->chars, "function")) {
no_of_chars_to_indent += is_indent(row->chars, ")", E->cx) * E->tab_stop;
}
}
} else if (!E->is_soft_indent
&& ! strcasecmp(E->syntax->filetype, "Makefile")) {
// TODO like above
iter = 1;
for (i = 0; iter && i < E->cx; i++) {
if (row->chars[i] == ':') { // target: dep
no_of_chars_to_indent++;
iter = 0;
}
}
}
}
return no_of_chars_to_indent;
}
int
editor_insert_newline() {
int no_of_chars_to_indent = 0;
char *buf;
erow *row;
if (E->cx == 0) {
editor_insert_row(E->cy, "", 0);
no_of_chars_to_indent = 0;
} else {
row = &E->row[E->cy];
no_of_chars_to_indent = calculate_indent(row);
if (no_of_chars_to_indent > 0) {
/* # of new spaces + the end of row. */
buf = malloc(no_of_chars_to_indent + row->size - E->cx + 1);
if (no_of_chars_to_indent > 0) {
memset(buf, E->is_soft_indent ? ' ' : '\t', no_of_chars_to_indent);
}
memcpy(&buf[no_of_chars_to_indent], &row->chars[E->cx], row->size - E->cx);
buf[no_of_chars_to_indent + row->size - E->cx] = '\0';
editor_insert_row(E->cy + 1, buf, strlen(buf));
free(buf);
} else {
editor_insert_row(E->cy + 1, &row->chars[E->cx], row->size - E->cx);
}
// Update the split upper row.
row = &E->row[E->cy]; /* Reassign, because editor_insert_row() calls realloc(). */
row->size = E->cx;
row->chars[row->size] = '\0';
editor_update_row(row);
}
E->cy++;
E->cx = no_of_chars_to_indent; // was: = 0
return no_of_chars_to_indent;
}
<file_sep>CC=cc
OBJS = buffer.o clipboard.o command.o file.o filetypes.o find.o help.o \
init.o key.o kilo.o output.o row.o syntax.o terminal.o undo.o \
version.o options.o token.o
CFLAGS = -Wall -g
INCLUDES =
LIBS =
kilo:${OBJS}
${CC} ${CFLAGS} ${INCLUDES} -o $@ ${OBJS} ${LIBS}
clean:
-rm -f *.o core *.core
<file_sep>#ifndef TOKEN_H
#define TOKEN_H
/**
* is_indent
*
* return 1 is the line ends with (single chars) in triggers.
* There can be whitespace after trigger char.
*
* Return 0 otherwise (trigger chars don't end the row.)
*/
int is_indent(char *row, char *triggers, int line_len);
/*
* [start, p[
*
* return 1 is only whitespace between start and p-1, 0 otherwise.
*/
int is_whitespace_between(char *start, char *p);
int is_whitespace_to_end(char *p);
/**
* Fails with ^(WHITESPACE*)<< comment >>(WHITESPACE*)token
*
* Returns 1 is token is the first (whitespace separated) token
* in the row?
*
* Return 0 otherwise.
*/
int is_first_token(char *row, char *token);
/** Is token the last (whitespace separated) token in the row?
*
* Return 1 = yes; 0 = no
*/
int is_last_token(char *row, char *token);
#endif
<file_sep>#ifndef INIT_H
#define INIT_H
#include "const.h"
#include "data.h"
#include "terminal.h"
#include "syntax.h"
#include "clipboard.h"
#include "buffer.h"
//void init_buffer(int init_command_key);
void init_clipboard();
void init_editor();
void init_config(struct editor_config *cfg);
#endif
<file_sep>#include <stdio.h>
#include "const.h"
/**
version.c
*/
void
print_version() {
printf("%s\r\n", KILO_VERSION);
}
<file_sep>#ifndef KEY_H
#define KEY_H
/**
key.h
*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include "terminal.h"
#include "row.h"
/**
The CTRL_KEY macro bitwise-ANDs a character with the value 00011111, in binary.
In other words, it sets the upper 3 bits of the character to 0.
This mirrors what the Ctrl key does in the terminal: it strips the 6th and 7th
bits from whatever key you press in combination with Ctrl, and sends that.
The ASCII character set seems to be designed this way on purpose.
(It is also similarly designed so that you can set and clear the 6th bit
to switch between lowercase and uppercase.)
*/
#define CTRL_KEY(k) ((k) & 0x1f)
enum editor_key {
BACKSPACE = 127,
ARROW_LEFT = 1000,
ARROW_RIGHT,
ARROW_UP,
ARROW_DOWN,
DEL_KEY,
HOME_KEY, /* Ctrl-A */
END_KEY, /* Ctrl-E */
PAGE_UP, /* Esc-V */
PAGE_DOWN, /* Ctrl-V */
REFRESH_KEY, /* Ctrl-L TODO */
QUIT_KEY, // 1010, Ctrl-Q
SAVE_KEY, /* Ctrl-S */
FIND_KEY, /* Ctrl-F */
CLEAR_MODIFICATION_FLAG_KEY, /* M-c */
/* These are more like commands.*/
MARK_KEY, /* Ctrl-Space */
KILL_LINE_KEY, /* Ctrl-K (like nano) */
COPY_REGION_KEY, /* Esc-W */
KILL_REGION_KEY, /* Ctrl-W */
YANK_KEY, /* Ctrl-Y */
COMMAND_KEY, /* Esc-x */
COMMAND_UNDO_KEY, /* Ctrl-u */
COMMAND_INSERT_NEWLINE, /* 1022 Best undo for deleting newline (backspace in the beginning of row ...*/
ABORT_KEY, /* TODO NOT IMPLEMENTED */
GOTO_LINE_KEY, /* Ctrl-G */
NEXT_BUFFER_KEY, /* Esc-N */
PREVIOUS_BUFFER_KEY, /* Esc-P */
NEW_BUFFER_KEY, /* Ctrl-N */
OPEN_FILE_KEY, /* Ctrl-O */
GOTO_BEGINNING_OF_FILE_KEY, /* Esc-A */
GOTO_END_OF_FILE_KEY, /* Esc-E */
};
int key_read();
int key_normalize(int c);
void key_move_cursor(int key);
#endif
<file_sep>#ifndef CLIPBOARD_H
#define CLIPBOARD_H
#include "data.h"
#include "row.h"
#include "output.h"
/* row (E.row in phase 1; from E.cx' to E.cx'' in phase 2)
is_eol = the whole line (phase 1; also phase 2 with double Ctrl-K or C-' ' & C/M-w)
*/
typedef struct clipboard_row {
char *row;
int size;
int orig_x; /* TODO for emacs */
int orig_y; /* TODO for undo */
int is_eol;
} clipboard_row;
struct clipboard {
/*
Fill clipboard with successive KILL_KEY presses. After the first non-KILL_KEY set C.is_full = 1
as not to add anything more. The clipboard contents stay & can be yanked as many times as needed,
UNTIL the next KILL_KEY which clears clipboard and resets C.is_full to 0 if it was 1.
*/
int is_full;
int numrows;
clipboard_row *row;
};
//extern struct clipboard C; /* TODO static or extern in other source files? */
void clipboard_clear();
void clipboard_add_line_to_clipboard();
void clipboard_add_region_to_clipboard(int command); // FIXME get rid of "int command"
void clipboard_yank_lines(char *success);
struct clipboard *clone_clipboard();
void undo_clipboard_kill_lines(struct clipboard *copy);
// FIXME create proper command_*() functions to commands.c & rename these to clipboard_* (command_*s will call these).
void command_mark(char *success /*struct command_str *c*/); // FIX most definitely get rid of struct command_str *
void command_copy_from_mark();
void command_kill_from_mark();
#endif
<file_sep>#ifndef COMMAND_H
#define COMMAND_H
#include <stddef.h>
#include "const.h"
#include "key.h"
#include "undo.h"
#include "clipboard.h"
#include "buffer.h"
/**
* Everything is a command.
*/
enum command_key {
COMMAND_NO_CMD = 0,
COMMAND_SET_MODE = 1,
COMMAND_SET_TAB_STOP,
COMMAND_SET_SOFT_TABS,
COMMAND_SET_HARD_TABS,
COMMAND_SET_AUTO_INDENT,
COMMAND_SAVE_BUFFER,
COMMAND_SAVE_BUFFER_AS,
COMMAND_OPEN_FILE, // TODO
COMMAND_MOVE_CURSOR_UP,
COMMAND_MOVE_CURSOR_DOWN, // cmd_key = 10
COMMAND_MOVE_CURSOR_LEFT,
COMMAND_MOVE_CURSOR_RIGHT,
COMMAND_MOVE_TO_START_OF_LINE,
COMMAND_MOVE_TO_END_OF_LINE,
COMMAND_KILL_LINE,
COMMAND_YANK_CLIPBOARD,
COMMAND_UNDO,
COMMAND_INSERT_CHAR, /* for undo */
COMMAND_DELETE_CHAR, /* for undo */
COMMAND_DELETE_INDENT_AND_NEWLINE, /* for undo only */
COMMAND_GOTO_LINE,
COMMAND_GOTO_BEGINNING_OF_FILE,
COMMAND_GOTO_END_OF_FILE,
COMMAND_REFRESH_SCREEN, /* Ctrl-L */
COMMAND_CREATE_BUFFER,
COMMAND_SWITCH_BUFFER,
COMMAND_DELETE_BUFFER,
COMMAND_NEXT_BUFFER, /* Esc-N */
COMMAND_PREVIOUS_BUFFER, /* Esc-P */
COMMAND_MARK,
COMMAND_COPY_REGION,
COMMAND_KILL_REGION
};
enum command_arg_type {
COMMAND_ARG_TYPE_NONE = 0,
COMMAND_ARG_TYPE_INT,
COMMAND_ARG_TYPE_STRING
};
struct command_str {
int command_key;
char *command_str;
int command_arg_type;
char *prompt;
char *success;
char *error_status;
};
/** prototypes */
int command_entries();
void editor_del_char(int undo);
void editor_process_keypress();
void command_open_file(char *filename);
void editor_save(int command_key);
void command_debug(int command_key);
struct command_str *command_get_by_key(int command_key);
void command_insert_char(int character);
void command_delete_char();
void command_insert_newline();
int editor_get_command_argument(struct command_str *c, int *ret_int, char **ret_string);
void command_move_cursor(int command_key);
void command_goto_line();
void command_goto_beginning_of_file();
void command_goto_end_of_file();
void command_refresh_screen();
void exec_command();
#endif
<file_sep>/**
filetypes.c
*/
#include <stddef.h>
#include "const.h"
#include "syntax.h"
#include "highlight.h"
char *C_extensions[] = { ".c", ".h", ".cpp", NULL };
char *C_executables[] = { NULL };
char *C_HL_keywords[] = {
"auto", "break", "case", "const", "continue", "default", "do",
"else", "enum", "extern", "for", "goto", "if", "register",
"return", "signed", "sizeof", "static", "struct", "switch",
"typedef", "union", "unsigned", "volatile", "while",
/* C99 */
"restrict", "inline", "_Bool", "bool", "_Complex", "complex",
"_Imaginary", "imaginary", "_Pragma",
/* C11 */
"_Alignas", "alignas", "_Alignof", "alignof",
"_Atomic", "atomic_bool", "atomic_int",
"_Generic", "_Noreturn", "noreturn",
"_Static_assert", "static_assert",
"_Thread_local", "thread_local", /* C11 */
/* "asm", "fortran", */
/* Those C++(upto 11) keywords not in C(upto11). */
"and", "and_eq", "asm", "atomic_cancel", "atomic_commit",
"atomic_noexcept", "bitand", "bitor", "catch", "char16_t",
"char32_t", "class", "compl", "concept", "constexpr",
"const_cast", "decltype", "delete", "dynamic_cast", "explicit",
"export", "false", "friend", "import", "module", "mutable",
"namespace", "new", "noexcept", "not", "not_eq", "nullptr",
"operator", "or", "or_eq", "private", "protected", "public",
"register", "reinterpret_cast", "requires", "static_assert",
"static_cast", "synchronized", "template", "this", "throw",
"true", "try", "typeid", "typename", "using", "virtual",
"wchar_t", "xor", "xor_eq", /* C++ 11 */
/* cpp */
"#if", "#ifdef", "#ifndef",
"#elif", "#else", "#endif",
"#define", "#defined", "#undef",
"#include", "#pragma", "#line", "#error",
/* C types */
"int|", "long|", "double|", "float|", "char|", "unsigned|", "signed|", "void|",
NULL
};
char *Java_extensions[] = { ".java", NULL };
char *Java_HL_keywords[] = {
"abstract", "assert", "break", "case", "catch", "class", "const",
"continue", "default", "do", "else", "enum", "extends", "final",
"finally", "for", "goto", "if", "implements", "import", "instanceof",
"native", "new", "package", "private", "protected", "public", "return",
"static", "strictfp", "super", "switch", "synchronized", "this", "throw",
"transient", "try", "void", "volatile", "while", "false", "null", "true",
"boolean|", "byte|", "char|", "double|", "float|", "int|", "long|",
"Boolean|", "Byte|", "Character|", "Double|", "Float|", "Integer|", "Long|",
"short|", "Short|",
"@Deprecated", "@Override", "@SuppressWarnings", "@SafeVarargs",
"@FunctionalInterface", "@Retention", "@Documented", "@Target",
"@Inherited", "@Repeatable",
"@Test", // There will be more.
NULL
};
char *Python_extensions[] = { ".py", NULL };
char *Python_HL_keywords[] = {
"False", "None", "True",
"and", "as", "assert", "break", "class", "continue", "def", "del",
"elif", "else", "except", "finally", "for", "from", "global",
"if", "import", "in", "is", "lambda", "nonlocal", "not", "or",
"pass", "raise", "return", "try", "while", "with", "yield",
"int|", "float|", "complex|", "decimal|", "fraction|",
"container|", "iterator|", "list|", "tuple|", "range|",
"bytes|", "bytearray|",
"set|", "frozenset|",
"dict|",
NULL
};
char *Text_extensions[] = { ".txt", ".ini", ".cfg", ".properties", NULL };
char *Text_HL_keywords[] = { NULL };
char *Makefile_extensions[] = { "Makefile", "makefile", ".mk", ".mmk", NULL };
char *Makefile_HL_keywords[] = { NULL };
char *Erlang_extensions[] = { ".erl", NULL };
char *Erlang_HL_keywords[] = {
"after", "and", "andalso", "band", "begin", "bnot", "bor",
"bsl", "bsr", "bxor", "case", "catch", "cond", "div", "end",
"fun", "if", "let", "not", "of", "or", "orelse", "receive",
"rem", "try", "when", "xor",
"->", // can do?
"-module", "-export", "-import",
NULL
};
char *JS_extensions[] = { ".js", ".json", NULL };
char *JS_HL_keywords[] = {
"abstract", "arguments", "await",
"boolean|", "break", "byte|",
"case", "catch ", "char|", "class", "const", "continue",
"debugger", "default", "delete", "do", "double|",
"else", "enum", "eval", "export", "extends",
"false", "final", "finally", "float|", "for", "function",
"goto",
"if", "implements", "import", "in", "instanceof", "int|", "interface",
"let", "long|",
"native", "new", "null",
"package", "private", "protected", "public",
"return",
"short|", "static", "super", "switch", "synchronized",
"this", "throw", "throws", "transient", "true", "try", "typeof",
"var", "void|", "volatile",
"while", "with",
"yield",
/* And even more: JavaScript Object, Properties, and Methods. */
"Array|", "Date|", "hasOwnProperty",
"Infinity|", "isFinite", "isNaN", "isPrototypeOf",
"length", "Math", "NaN|", "name", "Number|", "Object|",
"prototype", "String|", "toString", "undefined", "valueOf",
/* Java reserved words. */
"getClass", "java", "JavaArray|", "javaClass", "JavaClass",
"JavaObject|", "JavaPackage",
/* Other reserved words. HTML and Window objects and properties. */
"alert", "all", "anchor", "anchors", "area", "assign",
"blur", "button",
"checkbox", "clearInterval", "clearTimeout", "clientInformation",
"close", "closed", "confirm", "constructor", "crypto",
"decodeURI", "decodeURIComponent", "defaultStatus", "document",
"element", "elements", "embed", "embeds", "encodeURI",
"encodeURIComponent", "escape", "event",
"fileUpload", "focus", "form", "forms", "frame", "frames", "frameRate",
"hidden", "history",
"image", "images", "innerHeight", "innerWidth",
"layer", "layers", "link", "location",
"mimeTypes",
"navigate", "navigator",
"offscreenBuffering", "open", "opener", "option", "outerHeight",
"outerWidth",
"packages", "pageXOffset", "pageYOffset", "parent", "parseFloat",
"parseInt", "password", "pkcs11", "plugin", "prompt", "propertyIsEnum",
"radio", "reset",
"screenX", "screenY", "scroll", "secure", "select", "self",
"setInterval", "setTimeout", "status", "submit",
"taint", "text", "textarea", "top", "unescape", "untaint",
"window",
/* HTML Event Handlers. */
"onblur", "onclick", "onerror", "onfocus", "onkeydown", "onkeyup",
"onmouseover", "onmouseup", "onmousedown", "onload", "onsubmit",
NULL
};
char *Shell_extensions[] = { ".sh", "profile", ".bash_profile", ".bashrc",
".bash_login", ".bash_logout", ".bash_history", ".history", ".login", ".logout",
"zshenv", "zprofile", "zshenv" "zshrc", "zlogin", "zlogout",
"csh.cshrc", "csh.login", ".cshrc", "csh.logout", ".tschrc",
".cshdirs",
NULL
};
char *Shell_executables[] = { "sh", "ash", "bash", "csh", "dash", "fish",
"hush", "ksh", "mksh", "pdksh", "tcsh", "zsh", NULL };
char *Shell_HL_keywords[] = {
// compgen -k
"if", "then", "else", "elif", "fi",
"case", "esac", "for", "select", "while", "until",
"do", "done", "in", "function", "time", "[[", "]]",
/* GNU test command/builtin (test and [ ]) test switches. */
"test",
"-a", /* AND: expr -a expr */
"-o", /* OR: expr -o expr */
"-n", /* nonzero length: -n string. Equivalent to (just) string */
"-z", /* zero length: -z string */
"-eq", /* integer -eq integer: == */
"-ge", /* integer -ge integer: >= */
"-gt", /* integer -gt integer: > */
"-le", /* integer -le integer: <= */
"-lt", /* integer -lt integer: < */
"-ne", /* integer -ne integer: != */
"-ef", /* file1 -eq file2: files have the same device and inode numbers */
"-nt", /* file1 -nt file2: file1 is newer than file2 (modification date) */
"-ot,", /* file1 -ot file2: file2 is older than file2 (modification date) */
"-b" /* -b file: file exists and is block special */
"-c", /* -c file: file exists and is character special */
"-d", /* -d file: file exists and is a directory */
"-e", /* -e file: file exists */
"-f", /* -f file: file exists and is a regular file */
"-g", /* -g file: file exists and is set-group-ID */
"-G", /* -G file: file exists and is owned by the effective group ID */
"-h", /* -h file: file exists and is a symbolic link: same as -L */
"-L", /* -F file: file exists and is a symbolic link: same as -h */
"-k", /* -k file: file exists and has its sticky bit set */
"-O", /* -O file: file exists and is owned by the effective user ID */
"-p", /* -p file: file exists and is a named pipe */
"-r", /* -r file: file exists is read permission is granted */
"-s", /* -s file: file exists and has a size greater than zero */
"-S", /* -S file: file exists and is a socket */
"-t", /* -t FD: file descriptor FD is opened on a terminal */
"-u", /* -u file: file exists and its set-user-ID bit is set */
"-w", /* -w file: file exists and write permission is granted */
"-x", /* -x file: file exists and execute (search) permission is granted */
NULL
};
char *Perl_extensions[] = { ".pl", ".perl", NULL };
char *Perl_HL_keywords[] = {
/* Perl functions. */
"-A", "-B", "-b", "-C", "-c", "-d", "-e", "-f", "-g", "-k", "-l", "-M", "-O", "-o",
"-p", "-r" "-R", "-S", "-s", "-T", "-t", "-u", "-w", "-W", "-X", "-x", "-z",
"abs", "accept", "alarm", "atan2", "AUTOLOAD",
"BEGIN", "bind", "binmode", "bless", "break",
"caller", "chdir", "CHECK", "chmod", "chomp", "chop", "chown", "chr", "chroot",
"close", "closedir", "connect", "cos", "crypt",
"dbmclose", "defined", "delete", "DESTROY", "die", "dump",
"each", "END", "endgrent", "endhostent", "endnetent", "endprotoent", "endpwent",
"endservent", "eof", "eval", "exec", "exists", "exit",
"fcntl", "fileno", "flock", "fork", "format", "formline",
"getc", "getgrent", "getgrgid", "getgrnam", "gethostbyaddr", "gethostbyname",
"gethostent", "getlogin", "getnetbyaddr", "getnetbyname", "getnetent",
"getpeername", "getpgrp", "getppid", "getpriority", "getprotobyname",
"getprotobynumber", "getprotoent", "getpwent", "getpwnam", "getpwuid",
"getservbyport", "getservent", "getsockname", "getsockopt", "glob", "gmtime",
"goto", "grep",
"hex",
"index",
"INIT", "int", "ioctl",
"join",
"keys", "kill",
"last", "lc", "lcfirst", "length", "link", "listen", "local", "localtime",
"log", "lstat",
"map", "mkdir", "msgctl", "msgget", "msgrcv", "msgsnd", "my",
"next", "not",
"oct", "open", "opendir", "ord", "our",
"pack", "pipe", "pop", "pos", "print", "printf", "prototype", "push",
"quotemeta",
"rand", "read", "readdir", "readline", "readlink", "readpipe", "recv",
"redo", "ref", "rename", "require", "reset", "return", "reverse", "rewinddir",
"rindex", "rmdir",
"say", "scalar", "seek", "seekdir", "select", "semctl", "semget", "semop",
"send", "setgrent", "sethostent", "setnetent", "setpgrp", "setpriority",
"setprotoent", "setpwent", "setservent", "setsockopt", "shift",
"shmctl", "shmget", "shmread", "shmwrite", "shutdown", "sin", "sleep",
"socket", "socketpair", "sort", "splice", "split", "sprintf", "sqrt", "srand",
"stat", "state", "study", "substr", "symlink", "syscall", "sysopen", "sysread",
"sysseek", "system", "syswrite",
"tell", "telldir", "tie", "tied", "time", "times", "truncate",
"uc", "ucfirst", "umask", "undef", "UNITCHECK", "unlink", "unpack", "unshift",
"untie", "use", "utime",
"values", "vec", "wait", "waitpid", "wantarray", "warn", "write",
/* Perl syntax */
"__DATA__", "__END__", "__FILE__", "__LINE__", "__PACKAGE__",
"and", "cmp", "continue", "CORE", "do", "else", "elsif", "eq", "exp",
"for", "foreach", "ge", "gt", "if", "le", "lock", "lt",
"m", "ne", "no", "or", "package", "q", "qq", "qr", "qw", "qx",
"s", "sub", "tr", "unless", "until", "while", "xor", "y",
NULL
};
char *Ruby_extensions[] = { ".rb", "Vagrantfile", NULL };
char *Ruby_HL_keywords[] = {
"__ENCODING__", "__LINE__", "__FILE__", "BEGIN", "END",
"alias", "and", "begin", "break",
"case", "class",
"def", "defined?", "do",
"else", "elsif", "end", "ensure",
"false", "for",
"if", "in",
"module",
"next", "nil", "not",
"or",
"redo", "rescue", "retry", "return",
"self", "super",
"then", "true",
"undef", "unless", "until",
"when", "while",
"yield",
NULL
};
/* https://guide.elm-lang.org */
char *Elm_extensions[] = { ".elm", NULL };
char *Elm_HL_keywords[] = {
"if", "then", "else", "case", "of", "let", "in", "type",
/* Maybe not 'where' */
"module", "where", "import", "exposing", "as", "port",
"infix", "infixl", "infixr",
"Empty", "False", "True",
/* Types */
"Bool|",
"Float|",
"Int|",
"List|",
"String|",
NULL
};
char *PHP_extensions[] = { ".php", NULL };
char *PHP_HL_keywords[] = {
"__halt_compiler",
"abstract", "and", "array", "as",
"break",
"callable", "case", "catch", "class", "clone", "const", "continue",
"declare", "default", "die", "do",
"echo", "else", "elseif", "empty", "enddeclare", "endfor",
"endforeach", "endif", "endswitch", "endwhile", "eval", "exit",
"extends",
"final", "finally", "for", "foreach", "function",
"global", "goto",
"if", "implements", "include", "include_once", "instanceof",
"insteadof", "interface", "isset",
"list",
"namespace", "new",
"or",
"print", "private", "protected", "public",
"require", "require_once", "return",
"static", "switch",
"throw", "trait", "try",
"unset", "use",
"var",
"while",
"xor",
"yield",
"__CLASS__", "__DIR__", "__FILE__", "__FUNCTION__", "__LINE__",
"__METHOD__", "__NAMESPACE__", "__TRAIT__",
NULL
};
/* https://docs.bazel.build/versions/master/be/overview.html */
char *Bazel_extensions[] = { "WORKSPACE", "BUILD", ".bzl", NULL };
char *Bazel_HL_keywords[] = {
// Functions
"load", "package", "package_group", "licenses", "exports_files",
"glob", "select", "workspace",
// Android
"android_binary", "android_library", "aar_import",
"android_device", "android_ndk_repository",
"android_sdk_repository",
// C/C++
"cc_binary", "cc_inc_library", "cc_library", "cc_proto_library",
"cc_test",
// Java
"java_binary", "java_import", "java_library",
"java_lite_proto_library", "java_proto_library", "java_test",
"java_plugin", "java_runtime", "java_runtime_suite",
"java_toolchain",
// Objective_C
"apple_binary", "apple_static_library", "apple_stub_library",
"ios_application", "ios_extension", "ios_extension_binary",
"objc_binary", "j2objc_library", "objc_bundle",
"objc_bundle_library", "objc_framework", "objc_import",
"objc_library", "objc_proto_library", "ios_test",
// Protocol Buffer
"proto_lang_toolchain", "proto_library",
//Python
"py_binary", "py_library", "py_test", "py_runtime",
// Shell
"sh_binary", "sh_library", "sh_test",
// Extra Actions
"action_listener", "extra_action",
// General
"filegroup", "genquery", "test_suite", "alias",
"config_setting", "genrule",
// Platform
"constraint_setting", "contraint_value", "platform", "toolchain",
// Workspace
"bind", "git_repository", "http_archive", "http_file", "http_jar",
"local_repository", "maven_jar", "maven_server",
"new_git_repository", "new_http_archive", "new_local_repository",
"xcode_config", "xcode_version",
NULL
};
/* A .dockerignore file does not contain any Dockerfile keywords (unless by chance),
it's a newline separated list of patterns similar to file globs. But I wanted to
add it here to empasize its 'Dockerness'. */
char *Dockerfile_extensions[] = { "Dockerfile", ".dockerignore", NULL };
char *Dockerfile_HL_keywords[] = {
"ADD", "ARG",
"CMD", "COPY",
"ENTRYPOINT", "ENV", "EXPOSE",
"FROM",
"HEALTHCHECK",
"LABEL",
"MAINTAINER", /* Deprecated */
"ONBUILD",
"RUN",
"SHELL", "STOPSIGNAL",
"USER",
"VOLUME",
"WORKDIR",
NULL
};
char *SQL_extensions[] = { ".sql", ".SQL", NULL };
char *SQL_HL_keywords[] = {
/* https://www.drupal.org/docs/develop/coding-standards/list-of-sql-reserved-words */
"A", "ABORT", "ABS", "ABSOLUTE", "ACCESS", "ACTION", "ADA", "ADD",
"ADMIN", "AFTER", "AGGREGATE", "ALIAS", "ALL", "ALLOCATE", "ALSO",
"ALTER", "ALWAYS", "ANALYSE", "ANALYZE", "AND", "ANY", "ARE", "ARRAY|",
"AS", "ASC", "ASENSITIVE", "ASSERTION", "ASSIGNMENT", "ASYMMETRIC",
"AT", "ATOMIC", "ATTRIBUTE", "ATTRIBUTES", "AUDIT", "AUTHORIZATION",
"AUTO_INCREMENT", "AVG", "AVG_ROW_LENGTH",
"BACKUP", "BACKWARD", "BEFORE", "BEGIN", "BERNOULLI", "BETWEEN",
"BIGINT|", "BINARY|", "BIT|", "BIT_LENGTH", "BITVAR", "BLOB|", "BOOL|",
"BOOLEAN|", "BOTH", "BREADTH", "BREAK", "BROWSE", "BULK", "BY",
"C", "CACHE", "CALL", "CALLED", "CARDINALITY", "CASCADE", "CASCADED",
"CASE", "CAST", "CATALOG", "CATALOG_NAME", "CEIL", "CEILING", "CHAIN",
"CHANGE", "CHAR|","CHAR_LENGTH", "CHARACTER|", "CHARACTER_LENGTH",
"CHARACTER_SET_CATALOG", "CHARACTER_SET_NAME", "CHARACTER_SET_SCHEMA",
"CHARACTERISTIC", "CHARACTERS", "CHECK", "CHECKED", "CHECKPOINT",
"CHECKSUM", "CLASS", "CLASS_ORIGIN", "CLOB|", "CLOSE", "CLUSTER",
"CLUSTERED", "COALESCE", "COBOL", "COLLATE", "COLLATION",
"COLLATION_CATALOG", "COLLATION_NAME", "COLLATION_SCHEMA", "COLLECT",
"COLUMN", "COLUMN_NAME", "COLUMNS", "COMMAND_FUNCTION",
"COMMAND_FUNCTION_CODE", "COMMENT", "COMMIT", "COMMITTED", "COMPLETED",
"COMPRESS", "COMPUTE", "CONDITION", "CONDITION_NUMBER", "CONNECT",
"CONNECTION", "CONNECTION_NAME", "CONSTRAINT", "CONSTRAINT_CATALOG",
"CONSTRAINT_NAME", "CONSTRAINT_SCHEMA", "CONSTRAINTS", "CONSTRUCTOR",
"CONTAINS", "CONTAINSTABLE", "CONTINUE", "CONVERSION", "COPY", "CORR",
"CORRESPONDING", "COUNT", "COVAR_POP", "COVAR_SAMP", "CREATE",
"CREATEDB", "CREATEROLE", "CREATEUSER", "CROSS", "CSV","CUBE",
"CUME_DIST", "CURRENT", "CURRENT_DATE",
"CURRENT_DEFAULT_TRANSFORM_GROUP", "CURRENT_PATH", "CURRENT_ROLE",
"CURRENT_TIME", "CURRENT_TIMESTAMP",
"CURRENT_TRANSFORM_GROUP_FOR_TYPE", "CURRENT_USER", "CURSOR|",
"CURSOR_NAME", "CYCLE",
"DATA", "DATABASE", "DATABASES", "DATE|", "DATETIME|",
"DATETIME_INTERVAL_CODE", "DATETIME_INTERVAL_PRECISION", "DAY",
"DAY_HOUR", "DAY_MICROSECOND", "DAY_MINUTE", "DAY_SECOND",
"DAYOFMONTH", "DAYOFWEEK", "DAYOFYEAR", "DBCC", "DEALLOCATE", "DEC",
"DECIMAL|", "DECLARE", "DEFAULT", "DEFAULTS", "DEFERRABLE",
"DEFINED", "DEFINER", "DEGREE", "DELAY_KEY_WRITE", "DELAYED", "DELETE",
"DELIMITER", "DELIMITERS", "DENSE_RANK", "DENY", "DEPTH", "DEREF",
"DERIVED", "DESC", "DESCRIBE", "DESCRIPTOR", "DESTROY", "DESTRUCTOR",
"DETERMINISTIC", "DIAGNOSTIC", "DICTIONARY", "DISABLE", "DISCONNECT",
"DISK", "DISPATCH", "DISTINCT", "DISTINCTROW", "DISTRIBUTED", "DIV",
"DO", "DOMAIN", "DOUBLE|", "DROP", "DUAL", "DUMMY", "DUMP", "DYNAMIC",
"DYNAMIC_FUNCTION", "DYNAMIC_FUNCTION_CODE",
"EACH", "ELEMENT", "ELSE", "ELSEIF", "ENABLE", "ENCLOSED", "ENCODING",
"ENCRYPTED", "END", "END-EXEC", "ENUM", "EQUALS", "ERRLVL", "ESCAPE",
"EVERY", "EXCEPT", "EXCEPTION", "EXCLUDE", "EXCLUDING", "EXCLUSIVE",
"EXEC", "EXECUTE", "EXISTING", "EXISTS", "EXIT", "EXP", "EXPLAIN",
"EXTERNAL", "EXTRACT",
"FALSE|", "FETCH", "FIELDS", "FILE", "FILLFACTOR", "FILTER", "FINAL",
"FIRST", "FLOAT|", "FLOAT4|", "FLOAT8|", "FLOOR", "FLUSH", "FOLLOWING",
"FOR", "FORCE", "FOREIGN", "FORTRAN", "FORWARD", "FOUND", "FREE",
"FREETEXT", "FREETEXTTABLE", "FREEZE", "FROM", "FULL", "FULLTEXT",
"FUNCTION", "FUSION",
"G", "GENERAL", "GENERATED", "GET", "GLOBAL", "GO", "GOTO", "GRANT",
"GRANTED", "GRANTS", "GREATEST", "GROUP", "GROUPING",
"HANDLER", "HAVING", "HEADER", "HEAP", "HIERARCHY", "HIGH_PRIORITY",
"HOLD", "HOLDLOCK", "HOST", "HOSTS", "HOUR", "HOUR_MICROSECOND",
"HOUR_MINUTE", "HOUR_SECOND",
"IDENTIFIED", "IDENTITY", "IDENTITY_INSERT", "IDENTITYCOL", "IF",
"IGNORE", "ILIKE", "IMMEDIATE", "IMMUTABLE", "IMPLEMENTATION",
"IMPLICIT", "IN", "INCLUDE", "INCLUDING", "INCREMENT", "INDEX",
"INDICATOR", "INFILE", "INFIX", "INHERIT", "INHERITS", "INITIAL",
"INITIALIZE", "INITIALLY", "INNER", "INOUT", "INPUT", "INSENSITIVE",
"INSERT", "INSERT_ID", "INSTANCE", "INSTANTIABLE", "INSTEAD", "INT|",
"INT1|", "INT2|", "INT3|", "INT4|", "INT8|", "INTEGER|", "INTERSECT",
"INTERSECTION", "INTERVAL", "INTO", "INVOKER", "IS", "ISAM", "ISNULL",
"ISOLATION", "ITERATE",
"JOIN",
"K", "KEY", "KEY_MEMBER", "KEY_TYPE", "KEYS", "KILL",
"LANCOMPILER", "LANGUAGE", "LARGE", "LAST", "LAST_INSERT_ID",
"LATERAL", "LEADING", "LEAST", "LEAVE", "LEFT", "LENGTH", "LESS",
"LEVEL", "LIKE", "LIMIT", "LINENO", "LINES", "LISTEN", "LN", "LOAD",
"LOCAL", "LOCALTIME", "LOCALTIMESTAMP", "LOCATION", "LOCATOR", "LOCK",
"LOGIN", "LOGS", "LONG|", "LONGBLOB|", "LONGTEXT|", "LOOP",
"LOW_PRIORITY", "LOWER",
"M", "MAP", "MATCH", "MATCHED", "MAX", "MAX_ROWS", "MAXETXTENTS",
"MAXVALUE", "MEDIUMBLOB|", "MEDIUMINT|", "MEDIUMINT|", "MEMBER",
"MERGE", "MESSAGE_LENGTH", "MESSAGE_OCTET_LENGTH", "MESSAGE_TEXT",
"METHOD", "MIDDLEINT|", "MIN", "MIN_ROWS", "MINUS", "MINUTE",
"MINUTE_MICROSECOND", "MINUTE_SECOND", "MINVALUE", "MLSLABEL",
"MOD", "MODE", "MODIFIES", "MODIFY", "MODULE", "MONTH", "MONTHNAME",
"MORE", "MOVE", "MULTISET", "MUMPS", "MYISAM",
"NAME", "NAMES", "NATIONAL", "NATURAL", "NCHAR|", "NCLOB|", "NESTING",
"NEW", "NEXT", "NO", "NO_WRITE_TO_BINLOG", "NOAUDIT", "NOCHECK",
"NOCOMPRESS", "NOCREATEDB", "NOCREATEROLE", "NOCREATEUSER",
"NOINHERIT", "NOLOGIN", "NONCLUSTERED", "NONE", "NORMALIZE",
"NORMALIZED", "NOSUPERUSER", "NOT", "NOTHING", "NOTIFY", "NOTNULL",
"NOWAIT", "NULL", "NULLABLE", "NULLIF", "NULLS", "NUMBER|", "NUMERIC|",
"OBJECT", "OCTET_LENGTH", "OCTETS", "OF", "OFF", "OFFLINE", "OFFSET",
"OFFSETS", "OIDS", "OLD", "ON", "ONLINE", "ONLY", "OPEN",
"OPENDATASOURCE", "OPENQUERY", "OPENROWSET", "OPENXML", "OPERATION",
"OPERATOR", "OPTIMIZE", "OPTION", "OPTIONALLY", "OPTIONS", "OR",
"ORDER", "ORDERING", "ORDINALITY", "OTHERS", "OUT", "OUTER", "OUTFILE",
"OUTPUT", "OVER", "OVERLAPS", "OVERLAY", "OVERRIDING", "OWNER",
"PACK_KEYS", "PAD", "PARAMETER", "PARAMETER_MODE", "PARAMETER_NAME",
"PARAMETER_ORDINAL_POSITION", "PARAMETER_SPECIFIC_CATALOG",
"PARAMETER_SPECIFIC_NAME", "PARAMETER_SPECIFIC_SCHEMA", "PARAMETERS",
"PARTIAL", "PARTITION", "PASCAL", "PASSWORD", "PATH", "PCTFREE",
"PERCENT", "PERCENT_RANK", "PERCENTILE_CONT", "PERCENTILE_DISC",
"PLACING" "PLAN", "PLI", "POSITION", "POSTFIX", "POWER", "PRECEDING",
"PRECISION", "PREFIX", "PREORDER", "PREPARE", "PREPARED", "PRESERVE",
"PRIMARY", "PRINT", "PRIOR", "PRIVILEGES", "PROC", "PROCEDURAL",
"PROCEDURE", "PROCESS", "PROCESSLIST", "PUBLIC", "PURGE",
"RAID0", "RAISERROR", "RANGE", "RANK", "RAW", "READ", "READS",
"READTEXT", "|REAL", "RECHECK", "RECONFIGURE", "RECURSIVE", "REF",
"REFERENCES", "REFERENCING", "REGEXP", "REGR_AVGX", "REGR_AVGY",
"REGR_COUNT", "REGR_INTERCEPT", "REGR_R2", "REGR_SLOPE", "REGR_SXX",
"REGR_SXY", "REGR_SYY", "REINDEX", "RELATIVE", "RELEASE", "RELOAD",
"RENAME", "REPEAT", "REPEATABLE", "REPLACE", "REPLICATION", "REQUIRE",
"RESET", "RESIGNAL", "RESOURCE", "RESTART", "RESTORE", "RESTRICT",
"RESULT", "RETURN", "RETURNED_CARDINALITY", "RETURNED_LENGTH",
"RETURNED_OCTET_LENGTH", "RETURNED_SQLSTATE", "RETURNS", "REVOKE",
"RIGHT", "RLIKE", "ROLE", "ROLLBACK", "ROLLUP", "ROUTINE",
"ROUTINE_CATALOG", "ROUTINE_NAME", "ROUTINE_SCHEMA", "ROW",
"ROW_COUNT", "ROW_NUMBER", "ROWCOUNT", "ROWGUIDCOL", "ROWID", "ROWNUM",
"ROWS", "RULE",
"SAVE", "SAVEPOINT", "SCALE", "SCHEMA", "SCHEMA_NAME", "SCHEMAS",
"SCOPE", "SCOPE_CATALOG", "SCOPE_NAME", "SCROLL", "SEARCH", "SECOND",
"SECOND_MICROSECOND", "SECTION", "SECURITY", "SELECT", "SELF",
"SENSITIVE", "SEPARATOR", "SEQUENCE", "SERIALIZABLE", "SERVER_NAME",
"SESSION", "SESSION_USER", "SET", "SETOF", "SETS", "SETUSER", "SHARE",
"SHOW", "SHUTDOWN", "SIGNAL", "SIMILAR", "SIMPLE", "SIZE", "SMALLINT|",
"SOME", "SONAME", "SOURCE", "SPACE", "SPATIAL", "SPECIFIC",
"SPECIFIC_NAME", "SPECIFICTYPE", "SQL", "SQL_BIG_RESULT",
"SQL_BIG_SELECTS", "SQL_BIG_TABLES", "SQL_CALC_FOUND_ROWS",
"SQL_LOG_OFF", "SQL_LOG_UPDATE", "SQL_LOW_PRIORITY_UPDATES",
"SQL_SELECT_LIMIT", "SQL_SMALL_RESULT", "SQL_WARNINGS", "SQLCA",
"SQLCODE", "SQLERROR", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING",
"SQRT", "SSL", "STABLE", "START", "STARTING", "STATE", "STATEMENT",
"STATIC", "STATISTIC", "STATUS", "STDDEV_POP", "STDDEV_SAMP", "STDIN",
"STDOUT", "STORAGE", "STRAIGHT_JOIN", "STRICT", "STRING", "STRUCTURE",
"STYLE", "SUBCLASS_ORIGIN", "SUBLIST", "SUBMULTISET", "SUBSTRING",
"SUCCESSFUL", "SUM", "SUPERUSER", "SYMMETRIC", "SYNONYM", "SYSDATE",
"SYSID", "SYSTEM", "SYSTEM_USER",
"TABLE", "TABLE_NAME", "TABLES", "TABLESAMPLE", "TABLESPACE", "TEMP",
"TEMPLATE", "TEMPORARY", "TERMINATE", "TERMINATED", "TEXT|",
"TEXTSIZE", "THAN", "THEN", "TIES", "TIME|", "TIMESTAMP|",
"TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TINYBLOB|", "TINYINT|",
"TINYTEXT|", "TO", "TOAST", "TOP", "TOP_LEVEL_COUNT", "TRAILING",
"TRAN", "TRANSACTION", "TRANSACTION_ACTIVE", "TRANSACTIONS_COMMITTED",
"TRANSACTIONS_ROLLED_BACK", "TRANSFORM", "TRANSFORMS", "TRANSLATE",
"TREAT", "TRIGGER", "TRIGGER_CATALOG", "TRIGGER_NAME",
"TRIGGER_SCHEMA", "TRIM", "TRUE|", "TRUNCATE", "TRUSTED", "TSEQUAL",
"TYPE", "UESCAPE", "|UID", "UNBOUNDED", "UNCOMMITTED", "UNDER", "UNDO",
"UNENCRYPTED", "UNION", "UNIQUE", "UNKNOWN", "UNLISTEN", "UNLOCK",
"UNNAMED", "UNNEST", "UNSIGNED|", "UNTIL", "UPDATE", "UPDATETEXT",
"UPPER", "USAGE", "USE", "USER", "USER_DEFINED_TYPE_CATALOG",
"USER_DEFINED_TYPE_CODE", "USER_DEFINED_TYPE_NAME",
"USER_DEFINED_TYPE_SCHEMA", "USING", "UTC_DATE", "UTC_TIME",
"UTC_TIMESTAMP",
"VACUUM", "VALID", "VALIDATE", "VALIDATOR", "VALUE", "VALUES",
"VAR_POP", "VAR_SAMP", "VARBINARY|", "VARCHAR|", "VARCHAR2|",
"VARCHARACTER|", "VARIABLE", "VARIABLES", "VARYING", "VERBOSE",
"VIEW", "VOLATILE",
"WAITFOR", "WHEN", "WHENEVER", "WHERE", "WHILE", "WIDTH_BUCKET",
"WINDOW", "WITH", "WITHIN", "WITHOUT", "WORK", "WRITE", "WRITETEXT",
"X509", "XOR",
"YEAR", "YEAR_MONTH",
/* lowercase */
"zerofill", "zone",
"a", "abort", "abs", "absolute", "access", "action", "ada", "add",
"admin", "after", "aggregate", "alias", "all", "allocate", "also",
"alter", "always", "analyse", "analyze", "and", "any", "are", "array|",
"as", "asc", "asensitive", "assertion", "assignment", "asymmetric",
"at", "atomic", "attribute", "attributes", "audit", "authorization",
"auto_increment", "avg", "avg_row_length",
"backup", "backward", "before", "begin", "bernoulli", "between",
"bigint|", "binary|", "bit|", "bit_length", "bitvar", "blob|", "bool|",
"boolean|", "both", "breadth", "break", "browse", "bulk", "by",
"c", "cache", "call", "called", "cardinality", "cascade", "cascaded",
"case", "cast", "catalog", "catalog_name", "ceil", "ceiling", "chain",
"change", "char|","char_length", "character|", "character_length",
"character_set_catalog", "character_set_name", "character_set_schema",
"characteristic", "characters", "check", "checked", "checkpoint",
"checksum", "class", "class_origin", "clob|", "close", "cluster",
"clustered", "coalesce", "cobol", "collate", "collation",
"collation_catalog", "collation_name", "collation_schema", "collect",
"column", "column_name", "columns", "command_function",
"command_function_code", "comment", "commit", "committed", "completed",
"compress", "compute", "condition", "condition_number", "connect",
"connection", "connection_name", "constraint", "constraint_catalog",
"constraint_name", "constraint_schema", "constraints", "constructor",
"contains", "containstable", "continue", "conversion", "copy", "corr",
"corresponding", "count", "covar_pop", "covar_samp", "create",
"createdb", "createrole", "createuser", "cross", "csv","cube",
"cume_dist", "current", "current_date",
"current_default_transform_group", "current_path", "current_role",
"current_time", "current_timestamp",
"current_transform_group_for_type", "current_user", "cursor|",
"cursor_name", "cycle",
"data", "database", "databases", "date|", "datetime|",
"datetime_interval_code", "datetime_interval_precision", "day",
"day_hour", "day_microsecond", "day_minute", "day_second",
"dayofmonth", "dayofweek", "dayofyear", "dbcc", "deallocate", "dec",
"decimal|", "declare", "default", "defaults", "deferrable",
"defined", "definer", "degree", "delay_key_write", "delayed", "delete",
"delimiter", "delimiters", "dense_rank", "deny", "depth", "deref",
"derived", "desc", "describe", "descriptor", "destroy", "destructor",
"deterministic", "diagnostic", "dictionary", "disable", "disconnect",
"disk", "dispatch", "distinct", "distinctrow", "distributed", "div",
"do", "domain", "double|", "drop", "dual", "dummy", "dump", "dynamic",
"dynamic_function", "dynamic_function_code",
"each", "element", "else", "elseif", "enable", "enclosed", "encoding",
"encrypted", "end", "end-exec", "enum", "equals", "errlvl", "escape",
"every", "except", "exception", "exclude", "excluding", "exclusive",
"exec", "execute", "existing", "exists", "exit", "exp", "explain",
"external", "extract",
"false|", "fetch", "fields", "file", "fillfactor", "filter", "final",
"first", "float|", "float4|", "float8|", "floor", "flush", "following",
"for", "force", "foreign", "fortran", "forward", "found", "free",
"freetext", "freetexttable", "freeze", "from", "full", "fulltext",
"function", "fusion",
"g", "general", "generated", "get", "global", "go", "goto", "grant",
"granted", "grants", "greatest", "group", "grouping",
"handler", "having", "header", "heap", "hierarchy", "high_priority",
"hold", "holdlock", "host", "hosts", "hour", "hour_microsecond",
"hour_minute", "hour_second",
"identified", "identity", "identity_insert", "identitycol", "if",
"ignore", "ilike", "immediate", "immutable", "implementation",
"implicit", "in", "include", "including", "increment", "index",
"indicator", "infile", "infix", "inherit", "inherits", "initial",
"initialize", "initially", "inner", "inout", "input", "insensitive",
"insert", "insert_id", "instance", "instantiable", "instead", "int|",
"int1|", "int2|", "int3|", "int4|", "int8|", "integer|", "intersect",
"intersection", "interval", "into", "invoker", "is", "isam", "isnull",
"isolation", "iterate",
"join",
"k", "key", "key_member", "key_type", "keys", "kill",
"lancompiler", "language", "large", "last", "last_insert_id",
"lateral", "leading", "least", "leave", "left", "length", "less",
"level", "like", "limit", "lineno", "lines", "listen", "ln", "load",
"local", "localtime", "localtimestamp", "location", "locator", "lock",
"login", "logs", "long|", "longblob|", "longtext|", "loop",
"low_priority", "lower",
"m", "map", "match", "matched", "max", "max_rows", "maxetxtents",
"maxvalue", "mediumblob|", "mediumint|", "mediumint|", "member",
"merge", "message_length", "message_octet_length", "message_text",
"method", "middleint|", "min", "min_rows", "minus", "minute",
"minute_microsecond", "minute_second", "minvalue", "mlslabel",
"mod", "mode", "modifies", "modify", "module", "month", "monthname",
"more", "move", "multiset", "mumps", "myisam",
"name", "names", "national", "natural", "nchar|", "nclob|", "nesting",
"new", "next", "no", "no_write_to_binlog", "noaudit", "nocheck",
"nocompress", "nocreatedb", "nocreaterole", "nocreateuser",
"noinherit", "nologin", "nonclustered", "none", "normalize",
"normalized", "nosuperuser", "not", "nothing", "notify", "notnull",
"nowait", "null", "nullable", "nullif", "nulls", "number|", "numeric|",
"object", "octet_length", "octets", "of", "off", "offline", "offset",
"offsets", "oids", "old", "on", "online", "only", "open",
"opendatasource", "openquery", "openrowset", "openxml", "operation",
"operator", "optimize", "option", "optionally", "options", "or",
"order", "ordering", "ordinality", "others", "out", "outer", "outfile",
"output", "over", "overlaps", "overlay", "overriding", "owner",
"pack_keys", "pad", "parameter", "parameter_mode", "parameter_name",
"parameter_ordinal_position", "parameter_specific_catalog",
"parameter_specific_name", "parameter_specific_schema", "parameters",
"partial", "partition", "pascal", "password", "path", "pctfree",
"percent", "percent_rank", "percentile_cont", "percentile_disc",
"placing" "plan", "pli", "position", "postfix", "power", "preceding",
"precision", "prefix", "preorder", "prepare", "prepared", "preserve",
"primary", "print", "prior", "privileges", "proc", "procedural",
"procedure", "process", "processlist", "public", "purge",
"raid0", "raiserror", "range", "rank", "raw", "read", "reads",
"readtext", "|real", "recheck", "reconfigure", "recursive", "ref",
"references", "referencing", "regexp", "regr_avgx", "regr_avgy",
"regr_count", "regr_intercept", "regr_r2", "regr_slope", "regr_sxx",
"regr_sxy", "regr_syy", "reindex", "relative", "release", "reload",
"rename", "repeat", "repeatable", "replace", "replication", "require",
"reset", "resignal", "resource", "restart", "restore", "restrict",
"result", "return", "returned_cardinality", "returned_length",
"returned_octet_length", "returned_sqlstate", "returns", "revoke",
"right", "rlike", "role", "rollback", "rollup", "routine",
"routine_catalog", "routine_name", "routine_schema", "row",
"row_count", "row_number", "rowcount", "rowguidcol", "rowid", "rownum",
"rows", "rule",
"save", "savepoint", "scale", "schema", "schema_name", "schemas",
"scope", "scope_catalog", "scope_name", "scroll", "search", "second",
"second_microsecond", "section", "security", "select", "self",
"sensitive", "separator", "sequence", "serializable", "server_name",
"session", "session_user", "set", "setof", "sets", "setuser", "share",
"show", "shutdown", "signal", "similar", "simple", "size", "smallint|",
"some", "soname", "source", "space", "spatial", "specific",
"specific_name", "specifictype", "sql", "sql_big_result",
"sql_big_selects", "sql_big_tables", "sql_calc_found_rows",
"sql_log_off", "sql_log_update", "sql_low_priority_updates",
"sql_select_limit", "sql_small_result", "sql_warnings", "sqlca",
"sqlcode", "sqlerror", "sqlexception", "sqlstate", "sqlwarning",
"sqrt", "ssl", "stable", "start", "starting", "state", "statement",
"static", "statistic", "status", "stddev_pop", "stddev_samp", "stdin",
"stdout", "storage", "straight_join", "strict", "string", "structure",
"style", "subclass_origin", "sublist", "submultiset", "substring",
"successful", "sum", "superuser", "symmetric", "synonym", "sysdate",
"sysid", "system", "system_user",
"table", "table_name", "tables", "tablesample", "tablespace", "temp",
"template", "temporary", "terminate", "terminated", "text|",
"textsize", "than", "then", "ties", "time|", "timestamp|",
"timezone_hour", "timezone_minute", "tinyblob|", "tinyint|",
"tinytext|", "to", "toast", "top", "top_level_count", "trailing",
"tran", "transaction", "transaction_active", "transactions_committed",
"transactions_rolled_back", "transform", "transforms", "translate",
"treat", "trigger", "trigger_catalog", "trigger_name",
"trigger_schema", "trim", "true|", "truncate", "trusted", "tsequal",
"type", "uescape", "|uid", "unbounded", "uncommitted", "under", "undo",
"unencrypted", "union", "unique", "unknown", "unlisten", "unlock",
"unnamed", "unnest", "unsigned|", "until", "update", "updatetext",
"upper", "usage", "use", "user", "user_defined_type_catalog",
"user_defined_type_code", "user_defined_type_name",
"user_defined_type_schema", "using", "utc_date", "utc_time",
"utc_timestamp",
"vacuum", "valid", "validate", "validator", "value", "values",
"var_pop", "var_samp", "varbinary|", "varchar|", "varchar2|",
"varcharacter|", "variable", "variables", "varying", "verbose",
"view", "volatile",
"waitfor", "when", "whenever", "where", "while", "width_bucket",
"window", "with", "within", "without", "work", "write", "writetext",
"x509", "xor",
"year", "year_month",
"zerofill", "zone",
NULL
};
char *nginx_extensions[] = { "nginx.conf", "global.conf", NULL };
char *nginx_HL_keywords[] = {
/* http://nginx.org/en/docs/dirindex.html */
"absolute_redirect", "accept_mutex", "accept_mutex_delay",
"access_log", "add_after_body", "add_before_body", "add_header",
"add_trailer", "addition_types", "aio", "aio_write", "alias", "allow",
"ancient_browser", "ancient_browser_value", "api", "auth_basic",
"auth_basic_user_file", "auth_http", "auth_http_header",
"auth_http_pass_client_cert", "auth_http_timeout", "auth_jwt",
"auth_jwt_claim_set", "auth_jwt_key_file", "auth_request",
"auth_request_set", "autoindex", "autoindex_exact_size",
"autoindex_format", "autoindex_localtime",
"break",
"charset", "charset_map", "charset_types", "chunked_transfer_encoding",
"client_body_buffer_size", "client_body_in_file_only",
"client_body_in_single_buffer", "client_body_temp_path",
"client_body_timeout", "client_header_buffer_size",
"client_header_timeout", "client_max_body_size",
"connection_pool_size", "create_full_put_path",
"daemon", "dav_access", "dav_methods", "debug_connection",
"debug_point", "default_type", "deny", "directio",
"directio_alignment", "diable_symlinks",
"empty_gif", "env", "error_log", "error_page", "etag", "events",
"expires",
"f4f", "f4f_buffer_size", "fastcgi_buffer_size", "fastcgi_buffering",
"fastcgi_buffers", "fastcgi_busy_buffers_size", "fastcgi_cache",
"fastcgi_cache_background_update", "fastcgi_cache_bypass",
"fastcgi_cache_key", "fastcgi_cache_lock", "fastcgi_cache_lock_age",
"fastcgi_cache_lock_timeout", "fastcgi_cache_max_range_offset",
"fastcgi_cache_methods", "fastcgi_cache_min_users",
"fastcgi_cache_path", "fastcgi_cache_purge",
"fastcgi_cache_revalidate", "fastcgi_cache_use_stale",
"fastcgi_cache_valid", "fastcgi_catch_stderr",
"fastcgi_connect_timeout", "fastcgi_force_ranges",
"fastcgi_hide_header", "fastcgi_ignore_client_abort",
"fastcgi_ignore_headers", "fastcgi_index", "fastcgi_intercept_errors",
"fastcgi_keep_conn", "fastcgi_limit_rate",
"fastcgi_max_temp_file_size", "fastcgi_next_upstream",
"fastcgi_next_upstream_timeout", "fastcgi_next_upstream_tries",
"fastcgi_no_cache", "fastcgi_param", "fastcgi_pass",
"fastcgi_pass_header", "fastcgi_pass_request_body",
"fastcgi_pass_request_headers", "fastcgi_read_timeout",
"fastcgi_request_buffering", "fastcgi_send_lowat",
"fastcgi_send_timeout", "fastcgi_split_path_info", "fastcgi_store",
"fastcgi_store_access", "fastcgi_temp_file_write_size",
"fastcgi_temp_path", "flv",
"geo", "geoip_city", "geoip_country", "geoip_org", "geoip_proxy",
"geoip_proxy_recursive", "google_perftools_profiles", "gunzip",
"gunzip_buffers", "gzip", "gzip_buffers", "gzip_comp_level",
"gzip_disable", "gzip_http_version", "gzip_min_length", "gzip_proxied",
"gzip_static", "gzip_types", "gzip_vary",
"hash", "health_check", "health_check_timeout", "hls", "hls_buffers",
"hls_forward_args", "hls_fragment", "hls_mp4_buffer_size",
"hls_mp4_max_buffer_size", "http", "http2_body_preread_size",
"http2_idle_timeout", "http2_max_concurrent_streams",
"http2_max_field_size", "http2_max_header_size", "http2_max_requests",
"http2_recv_buffer_size", "http2_recv_timeout",
"if", "if_modified_since", "ignore_invalid_headers", "image_filter",
"image_filter_buffer", "image_filter_interface",
"image_filter_interlace", "image_filter_jpeg_quality",
"image_filter_sharpen", "image_filter_transparency",
"image_filter_webp_quality", "imap_auth", "imap_capabilities",
"imap_client_buffer", "include", "index", "internal", "ip_hash",
"js_access", "js_content", "js_filter", "js_include", "js_preread",
"js_set",
"keepalive", "keepalive_disable", "keepalive_requests",
"keepalive_timeout", "keyval", "keyval_zone",
"large_client_header_buffers", "least_conn", "least_time",
"Limit_conn", "limit_conn_log_level", "limit_conn_status",
"limit_conn_status", "limit_conn_zone", "limit_except", "Limit_rate",
"limit_rate_after", "limit_req", "limit_req_log_level",
"limit_req_status", "limit_req_zone", "limit_zone", "lingering_close",
"lingering_time", "lingering_timeout", "listen", "load_module",
"location", "lock_file", "log_format", "log_not_found",
"log_subrequest",
"mail", "map", "map_hash_bucket_size", "map_hash_max_size",
"master_process", "match", "max_ranges", "memcached_bind",
"memcached_buffer_size", "memcached_connect_timeout",
"memcached_force_ranges", "memcached_gzip_flag",
"memcached_next_upstream", "memcached_net_upstream_timeout",
"memcached_next_upstream_tries", "memcached_pass",
"memcached_read_timeout", "memcahced_send_timeout", "merge_slashes",
"min_delete_depth", "mirror", "mirror_request_body", "modern_browser",
"modern_browser_value", "mp4", "mp4_buffer_size", "mp4_limit_rate",
"mp4_limit_rate_after", "mp4_max_buffer_size", "msie_padding",
"msie_refresh", "multi_accept",
"ntim",
"open_file_cache", "open_file_cache_errors",
"open_file_cache_min_uses", "open_file_cache_valid",
"open_log_file_cache", "output_buffers", "override_charset",
"pcre_jit", "perl", "perl_modules", "perl_require", "perl_set", "pid",
"pop3_auth", "pop3_capabilities", "port_in_redirect",
"postpone_output", "preread_buffer_size", "preread_timeout",
"protocol", "proxy_bind", "proxy_buffer", "proxy_buffer_size",
"proxy_buffering", "proxy_buffers", "proxy_busy_buffers_size",
"proxy_cache", "proxy_cache_background_update", "proxy_cache_bypass",
"proxy_cache_convert_head", "proxy_cache_key", "proxy_cache_key",
"proxy_cache_lock", "proxy_cache_lock_age", "proxy_cache_lock_timeout",
"proxy_cache_max_range_offset", "proxy_cache_methods",
"proxy_cache_min_uses", "proxy_cache_path", "proxy_cache_purge",
"proxy_cache_revalidate", "proxy_cache_use_stale", "proxy_cache_valid",
"proxy_connect_timeout", "proxy_cookie_domain", "proxy_cookie_path",
"proxy_download_rate", "proxy_force_ranges",
"proxy_headers_hash_bucket_size", "proxy_headers_hash_max_size",
"proxy_hide_header", "proxy_http_version", "proxy_ignore_client_abort",
"proxy_ignore_headers", "proxy_intercept_errors", "proxy_limit_rate",
"proxy_max_temp_file_size", "proxy_method", "proxy_next_upstream",
"proxy_next_upstream_timeout", "proxy_next_upstrean_tries",
"prixy_no_cache", "proxy_pass", "proxy_pass_error_message",
"proxy_pass_header", "proxy_pass_rquest_body",
"proxy_pass_request_headers", "proxy_protocol",
"proxy_protocol_timeout", "proxy_read_timeout", "proxy_redirect",
"proxy_request_buffering", "proxy_responses", "proxy_send_lowat",
"proxy_send_timeout", "proxy_set_body", "proxy_set_header",
"proxy_ssl", "proxy_ssl_certificate", "proxy_ssl_certificate_key",
"proxy_ssl_ciphers", "proxy_ssl_crl", "proxy_ssl_name",
"proxy_ssl_password_file", "proxy_ssl_protocols",
"proxy_ssl_server_name", "proxy_ssl_session_reuse",
"proxy_ssl_trusted_certificate", "proxy_ssl_verify",
"proxy_ssl_verify_depth", "proxy_store", "proxy_store_access",
"proxy_temp_file_write_size", "proxy-temp_path", "proxy_timeout",
"proxy_upload_rate",
"queue",
"random_index", "read_ahead", "real_ip_header","real_ip_recursive",
"recursive_error_pages", "referer_hash_bucket_size",
"referer_hash_max_size", "request_pool_size",
"reset_timeout_connection", "resolver", "resolver_timeout", "return",
"rewrite", "rewrite_log", "root",
"satisfy", "scgi_bind", "scgi_buffer_size", "scgi_buffering",
"scgi_buffers", "scgi_busy_buffers_size", "scgi_cache",
"scgi_cache_background_update", "scgi_cache_bypass", "scgi_cache_key",
"scgi_cache_lock", "scgi_cache_lock_age", "scgi_cache_lock_timeout",
"scgi_cache_max_range_offset", "scgi_cache_methods", "scgi_cache_path",
"scgi_cache_purge", "scgi_cache_revalidate", "scgi_cache_use_state",
"scgi_cache_valid", "scgi_connect_timeout", "scgi_force_ranges",
"scgi_hide_header", "scgi_ignore_client_abort", "scgi_ignore_headers",
"scgi_intercept_errors", "scgi_limit_rate", "scgi_max_temp_file_size",
"scgi_next_upstream", "scgi_next_upstream_timeout",
"scgi_next_upstream_tries", "scgi_no_cache", "scgi_param", "scgi_pass",
"scgi_pass_header", "scgi_pass_request_body",
"scgi_pass_request_headers", "scgi_read_timeout",
"scgi_request_buffering", "scgi_send_timeout", "scgi_store",
"scgi_store_access", "scgi_temp_file_write_size", "scgi_temp_path",
"secure_link", "secure_link_md5", "secure_link_secret", "send_lowat",
"send_timeout", "sendfile", "sendfile_max_chunk", "server",
"server_name", "server_name_in_redirect",
"server_names_hash_bucket_size", "server_names_hash_max_size",
"server_tokens", "session_log", "session_log_format",
"session_log_zone", "set", "set_real_ip_from", "slice", "smtp_auth",
"smtp_capabilities", "source_charset", "spdy_chunk_size",
"sdpy_headers_comp", "split_clients", "ssi", "ssi_last_modified",
"ssi_min_file_chunk", "ssi_silent_errors", "ssi_types",
"ssi_value_length", "ssl", "ssl_buffer_size", "ssl_certificate",
"ssl_certificate_key", "ssl_ciphers", "ssl_client_certificate",
"ssl_crl", "ssl_dhparam", "ssl_ecdh_curve", "ssl_engine",
"ssl_handshake_timeout", "ssl_password_file",
"ssl_prefer_server_ciphers", "ssl_preread", "ssl_protocols",
"ssl_session_cache", "ssl_session_ticket_key", "ssl_session_tickets",
"ssl_session_timeout", "ssl_stapling", "ssl_stapling_file",
"ssl_stapling_responder", "ssl_stapling_verify",
"ssl_trusted_certificate", "ssl_verify_client", "starttls", "state",
"status", "status_format", "status_zone", "sticky",
"sticky_cookie_name", "stream", "stub_status", "sub_filter",
"sub_filter_last_modified", "sub_filter_once", "sub_filter_types",
"tcp_nodelay", "tcp_nopush", "thread_pool", "timeout",
"timer_recolution", "try_files", "types", "types_hash_bucket_size",
"types_hash_max_size",
"underscores_in_headers", "uninitialized_variable_warn", "upstream",
"upstream_conf", "use", "user", "userid", "userid_domain",
"userid_expires", "userid_mark", "userid_name", "userid_p3p",
"userid_path", "userid_service", "uwsgi_bind", "uwsgi_buffer_size",
"uwsgi_buffering", "uwsgi_buffers", "uwsgi_busy_buffers_size",
"uwsgi_cache", "uwsgi_cache_background_update", "uwsgi_cache_bypass",
"uwsgi_cache_key", "uwsgi_cache_lock", "uwsgi_cache_lock_age",
"uwsgi_cache_lock_timeout", "uwsgi_cache_max_range_offset",
"uwsgi_cache_methods", "uwsgi_cache_min_uses", "uwsgi_cache_path",
"uwsgi_cache_purge", "uwsgi_cache_revalidate", "uwsgi_cache_use_stale",
"uwsgi_cache_valid", "uwsgi_connect_timeout", "uwsgi_force_ranges",
"uwsgi_hide_header", "uwsgi_ignore_client_abort",
"uwsgi_ignore_headers", "uwsgi_intercept_errors", "uwsgi_limit_rate",
"uwsgi_max_temp_file_size", "uwsgi_modifier1", "uwsgi_modifier2",
"uwsgi_next_upstream", "uwsgi_next_upstream_timeout",
"uwsgi_next_upstream_tries", "uwsgi_no_cache", "uwsgi_param",
"uwsgi_pass", "uwsgi_pass_header", "uwsgi_pass_request_body",
"uwsgi_pass_request_headers", "uwsgi_read_timeout",
"uwsgi_request_buffering", "uwsgi_send_timeout",
"uwsgi_ssl_certificate", "uwsgi_ssl_certificate_key",
"uwsgi_ssl_ciphers", "uwsgi_ssl_crl", "uwsgi_ssl_name",
"uwsgi_ssl_password_file", "uwsgi_ssl_protocols",
"uwsgi_ssl_server_name", "uwsgi_ssl_session_reuse",
"uwsgi_ssl_trusted_certificate", "uwsgi_ssl_verify",
"uwsgi_ssl_verify_depth", "uwsgi_store", "uwsgi_store_access",
"uwsgi_temp_file_write_size", "uwsgi_temp_path",
"valid_referers", "variables_hash_bucket_size",
"variables_hash_max_size",
"worker_aio_requests", "worker_connections", "worker_cpu_affinity",
"worker_priority", "worker_processes", "worker_rlimit_core",
"worker_rlimit_nofile", "worker_shutdown_timeout",
"working_directory",
"xclient", "xml_entities", "xslt_last_modified", "xslt_param",
"xslt_string_param", "xslt_stylesheet", "xslt_types",
"zone",
NULL
};
char *go_extensions[] = { ".go", NULL };
char *go_HL_keywords[] = {
"break",
"case", "chan", "const", "continue",
"default", "defer",
"else",
"fallthrough", "for", "func",
"go", "goto",
"if", "import", "interface",
"map",
"package",
"range", "return",
"select", "struct", "switch",
"type",
"var",
"bool|", "byte|", // byte is alias for uint8
"complex64|", "complex128|",
"float32|", "float64|",
"int|", "int8|", "int16|", "int32|", "int64|",
"rune|", // alias for int32, represents a Unicode code point
"string|",
"uint|", "uint8|", "uint16|", "uint32|", "uint64|", "uinptr|",
NULL
};
char *groovy_extensions[] = { ".groovy", ".gradle", NULL };
char *groovy_HL_keywords[] = {
"as", "assert",
"break",
"case", "catch", "class", "const", "continue",
"def", "default", "do",
"else", "enum", "extends",
"false", "finally", "for",
"goto",
"if", "implements", "import", "in", "instanceof", "interface",
"new", "null",
"package",
"return",
"super", "static", "switch",
"this", "throw", "throws", "trait", "true", "try",
"while",
"boolean|", "Boolean|",
"byte|", "Byte|",
"char|", "Character|",
"double|", "Double|",
"float|", "Float|",
"int|", "Integer|",
"long|", "Long|",
"short", "Short|",
"void|",
NULL
};
char *R_extensions[] = { ".R", NULL };
char *R_HL_keywords[] = {
"...", // The dot-dot-dot object type
"break",
"else",
"FALSE", "for", "function",
"if", "in", "Inf",
"NA", "NaN", "NA_integer_", "NA_real_", "NA_complex_", "NA_character_",
"next", "NULL",
"repeat",
"switch", // Not a reserved word but I'll include it.
"TRUE",
"while",
NULL
};
char *Haxe_extensions[] = { ".hx", NULL };
char *Haxe_HL_keywords[] = {
"abstract",
"break",
"case", "cast", "catch", "class", "continue",
"default", "do", "dynamic",
"else", "enum", "extends", "extern",
"false", "for", "function",
"if", "implements", "import", "in", "inline", "interface",
"macro",
"new", "null",
"override",
"package", "private", "public",
"return",
"static", "switch",
"this", "throw", "true", "try", "typedef",
"untyped", "using",
"var",
"while",
"#if",
"#else", "#elseif", "#end",
NULL
};
char *Chapel_extensions[] = { ".chpl", NULL };
char *Chapel_HL_keywords[] = {
/* "_" */
"align", "as", "atomic",
"begin", "break", "by",
"class", "cobegin", "coforall", "config", "const", "continue",
"delete", "dmapped", "do", "domain",
"else", "enum", "except", "extern",
"for", "forall",
"if", "in", "index", "inline", "inout", "iter",
"label", "let", "local",
"module",
"new", "nil", "noinit",
"on", "only", "otherwise", "out",
"param", "private", "proc", "public",
"record", "reduce", "ref", "require", "return",
"scan", "select", "serial", "single", "sparse", "subdomain", "sync",
"then", "type",
"union", "use",
"var",
"when", "where", "while", "with",
"yield",
"zip",
/* Spec 0.985: 6.4.2 Reserved for future use. */
"lambda",
/* Primitive Types */
"bool|",
"complex|",
"imag|", "int|",
"real|",
"string|",
"uint|",
"void|",
NULL
};
char *Kotlin_extensions[] = { ".kt", NULL };
char *Kotlin_HL_keywords[] = {
/* Hard keywords. */
"as", "as?",
"break",
"class", "continue",
"do",
"else",
"false", "for", "fun",
"if", "in", "!in", "interface", "is", "!is",
"null",
"object",
"package",
"return",
"super",
"this", "throw", "true", "try", "typealias", "typeof",
"val", "var",
"when", "while",
/* Soft keywords */
"by",
"catch", "constructor",
"delegate", "dynamic",
"field", "file", "finally",
"get",
"import", "init",
"param", "property",
"receiver",
"set", "setparam",
"where",
/* Modifier keywords */
"actual", "abstract", "annotation",
"companion", "const", "crossinline",
"data",
"enum", "expect", "external",
"final",
"infix", "inline", "inner", "internal",
"lateinit",
"noinline",
"open", "operator", "out", "override",
"private", "protected", "public",
"reified",
"sealed", "suspend",
"tailrec",
"vararg",
/* Special identifiers */
"field",
"it",
/* Data types */
"Boolean|",
"Byte|",
"Char|",
"Double|",
"Float|",
"Int|",
"Long|",
"Short|",
"String|",
"Array|",
/* Kotlin 1.3 ->, experimental */
"UByte|",
"UShort|",
"UInt|",
"ULong|",
"UByteArray|",
"UShortArray|",
"UIntArray|",
"ULongArray|",
NULL
};
char *C_sharp_extensions[] = { ".cs", NULL };
char *C_sharp_HL_keywords[] = {
/* Keywords */
"abstract", "as",
"base",
"case", "catch", "checked", "class", "const", "continue",
"default", "delegate", "do",
"else", "enum", "event", "explicit", "extern",
"false", "finally", "fixed", "for", "foreach",
"goto",
"if", "implicit", "in", "interface", "internal", "is",
"lock",
"namespace", "new", "null",
"operator", "out", "override",
"params", "private", "protected", "public",
"readonly", "ref", "return",
"sealed", "sizeof", "stackalloc", "static", "struct", "switch",
"this", "throw", "true", "try", "typeof",
"unchecked", "unsafe", "using", /* using static */
"var", "virtual", "volatile",
"while",
/* Types */
"bool|", "byte|",
"decimal|", "double|",
"float|",
"int|",
"long|",
"object|",
"sbyte|", "short|", "string|",
"uint|", "ulong|", "ushort|",
"void|",
NULL
};
char *Scala_extensions[] = { ".scala", ".sbt", NULL };
char *Scala_HL_keywords[] = {
/* Keywords */
"abstract",
"case", "catch", "class",
"def", "do",
"else", "extends",
"false", "final", "finally", "for", "forSome",
"if", "implicit", "import",
"lazy",
"match",
"new",
"object", "override",
"package", "private", "protected",
"return",
"sealed", "super",
"this", "throw", "trait", "Try", "true", "type",
"val", "Var",
"while", "with",
"yield",
/* Not included
"-", ":", "=", "=>", "<-", "<:", "<%", ">:", "#", "@"
*/
/* Types */
"Any|", "AnyRef|",
"Boolean|", "Byte|",
"Char|",
"Double|",
"Float|",
"Int|",
"Long|",
"Null|",
"Nothing|",
"Short|",
"String|",
"Unit|",
NULL
};
char *Lua_extensions[] = { ".lua", NULL };
// Default executable.
char *Lua_HL_keywords[] = {
"and",
"break",
"do",
"else", "elseif", "end",
"false", "for", "function",
"if", "in",
"local",
"nil", "not",
"or",
"repeat", "return",
"then", "true",
"until",
"while",
NULL
};
char *AWK_extensions[] = { ".awk", ".gawk", NULL };
char *AWK_executables[] = { "awk", "gawk", "mawk", "nawk", NULL };
char *AWK_HL_keywords[] = {
/* https://www.gnu.org/software/gawk/manual/gawk.html */
"BEGIN", "BEGINFILE",
"END", "ENDFILE",
/* Predefined variables. */
"BINMODE|",
"CONVFMT|",
"FIELDWIDTHS|", "FPAT|", "FS|",
"IGNORECASE|",
"LINT|",
"OFMT|", "OFS|", "OPS|",
"PREC|",
"ROUNDMODE|", "RS|",
"SUBSEP|",
"TEXTDOMAIN|",
/* Built-in variables. */
"ARGC|", "ARGV|", "ARGIND|",
"ENVIRON|", "ERRNO|",
"FILENAME|", "FNR|", "FUNCTAB|",
"NF|", "NR|",
"PROCINFO|",
"RLENGTH|", "RSTART|", "RT|",
"SYMTAB|",
/* Reserved keywords and built-in functions (GAWK extensions) */
"and", "asort", "asorti", "atan2",
"bindtextdomain", "break",
"close", "compl", "continue", "cos",
"dcgettext", "dcngettext", "default", "delete", "do",
"else", "exit", "exp",
"fflush", "function",
"gensub", "gsub",
"if", "in", "index", "int", "isarray",
"length", "log", "lshift",
"match", "mktime",
"next", "nextfile",
"or",
"patsplit", "print", "printf",
"rand", "return", "rshift",
"sin", "split", "sprintf", "sqrt", "srand", "strftime", "strtonum",
"sub", "substr", "switch", "system", "systime",
"tolower", "toupper", "typeof",
"while",
"xor",
/* Directives (GAWK) */
"@namespace",
NULL
};
/* */
char *No_executables[] = { NULL };
struct editor_syntax HLDB[] = {
{
"Text",
Text_extensions,
No_executables,
Text_HL_keywords,
"#",
"", "",
HARD_TABS,
DEFAULT_KILO_TAB_STOP, /* tab stop */
0 /* auto */
},
{
"Makefile",
Makefile_extensions,
No_executables,
Makefile_HL_keywords,
"#",
"", "", /* Comment continuation by backslash is missing. */
HARD_TABS,
DEFAULT_KILO_TAB_STOP,
1 /* auto indent */
},
{
"C",
C_extensions,
No_executables,
C_HL_keywords,
"//",
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
DEFAULT_KILO_TAB_STOP,
1, /* auto indent */
},
{
"Java",
Java_extensions,
No_executables,
Java_HL_keywords,
"//",
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Python",
Python_extensions,
No_executables,
Python_HL_keywords,
"#",
"'''", "'''",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Erlang",
Erlang_extensions,
No_executables,
Erlang_HL_keywords,
"%",
"", "",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1 // TODO make bitfield?
},
{
"JavaScript",
JS_extensions,
No_executables,
JS_HL_keywords,
"//",
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Shell",
Shell_extensions,
Shell_executables,
Shell_HL_keywords,
"#",
"", "",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
8,
1
},
{
"Perl",
Perl_extensions,
No_executables,
Perl_HL_keywords,
"#",
"", "", /* ^= ^= comments missing */
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Ruby",
Ruby_extensions,
No_executables,
Ruby_HL_keywords,
"#",
"", "",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"PHP",
PHP_extensions,
No_executables,
PHP_HL_keywords,
"//", // TODO also '#'
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Elm",
Elm_extensions,
No_executables,
Elm_HL_keywords,
"--",
"", "",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Bazel",
Bazel_extensions,
No_executables,
Bazel_HL_keywords,
"#",
"", "",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Docker",
Dockerfile_extensions,
No_executables,
Dockerfile_HL_keywords,
"#",
"", "",
HL_HIGHLIGHT_STRINGS, /* FIXME number parsing: ubuntu:16.04 only hilights 04 as number.*/
4,
1
},
{
"SQL",
SQL_extensions,
No_executables,
SQL_HL_keywords,
"--",
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"nginx",
nginx_extensions,
No_executables,
nginx_HL_keywords,
"#",
"", "",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"go",
go_extensions,
No_executables,
go_HL_keywords,
"//",
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Groovy",
groovy_extensions,
No_executables,
groovy_HL_keywords,
"//",
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"R",
R_extensions,
No_executables,
R_HL_keywords,
"#",
"", "",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
2,
1
},
{
"Haxe",
Haxe_extensions,
No_executables,
Haxe_HL_keywords,
"//",
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Chapel",
Chapel_extensions,
No_executables,
Chapel_HL_keywords,
"//",
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Kotlin",
Kotlin_extensions,
No_executables,
Kotlin_HL_keywords,
"//",
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"C#",
C_sharp_extensions,
No_executables,
C_sharp_HL_keywords,
"//",
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Scala",
Scala_extensions,
No_executables,
Scala_HL_keywords,
"//",
"/*", "*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Awk",
AWK_extensions,
AWK_executables,
AWK_HL_keywords,
"#",
"", "",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
},
{
"Lua",
Lua_extensions,
No_executables,
Lua_HL_keywords,
"--",
"--[[", "--]]",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS,
4,
1
}
};
/**
hldb_entries(): A macro replacement for
#define HLDB_ENTRIES (sizeof(HLDB) / sizeof(HLDB[0]))
*/
int
hldb_entries() {
return sizeof(HLDB) / sizeof(HLDB[0]);
}
<file_sep>#ifndef KILO_H
#define KILO_H
#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#define _GNU_SOURCE
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include "const.h"
#include "data.h"
#include "row.h"
#include "highlight.h"
#include "filetypes.h" /* language keywords */
#include "syntax.h"
#include "undo.h"
#include "terminal.h"
#include "key.h"
#include "command.h"
#include "clipboard.h"
#include "init.h"
#include "help.h"
#include "version.h"
#include "file.h"
/*** defines ***/
/*
2020-03-29
Latest:
- 0.4.14 more proper options parsing
- ... lots of modes, like Awk, C#, Kotlin, Lua, ...
- ... Emacs-like mode parsing from executable or -*- <mode> -*-
- 0.4.4 Haxe mode
- 0.4.3 R mode
- 0.4.2 Groovy mode
- 0.4.1 Some cleaning
- 0.4 Split kilo.c into multiple files
- 0.3.9.10 "Vagrantfile" triggers Ruby-mode
- 0.3.9.9 Dockerfile mode name changed to Docker & added ".dockerignore" to Docker mode.
- 0.3.9.8 golang mode
- 0.3.9.7 goto-line also refreshes screen
- 0.3.9.6 screen resize
- 0.3.9.5 nginx mode
- 0.3.9.4 SQL mode
- 0.3.9.3 Dockerfile mode
- 0.3.9.2 refactor indent calculation a bit.
- 0.3.9.1 Bazel autoindent && Erlang autoindent bug fix. TODO: generalize autoindent
- 0.3.9 Bazel mode
- 0.3.8 refresh (Ctrl-L)
- 0.3.7 goto-beginning & goto-end (Esc-A, Esc-E)
- Undo for next & previous buffer commands. (2017-05-30)
- Ctrl-O open file Ctrl-N new buffer
- M-x mark (but no kill/copy region yet); opening a new file don't cause segfault.
- M-x open-file
- Fixed open files bug where no files were opened in some cases.
- Slightly better editor_del_char() but undo for del does not work.
- delete-buffer
- create-buffer, next-buffer, previous-buffer works (need open-file, every E->dirty check), test delete-buffer.
- M-x goto-line
- When aborted, the find command stops at the position.
- Fixed cursor left movement bug when past screen length.
- --debug 4 debugs cursor & screen position
- Elm mode (incomplete but we'll get there)
- Ruby mode
- M-x undo works (but not 100%) on Ctrl-K/Ctrl-Y
- Help (-h, --help)
- Basically, limit input to ASCII only in command_insert_character().
TODO set mode upon saving a new buffer unless the mode has been set already.
TODO *Change* internal data structure to rope or gap ...
TODO BUG: go mode uses spaces not tabs (also: indentation).
TODO BUG: backspace at the end of a line that's longer than screencols.
TODO BUG: cursor up or down when at or near the end of line: faulty pos
TODO BUG: soft/hard tab mix (like in this very file) messes pos calc
TODO BUG: make integer arg parsing more robust (goto-line NaN segfaults)
TODO SQL mode can be context insensitive
TODO indentation revamp; more config with modes
TODO (0.5) Emacs style C-K or C-SPC & C/M-W
TODO (0.6) *Help* mode (BUFFER_TYPE_READONLY)
TODO M-x search-and-replace (version 0: string; version 1: regexps)
TODO *Command* or *Shell* buffer (think of REPL)
TODO (0.7) M-x compile (based on Mode & cwd contents): like Emacs (output)
[Compiling based on HL mode & working directory: make, mvn build, ant, lein]
TODO ~/.kilorc/.kilo.conf (tab-width) (M-x set-tab-width)
TODO M-x TAB command completion
TODO M-x command buffer & context-sensitive parameter buffer.
TODO (0.8) change internal data structure into rope or gap or similar
TODO (0.8.5) Store the last command argument context-sensitively
TODO Proper command line options (-lgetopt)
TODO (0.9) Unicode support (-lncurses)
TODO (1.0) Forth interpreter from libforth ... (also: M-x forth-repl)
TODO (1.1) Configuration files (with forth)
TODO (1.1.5) Filetypes as configuration
TODO (1.2) M-x hammurabi and other games. (maybe BUFFER_TYPE_INTERACTIVE)
*/
#endif
<file_sep>#ifndef HIGHLIGHT_H
#define HIGHLIGHT_H
/*
`erow.hl' is an array of unsigned char values, meaning integers in the range of 0 to 255.
Each value in the array will correspond to a character in render, and will tell you whether that
character is part of a string, or a comment, or a number, and so on. Let’s create an enum containing
the possible values that the hl array can contain.
*/
enum editor_highlight {
HL_NORMAL = 0,
HL_COMMENT,
HL_MLCOMMENT,
HL_KEYWORD1,
HL_KEYWORD2,
HL_STRING,
HL_NUMBER,
HL_MATCH
};
/* */
#define HL_HIGHLIGHT_NUMBERS (1<<0)
#define HL_HIGHLIGHT_STRINGS (1<<1)
#endif
<file_sep>/**
find.c
*/
#include "output.h"
#include "key.h"
#include "find.h"
void
editor_find_callback(char *query, int key) {
static int last_match = -1;
static int direction = 1;
static int saved_hl_line;
static char *saved_hl;
if (saved_hl) {
memcpy(E->row[saved_hl_line].hl, saved_hl, E->row[saved_hl_line].rsize);
free(saved_hl);
saved_hl = NULL;
}
int current;
erow *row;
char *match;
int i;
if (key == '\r' || key == '\x1b') {
last_match = -1;
direction = 1;
return;
} else if (key == ARROW_RIGHT || key == ARROW_DOWN) {
direction = 1;
} else if (key == ARROW_DOWN || key == ARROW_UP) {
direction = -1;
} else {
last_match = -1;
direction = 1;
}
if (last_match == -1)
direction = 1;
current = last_match;
for (i = 0; i < E->numrows; i++) {
current += direction;
if (current == -1)
current = E->numrows - 1;
else if (current == E->numrows)
current = 0;
row = &E->row[current];
match = strstr(row->render, query);
if (match) {
last_match = current;
E->cy = current;
E->cx = editor_row_rx_to_cx(row, match - row->render);
E->rowoff = E->numrows;
saved_hl_line = current;
saved_hl = malloc(row->rsize);
memcpy(saved_hl, row->hl, row->rsize);
memset(&row->hl[match - row->render], HL_MATCH, strlen(query));
break;
}
}
}
void
editor_find() {
char *query = editor_prompt(DEFAULT_SEARCH_PROMPT, editor_find_callback);
if (query) {
free(query);
}
}
char *
editor_prompt(char *prompt, void (*callback) (char *, int)) {
size_t bufsize = 256;
char *buf = malloc(bufsize);
size_t buflen = 0;
int c;
buf[0] = '\0';
while (1) {
editor_set_status_message(prompt, buf);
editor_refresh_screen();
c = key_read();
if (c == DEL_KEY || c == CTRL_KEY('h') || c == BACKSPACE) {
if (buflen != 0)
buf[--buflen] = '\0';
} else if (c == '\x1b') {
editor_set_status_message("");
if (callback)
callback(buf, c);
free(buf);
return NULL;
} else if (c == '\r') {
if (buflen != 0) {
editor_set_status_message("");
if (callback)
callback(buf, c);
return buf;
}
} else if (!iscntrl(c) && c < 128) {
if (buflen == bufsize - 1) {
bufsize *= 2;
buf = realloc(buf, bufsize);
}
buf[buflen++] = c;
buf[buflen] = '\0';
}
if (callback)
callback(buf, c);
}
}
<file_sep>#ifndef FILE_H
#define FILE_H
/**
file.h
*/
char *editor_rows_to_string(int *buflen);
char *editor_basename(char *path);
#endif
<file_sep>/*** file.c ***/
#include <stdlib.h>
#include <string.h>
#include "data.h"
extern struct editor_config *E;
char *
editor_rows_to_string(int *buflen) {
int totlen = 0;
int j;
char *buf;
char *p;
for (j = 0; j < E->numrows; j++)
totlen += E->row[j].size + 1;
*buflen = totlen;
buf = malloc(totlen);
p = buf;
for (j = 0; j < E->numrows; j++) {
memcpy(p, E->row[j].chars, E->row[j].size);
p += E->row[j].size;
*p = '\n';
p++;
}
return buf;
}
char *
editor_basename(char *path) {
char *s = strrchr(path, '/');
if (s == NULL) {
return strdup(path);
} else {
return strdup(s + 1);
}
}
<file_sep>#include <stddef.h>
#include <fcntl.h>
#include "command.h"
#include "row.h"
#include "buffer.h"
#include "clipboard.h"
#include "file.h"
#include "find.h"
extern struct clipboard C;
/* M-x "command-str" <ENTER> followed by an optional argument (INT or STRING). */
struct command_str COMMANDS[] = {
{
COMMAND_CREATE_BUFFER,
"create-buffer",
COMMAND_ARG_TYPE_NONE,
NULL,
"Buffer created.",
NULL
},
{
COMMAND_SWITCH_BUFFER,
"switch-buffer",
COMMAND_ARG_TYPE_STRING,
"Buffer: %s",
"Buffer created.",
"Failed to switch to buffer: '%s'"
},
{
/* DELETE CURRENT BUFFER */
COMMAND_DELETE_BUFFER,
"delete-buffer",
COMMAND_ARG_TYPE_NONE,
NULL,
"The current buffer deleted.",
"Unsaved changes. Save buffer or clear modification bit."
},
{
COMMAND_NEXT_BUFFER,
"next-buffer",
COMMAND_ARG_TYPE_NONE,
NULL,
"Switched to next buffer.",
NULL
},
{
COMMAND_PREVIOUS_BUFFER,
"previous-buffer",
COMMAND_ARG_TYPE_NONE,
NULL,
"Switched to previous buffer.",
NULL
},
{
COMMAND_SET_MODE,
"set-mode",
COMMAND_ARG_TYPE_STRING,
"Mode: %s",
"Mode set to: '%s'",
"Failed to set mode to '%s'"
},
{
COMMAND_SET_TAB_STOP,
"set-tab-stop",
COMMAND_ARG_TYPE_INT,
"Set tab stop to: %s", // always %s
"Tab stop set to: %d", // based on ARG_TYPE: %d or %s
"Invalid tab stop value: '%s' (range 2-)"
},
{
COMMAND_SET_SOFT_TABS,
"set-soft-tabs",
COMMAND_ARG_TYPE_NONE,
NULL,
"Soft tabs in use.",
NULL,
},
{
COMMAND_SET_HARD_TABS,
"set-hard-tabs",
COMMAND_ARG_TYPE_NONE,
NULL,
"Hard tabs in use",
NULL
},
{
COMMAND_SET_AUTO_INDENT,
"set-auto-indent",
COMMAND_ARG_TYPE_STRING,
"Set auto indent on or off: %s",
"Auto indent is %s",
"Invalid auto indent mode: '%s'"
},
{
COMMAND_SAVE_BUFFER,
"save-buffer",
COMMAND_ARG_TYPE_STRING, /* Prompt for new file only. */
"Save as: %s",
"%d bytes written to %s", // Special handling: %d and %s
"Can't save, I/O error: %s" // %s = error
},
{
// Open file for reading, save current buffer to it.
COMMAND_SAVE_BUFFER_AS,
"save-buffer-as",
COMMAND_ARG_TYPE_STRING,
"Save buffer as: %s",
"%d bytes written successfully to %s", // Special handling: %d and %s
"Can't save, I/O error: %s" // %s = error
},
{
COMMAND_OPEN_FILE,
"open-file",
COMMAND_ARG_TYPE_STRING,
"Open file: %s",
"%s opened.",
"Cannot open file: %s"
},
{
COMMAND_MOVE_CURSOR_UP,
"move-cursor-up",
COMMAND_ARG_TYPE_NONE,
NULL,
"",
NULL
},
{
COMMAND_MOVE_CURSOR_DOWN,
"move-cursor-down",
COMMAND_ARG_TYPE_NONE,
NULL,
"",
NULL
},
{
COMMAND_MOVE_CURSOR_LEFT,
"move-cursor-left",
COMMAND_ARG_TYPE_NONE,
NULL,
"",
NULL
},
{
COMMAND_MOVE_CURSOR_RIGHT,
"move-cursor-right",
COMMAND_ARG_TYPE_NONE,
NULL,
"",
NULL
},
{
COMMAND_GOTO_BEGINNING_OF_FILE,
"goto-beginning",
COMMAND_ARG_TYPE_NONE,
NULL,
"",
NULL
},
{
COMMAND_GOTO_END_OF_FILE,
"goto-end",
COMMAND_ARG_TYPE_NONE,
NULL,
"",
NULL
},
{
COMMAND_REFRESH_SCREEN,
"refresh",
COMMAND_ARG_TYPE_NONE,
NULL,
"",
NULL
},
{
COMMAND_KILL_LINE,
"kill-line",
COMMAND_ARG_TYPE_NONE,
NULL,
"",
NULL
},
{
COMMAND_YANK_CLIPBOARD,
"yank",
COMMAND_ARG_TYPE_NONE,
NULL,
"",
NULL
},
{
COMMAND_UNDO,
"undo",
COMMAND_ARG_TYPE_NONE,
NULL,
"",
NULL
},
{
COMMAND_INSERT_CHAR,
"insert-char",
COMMAND_ARG_TYPE_STRING,
"Character: %s",
"Inserted '%c'",
"Failed to insert a char:"
},
{
COMMAND_DELETE_CHAR,
"delete-char",
COMMAND_ARG_TYPE_NONE,
NULL,
"Deleted",
"No characters to delete!"
},
{
COMMAND_GOTO_LINE,
"goto-line",
COMMAND_ARG_TYPE_INT,
"Goto line: %s",
"Jumped",
"Failed to goto line: "
},
{
COMMAND_MARK,
"mark",
COMMAND_ARG_TYPE_NONE,
"",
"Mark set",
"Failed to set a mark."
},
{
COMMAND_COPY_REGION,
"copy-region",
COMMAND_ARG_TYPE_NONE,
"",
"Region copied.",
"No region to copy."
},
{
COMMAND_KILL_REGION,
"kill-region",
COMMAND_ARG_TYPE_NONE,
"",
"Region killed.",
"No region to kill."
}
};
int
command_entries() {
return sizeof(COMMANDS) / sizeof(COMMANDS[0]);
}
/**
* The functionality ought to be in command_del_char() because undo*()s are also here.
* TODO FIXME XXX
* @param undo (1=called from undo(); 0=normal operation)
*/
void
editor_del_char(int undo) {
erow *row;
if (E->cy == E->numrows) {
if (E->cy > 0) {
if (undo)
key_move_cursor(ARROW_LEFT);
else
command_move_cursor(COMMAND_MOVE_CURSOR_LEFT);
}
return;
}
if (E->cx == 0 && E->cy == 0)
return;
row = &E->row[E->cy];
if (E->cx > 0) {
int orig_cx = E->cx;
int char_to_be_deleted = row->chars[E->cx];
int len = editor_row_del_char(row, E->cx - 1);
if (len > 0) {
int current_cx = E->cx;
E->cx = orig_cx;
// FIXME undo as a single undo command
// as currently we can only pop one from the stack.
// Should do it, though.
while (current_cx < E->cx) {
E->cx = current_cx;
if (!undo) {
if (current_cx == orig_cx) { // ??
undo_push_one_int_arg(COMMAND_DELETE_CHAR, COMMAND_INSERT_CHAR,
char_to_be_deleted);
} else {
undo_push_one_int_arg(COMMAND_DELETE_CHAR, COMMAND_INSERT_CHAR,
E->is_soft_indent ? (int) ' ' : (int) '\t');
}
}
current_cx++;
}
}
E->cx = orig_cx - len;
if (E->coloff > 0) {
E->coloff -= len;
if (E->coloff < 0)
E->coloff = 0;
}
} else {
if (!undo) {
undo_push_one_int_arg(COMMAND_DELETE_CHAR, COMMAND_INSERT_CHAR, '\r');
} else {
// FIXME undo insert_newline.
}
E->cx = E->row[E->cy - 1].size;
editor_row_append_string(&E->row[E->cy - 1], row->chars, row->size);
editor_del_row(E->cy);
E->cy--;
}
}
/**
editor_process_keypress()
*/
void
editor_process_keypress() {
static int quit_times = KILO_QUIT_TIMES;
static int previous_key = -1;
int c = key_normalize(key_read());
// Cut and paste fix?
if (previous_key != '\r' && c == '\n')
c = '\r';
/* Clipboard is deemed full after the first non-KILL_LINE_KEY. */
if (previous_key == KILL_LINE_KEY && c != KILL_LINE_KEY) {
C.is_full = 1;
undo_push_clipboard();
}
previous_key = c;
E->is_banner_shown = 1; // After the first keypress, yes.
switch (c) {
case '\r':
command_insert_newline();
break;
case QUIT_KEY:
if (E->dirty && quit_times > 0) {
editor_set_status_message(UNSAVED_CHANGES_WARNING, quit_times);
quit_times--;
return;
}
/* Clear the screen at the end. */
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
exit(0);
break;
case SAVE_KEY:
editor_save(COMMAND_SAVE_BUFFER);
break;
case HOME_KEY:
E->cx = 0;
break;
case END_KEY:
if (E->cy < E->numrows)
E->cx = E->row[E->cy].size;
break;
case FIND_KEY:
editor_find();
break;
case BACKSPACE:
case CTRL_KEY('h'):
case DEL_KEY:
if (c == DEL_KEY)
command_move_cursor(COMMAND_MOVE_CURSOR_RIGHT);
command_delete_char();
break;
case PAGE_DOWN:
case PAGE_UP: {
int times = 0;
if (c == PAGE_UP) {
E->cy = E->rowoff;
times = TERMINAL.screenrows;
} else if (c == PAGE_DOWN) {
E->cy = E->rowoff + TERMINAL.screenrows - 1;
if (E->cy <= E->numrows) {
times = TERMINAL.screenrows;
} else {
E->cy = E->numrows;
times = E->numrows - E->rowoff;
}
}
while (times--)
command_move_cursor(c == PAGE_UP
? COMMAND_MOVE_CURSOR_UP : COMMAND_MOVE_CURSOR_DOWN);
break;
}
case ARROW_UP:
command_move_cursor(COMMAND_MOVE_CURSOR_UP);
break;
case ARROW_LEFT:
command_move_cursor(COMMAND_MOVE_CURSOR_LEFT);
break;
case ARROW_RIGHT:
command_move_cursor(COMMAND_MOVE_CURSOR_RIGHT);
break;
case ARROW_DOWN:
command_move_cursor(COMMAND_MOVE_CURSOR_DOWN);
break;
case GOTO_BEGINNING_OF_FILE_KEY:
command_goto_beginning_of_file();
break;
case GOTO_END_OF_FILE_KEY:
command_goto_end_of_file();
break;
case REFRESH_KEY: /* Ctrl-L */
case '\x1b':
command_refresh_screen();
break;
case KILL_LINE_KEY:
clipboard_add_line_to_clipboard();
break;
case YANK_KEY:
{
struct command_str *c = command_get_by_key(COMMAND_YANK_CLIPBOARD);
clipboard_yank_lines(c->success);
break;
}
case CLEAR_MODIFICATION_FLAG_KEY:
if (E->dirty) {
editor_set_status_message("Modification flag cleared.");
E->dirty = 0;
}
break;
case COMMAND_KEY:
exec_command();
break;
case COMMAND_UNDO_KEY:
undo();
break;
case GOTO_LINE_KEY:
command_goto_line();
break;
case NEXT_BUFFER_KEY:
command_next_buffer();
break;
case PREVIOUS_BUFFER_KEY:
command_previous_buffer();
break;
case MARK_KEY:
{
struct command_str *c = command_get_by_key(COMMAND_MARK);
command_mark(c->success);
break;
}
case COPY_REGION_KEY:
command_copy_from_mark(command_get_by_key(COMMAND_COPY_REGION));
break;
case KILL_REGION_KEY:
command_kill_from_mark();
break;
case NEW_BUFFER_KEY:
{
struct command_str *c = command_get_by_key(COMMAND_CREATE_BUFFER);
(void) create_buffer(BUFFER_TYPE_FILE, 0, c->success, COMMAND_NO_CMD);
break;
}
case OPEN_FILE_KEY:
command_open_file(NULL);
break;
default:
command_insert_char(c);
break;
}
quit_times = KILO_QUIT_TIMES;
}
int
is_empty_line(char *line, int linelen) {
if (line == NULL || linelen == 0)
return 1;
// There are no '\n' or '\r' in 'line'.
while (--linelen >= 0) {
if (line[linelen] != ' ' && line[linelen] != '\t')
return 0;
}
return 1;
}
/*
kilo implements more or less the GNU Emacs way of choosing the (major) mode.
https://www.gnu.org/software/emacs/manual/html_node/emacs/Choosing-Modes.html
*/
/*
* We have a line starting with the magic cookie, #!
* If the line is like #!executable or #!/path/to/executable
* (followed by EOL or whitespace and followed optionally by
* whatever) return 'executable'
*
* return NULL or char * pointing to executable name (malloc'd).
*/
char *
get_executable_name(char *line, int linelen) {
char *name = NULL;
int end = 2; // skip #!
int last_sep = 1;
while (end < linelen && !isspace(line[end])) {
// Should work in Windows, because it is POSIX compliant.
if (line[end] == '/')
last_sep = end;
end++;
}
end--;
if (end == last_sep)
return NULL;
name = malloc(end - last_sep + 1);
strncpy(name, line+last_sep+1, end - last_sep);
name[end - last_sep] = '\0';
return name;
}
/**
* name = mode name
* -*- name -*-
* -*- mode:name-*-
* -*- mode:name; -*-
* -*- mode:name; .... -*-
*
* whitespace ignored and not required
*
* return NULL or mode (malloc'd, remember to free())
*/
char *
get_mode_name(char *line, int linelen) {
char *SEP = "-*-";
char *MODE = "mode:";
char *l = strndup(line, linelen);
/* Starting -*- */
char *first = strstr(l, SEP);
if (first == NULL) {
free(l);
return NULL;
}
first += strlen(SEP);
char *after_mode = strstr(first, MODE);
/* There was a 'mode:' keyword. (It is optional.) */
if (after_mode != NULL)
first = after_mode + strlen(MODE);
char *second = strstr(first, SEP);
/* No ending -*-, so this line does not a mode contain. */
if (second == NULL) {
free(l);
return NULL;
}
/* There was an ending -*- */
/* Past whitespace. */
while (*first != '\0' && isspace(*first))
first++;
/* Find the end of the name. Because of C# mode '#' is accepted. */
char *name_end = first;
while (isalnum(*name_end) || *name_end == '#')
name_end++;
char *mode_name = malloc(name_end - first + 1);
strncpy(mode_name, first, name_end - first);
mode_name[name_end - first] = '\0';
free(l);
return mode_name;
}
/**
M-x open-file; also used when starting the editor to open files
specified in the command line.
*/
void
command_open_file(char *filename) {
char *line = NULL;
size_t linecap = 0;
ssize_t linelen;
struct stat stat_buffer;
FILE *fp = NULL;
int free_filename = 0;
int int_arg;
char *char_arg;
if (filename == NULL) {
struct command_str *c = command_get_by_key(COMMAND_OPEN_FILE);
int rc = editor_get_command_argument(c, &int_arg, &char_arg);
if (rc == 1) {
filename = strdup(char_arg);
free(char_arg);
free_filename = 1;
} else if (rc == 0) {
editor_set_status_message(STATUS_MESSAGE_ABORTED);
return;
} else {
editor_set_status_message(c->error_status);
return;
}
}
/* Yes, needed. */
if (E->dirty > 0
|| E->numrows > 0 || E->cx > 0 || E->cy > 0
|| E->filename != NULL) {
/* This buffer is in use. Create a new one & use it. */
(void) create_buffer(BUFFER_TYPE_FILE, 0, "FIXME: new buffer", COMMAND_NO_CMD);
}
E->filename = strdup(filename);
E->absolute_filename = realpath(filename, NULL);
E->basename = editor_basename(filename);
if (stat(E->filename, &stat_buffer) == -1) {
if (errno == ENOENT) {
E->is_new_file = 1;
E->dirty = 0;
if (free_filename)
free(filename);
syntax_set_mode_by_filename_extension(0);
return;
} else {
die("stat");
}
}
fp = fopen(E->absolute_filename, "r");
if (!fp) {
die("fopen");
}
int match_executable = !is_syntax_mode_set();
int match_mode_from_comment = match_executable;
int line_no = 0;
while ((linelen = getline(&line, &linecap, fp)) != -1) {
if (linelen > 0 && (line[linelen - 1] == '\n'
|| line[linelen - 1] == '\r'))
linelen--;
if (match_executable || match_mode_from_comment)
line_no++;
/* -*- mode -*- */
if (match_mode_from_comment && line_no <= 2) {
char *mode_name = get_mode_name(line, linelen);
if (mode_name != NULL) {
match_mode_from_comment = 0;
if (syntax_set_mode_by_name(mode_name, 0) == 0) {
// Only if mode matches.
match_executable = 0;
}
}
free(mode_name);
}
/* #!/path/to/executable */
if (match_executable) {
if (line_no == 1 && linelen > 2 && line[0] == '#' && line[1] == '!') {
match_executable = 0;
char *executable_name = get_executable_name(line, linelen);
if (executable_name != NULL
&& syntax_set_mode_by_name(executable_name, 0) == 0) {
match_mode_from_comment = 0;
}
free(executable_name);
}
}
editor_insert_row(E->numrows, line, linelen);
}
if (! is_syntax_mode_set())
syntax_set_mode_by_filename_extension(1);
free(line);
fclose(fp);
if (free_filename)
free(filename);
E->dirty = 0;
}
/**
* rc = 0 OK
* rc = -1 error
* rc = 1 aborted
*/
void
editor_save(int command_key) {
int len;
char *buf;
int fd;
char *tmp;
struct command_str *c = command_get_by_key(command_key);
if (c == NULL) {
editor_set_status_message("Unknown command! Cannot save!?!");
return;
}
if (command_key == COMMAND_SAVE_BUFFER_AS || E->filename == NULL) {
tmp = editor_prompt(c->prompt, NULL);
if (tmp != NULL) {
free(E->filename);
free(E->absolute_filename);
free(E->basename);
E->filename = strdup(tmp);
E->absolute_filename = strdup(E->filename); // realpath(E->filename, NULL) returns NULL.;
E->basename = editor_basename(E->filename);
syntax_select_highlight(NULL, 0);
free(tmp);
} else {
editor_set_status_message(STATUS_MESSAGE_ABORTED); // TODO ABORT message in conf.
return;
}
}
buf = editor_rows_to_string(&len);
if (buf == NULL || buf[0] == '\0') {
if (! E->dirty) {
editor_set_status_message("Empty buffer -- not saved.");
return;
} else {
// Add a newline and re-buf.
editor_insert_newline();
buf = editor_rows_to_string(&len);
}
}
fd = open(E->filename, O_RDWR | O_CREAT, 0644);
if (fd != -1) {
if (ftruncate(fd, len) != -1) {
if (write(fd, buf, len) == len) {
close(fd);
free(buf);
E->dirty = 0;
E->is_new_file = 0;
// if (strlen(abs) + strlen(success) > TERMINAL.screencols (not 100% acc)
// then cut X
if (E->absolute_filename
&& (strlen(E->absolute_filename) + strlen(c->success) > TERMINAL.screencols)) {
char *status_filename = malloc(TERMINAL.screencols + 1);
int truncate_len = strlen(E->absolute_filename) + strlen(c->success)
- TERMINAL.screencols + 3; // "..."
memset(status_filename, '\0', TERMINAL.screencols + 1);
strncpy(status_filename, "...", 3);
strncpy(status_filename+3, E->absolute_filename+truncate_len,
strlen(E->absolute_filename)-truncate_len);
status_filename[TERMINAL.screencols] = '\0';
editor_set_status_message(c->success, // TODO Special case: both %d and %s
len, status_filename); // ? E->absolute_filename : E->filename);
free(status_filename);
} else {
editor_set_status_message(c->success, len, E->absolute_filename ? E->absolute_filename : E->filename);
}
return; // fd closed, buf freed.
} // if write ok
syntax_select_highlight(NULL, 0);
}
close(fd);
}
free(buf);
editor_set_status_message(c->error_status, strerror(errno));
return;
} /* editor_save -> Acommand_save ... */
/*** M-x command ***/
void
command_debug(int command_key) {
if (!(E->debug & DEBUG_COMMANDS))
return;
struct command_str *c = command_get_by_key(command_key);
if (c != NULL)
editor_set_status_message(c->success);
}
/**
* Return command_str by command_key
*/
struct command_str *
command_get_by_key(int command_key) {
unsigned int i;
int entries = command_entries();
for (i = 0; i < entries; i++) {
if (COMMANDS[i].command_key == command_key)
return &COMMANDS[i];
}
return NULL;
}
void
command_insert_char(int character) {
if (E->ascii_only
&& character <= 31 && character != 9) // TODO 9 = TABKEY
return;
undo_push_simple(COMMAND_INSERT_CHAR, COMMAND_DELETE_CHAR);
editor_insert_char(character);
}
void
command_delete_char() {
editor_del_char(0);
undo_debug_stack();
command_debug(COMMAND_DELETE_CHAR);
}
void
command_insert_newline() {
int indent_len = editor_insert_newline();
if (E->is_auto_indent
&& (indent_len % E->tab_stop == 0)) { // 1 for newline
indent_len = indent_len / E->tab_stop; // no of tabs, soft or hard.
}
// Delete indented+1 chars at once.
undo_push_one_int_arg(COMMAND_INSERT_CHAR, COMMAND_DELETE_INDENT_AND_NEWLINE,
indent_len + 1); // newline here
if (E->debug & DEBUG_COMMANDS)
editor_set_status_message("Inserted newline");
}
/**
Return:
0 = no argument gotten
1 = one argument gotten.
-1 = argument conversion error.
*/
int
editor_get_command_argument(struct command_str *c, int *ret_int, char **ret_string) {
char *raw_str = NULL;
char *original_raw_string = NULL;
int raw_int = 0;
int rc;
if (c == NULL)
return 0;
/* FIXME now assume existence of %s in c->prompt. */
raw_str = editor_prompt(c->prompt, NULL);
if (raw_str == NULL)
return 0; /* Aborted. */
original_raw_string = strdup(raw_str);
if (c->command_arg_type == COMMAND_ARG_TYPE_STRING) {
*ret_string = original_raw_string;
free(raw_str);
return 1; // One argument
} else if (c->command_arg_type == COMMAND_ARG_TYPE_INT) {
*ret_string = original_raw_string; /* For the error status message */
// convert
if (strlen(raw_str) > 8) {
raw_str[8] = '\0';
}
rc = sscanf(raw_str, "%d", &raw_int); /* strtoimax(raw_str, NULL, 10); */
free(raw_str);
if (rc == 0) {
return -1;
}
*ret_int = raw_int;
return 1;
}
free(raw_str);
return 0;
} // editor_get_command_argument
void
command_move_cursor(int command_key) {
switch(command_key) {
case COMMAND_MOVE_CURSOR_UP:
/* Start macro */
undo_push_simple(COMMAND_MOVE_CURSOR_UP, COMMAND_MOVE_CURSOR_DOWN);
key_move_cursor(ARROW_UP);
/* End macro */
break;
case COMMAND_MOVE_CURSOR_DOWN:
undo_push_simple(COMMAND_MOVE_CURSOR_DOWN, COMMAND_MOVE_CURSOR_UP);
key_move_cursor(ARROW_DOWN);
break;
case COMMAND_MOVE_CURSOR_LEFT:
undo_push_simple(COMMAND_MOVE_CURSOR_LEFT, COMMAND_MOVE_CURSOR_RIGHT);
key_move_cursor(ARROW_LEFT);
break;
case COMMAND_MOVE_CURSOR_RIGHT:
undo_push_simple(COMMAND_MOVE_CURSOR_RIGHT, COMMAND_MOVE_CURSOR_LEFT);
key_move_cursor(ARROW_RIGHT);
break;
default:
break;
}
}
void
command_goto_line() {
int int_arg = 0;
char *char_arg = NULL;
int current_cy = E->cy;
struct command_str *c = command_get_by_key(COMMAND_GOTO_LINE);
if (c == NULL)
return;
int rc = editor_get_command_argument(c, &int_arg, &char_arg);
if (rc == 0) {
editor_set_status_message(STATUS_MESSAGE_ABORTED);
free(char_arg);
return;
} else if (rc == -1) {
editor_set_status_message(c->error_status, char_arg);
free(char_arg);
return;
}
if (int_arg > 0 && int_arg < E->numrows) {
E->cy = int_arg - 1;
command_refresh_screen();
}
free(char_arg);
undo_push_one_int_arg(COMMAND_GOTO_LINE, COMMAND_GOTO_LINE, current_cy);
}
void
command_goto_beginning_of_file() {
E->cy = 0;
E->cx = 0;
}
void
command_goto_end_of_file() {
E->cy = E->numrows;
E->cx = 0;
}
void
command_refresh_screen() {
E->rowoff = E->cy - (TERMINAL.screenrows / 2);
if (E->rowoff < 0)
E->rowoff = 0;
}
void
exec_command() {
char *command = NULL;
int entries;
unsigned int i = 0;
int int_arg = 0;
char *char_arg = NULL;
int found = 0;
char *tmp = editor_prompt("Command: %s", NULL);
if (tmp == NULL) {
editor_set_status_message(STATUS_MESSAGE_ABORTED);
return;
}
command = strdup(tmp);
free(tmp);
entries = command_entries();
for (i = 0; i < entries; i++) {
struct command_str *c = &COMMANDS[i];
if (!strncmp(c->command_str, command, strlen(command))) {
found = 1;
if ((c->command_arg_type == COMMAND_ARG_TYPE_INT
|| c->command_arg_type == COMMAND_ARG_TYPE_STRING)
/* FIXME remove exception... */
&& (c->command_key != COMMAND_SAVE_BUFFER
&& c->command_key != COMMAND_SAVE_BUFFER_AS)) {
/* should do union. */
// rc=1 is good: it's the number of successfully parsed arguments.
int rc = editor_get_command_argument(c, &int_arg, &char_arg);
if (rc == 0) { // Aborted
editor_set_status_message(STATUS_MESSAGE_ABORTED);
free(char_arg);
free(command);
return;
} else if (rc == -1) {
editor_set_status_message(c->error_status, char_arg);
free(char_arg);
free(command);
return;
}
}
switch (c->command_key) {
case COMMAND_SET_MODE:
if (syntax_set_mode_by_name(char_arg, 0) == 0) {
editor_set_status_message(c->success, char_arg);
} else {
editor_set_status_message(c->error_status, char_arg);
}
break;
case COMMAND_SET_TAB_STOP:
if (int_arg >= 2) {
undo_push_one_int_arg(COMMAND_SET_TAB_STOP, COMMAND_SET_TAB_STOP, E->tab_stop);
E->tab_stop = int_arg;
editor_set_status_message(c->success, int_arg);
} else {
editor_set_status_message(c->error_status, char_arg);
}
break;
case COMMAND_SET_AUTO_INDENT: {
int auto_indent_set = 0;
if (!strcasecmp(char_arg, "on")
|| !strcasecmp(char_arg, "t") || !strcasecmp(char_arg, "true")) {
E->is_auto_indent = 1;
auto_indent_set = 1;
} else if (!strcasecmp(char_arg, "off")
|| !!strcasecmp(char_arg, "f") || strcasecmp(char_arg, "false")) {
E->is_auto_indent = 0;
auto_indent_set = 1;
}
if (auto_indent_set)
editor_set_status_message(c->success, E->is_auto_indent ? "on" : "off");
else
editor_set_status_message(c->error_status, char_arg);
break;
}
case COMMAND_SET_HARD_TABS:
E->is_soft_indent = 0;
editor_set_status_message(c->success);
break;
case COMMAND_SET_SOFT_TABS:
E->is_soft_indent = 1;
editor_set_status_message(c->success);
break;
case COMMAND_SAVE_BUFFER:
case COMMAND_SAVE_BUFFER_AS:
editor_save(c->command_key);
break;
case COMMAND_MOVE_CURSOR_UP:
case COMMAND_MOVE_CURSOR_DOWN:
case COMMAND_MOVE_CURSOR_LEFT:
case COMMAND_MOVE_CURSOR_RIGHT:
command_move_cursor(c->command_key); // away (ref. helper f.)
break;
case COMMAND_UNDO:
undo();
break;
case COMMAND_INSERT_CHAR:
if (strlen(char_arg) > 0) {
int character = (int) char_arg[0];
command_insert_char(character);
} else {
editor_set_status_message(c->error_status);
}
break;
case COMMAND_DELETE_CHAR:
command_delete_char();
break;
case COMMAND_INSERT_NEWLINE:
command_insert_newline();
break;
case COMMAND_GOTO_LINE:
if (int_arg >= 0 && int_arg < E->numrows) {
undo_push_one_int_arg(COMMAND_GOTO_LINE, COMMAND_GOTO_LINE, E->cy);
E->cy = int_arg;
}
break;
case COMMAND_GOTO_BEGINNING_OF_FILE:
undo_push_one_int_arg(COMMAND_GOTO_BEGINNING_OF_FILE, COMMAND_GOTO_LINE, E->cy); /* TODO E->cx */
command_goto_beginning_of_file();
break;
case COMMAND_GOTO_END_OF_FILE:
undo_push_one_int_arg(COMMAND_GOTO_BEGINNING_OF_FILE, COMMAND_GOTO_LINE, E->cy); /* TODO E->cx */
command_goto_end_of_file();
break;
case COMMAND_REFRESH_SCREEN:
command_refresh_screen();
break;
case COMMAND_CREATE_BUFFER:
{
/* Note: for *Help* and *Compile* we set the type differently
and the buffer creation is not done here. */
struct command_str *c = command_get_by_key(COMMAND_CREATE_BUFFER);
(void) create_buffer(BUFFER_TYPE_FILE, 1, c->success, COMMAND_NO_CMD);
break;
}
case COMMAND_DELETE_BUFFER:
delete_current_buffer();
break;
case COMMAND_NEXT_BUFFER:
command_next_buffer();
break;
case COMMAND_PREVIOUS_BUFFER:
command_previous_buffer();
break;
case COMMAND_OPEN_FILE:
/* Note: is current buffer is empty, open into it.
Otherwise, create new buffer and open the file it.*/
command_open_file(char_arg);
break;
case COMMAND_MARK:
command_mark(c->success);
break;
case COMMAND_COPY_REGION:
command_copy_from_mark(c);
break;
case COMMAND_KILL_REGION:
command_kill_from_mark(); // calls copy_from with *KILL*
break;
default:
editor_set_status_message("Got command: '%s'", c->command_str);
break;
}
if (char_arg != NULL)
free(char_arg);
free(command);
return;
} /* if !strncasecmp */
} /* for */
if (!found) {
editor_set_status_message("Unknown command: '%s'");
}
free(command);
return;
}
<file_sep>#ifndef UNDO_H
#define UNDO_H
#include "const.h"
#include "terminal.h"
#include "output.h"
#include "clipboard.h"
struct undo_str {
int command_key; // orginal command
int undo_command_key; // undo command (if need to be run)
int cx;
int cy;
int orig_value; // set-tabs, auto-indent
struct clipboard *clipboard; // kill, yank
struct undo_str *next; // Because of stack.
};
struct undo_str *init_undo_stack(int init_command_key); // no more COMMAND_NO_KEY (ie command.h) any more.
void undo_debug_stack();
struct undo_str *alloc_and_init_undo(int command_key);
void undo_push_simple(int command_key, int undo_command_key);
void undo_push_one_int_arg(int command_key, int undo_command_key, int orig_value);
void undo_push_clipboard();
void undo();
#endif
| 5880e1c4819cc392b54e3b52af29114cdf7271b1 | [
"Markdown",
"C",
"Makefile"
] | 41 | C | jormis/kilo | 78ee18527a72b5ba9a4083683e73878976f634b3 | aaa914b9349bbbe78bd8ed321b1423856f815504 |
refs/heads/master | <repo_name>rolignu2/SivarDatabase<file_sep>/test.php
<?php
include 'Config.php';
include 'Database.php';
$db = new Database();
/**
*
* TESTEO DE INSERT
* **/
/* $table = "user_login";
$params = array(
"username" => "pepito" ,
"email" => "pepe",
"password" => "<PASSWORD>",
"estado" => 1,
"tipo" => 1
);
echo $db->Insert($table, $params); */
//TEST INSERT OK
/*$params = array(
"username" => "pepitorecargado" ,
"email" => "pepe",
"password" => "<PASSWORD>",
"estado" => 1,
"tipo" => 1
);
$table = "user_login";
echo $db->Update($table, $params, " iduser like 39");*/
//TEST UPDATE SET
echo $db->select("tabla", array(
"nombre" => "name",
"apellido" => "second name",
"valor" =>"values"
))->limit(0, 100)
->build_string();
echo "<br><br>";
echo $db->clean_build()->select("tabla" , array("nombre" , "apellido" , "valor"))->build_string();
echo "<br><br>";
echo $db->clean_build()->get_select("tabla", "valor" , GET_MAX)->build_string();
echo "<br><br>";
echo $db->clean_build()
->select("tabla")
->where("value1" , "string")
->build_string();
echo "<br><br>";
echo $db->clean_build()
->select("tabla")
->where("value1" , array( 'name1' , 'name2' , 'name3'))
->build_string();
echo "<br><br>";
echo $db->clean_build()
->select("tabla")
->where("value1" , 1)
->_or("value2", 3)
->build_string();
echo "<br><br>";
echo $db->clean_build()
->select("tabla")
->where("value1" , 1)
->_and("value2", 3 , "NOT LIKE")
->build_string();
| f9c6e6de4549a0bff4be8baccb83ea78bd652614 | [
"PHP"
] | 1 | PHP | rolignu2/SivarDatabase | c4844bef5c0af298ce2fd1619810a6fe494ba6bb | d050e8b9460ef8dd25dd784cde21f86d65a3c1de |
refs/heads/main | <repo_name>tshepoblom-dev/NopCommerceClickatellSMS<file_sep>/Nop.Plugin.Misc.Clickatell/Models/ClickatellModel.cs
using System;
using System.Collections.Generic;
using System.Text;
using Nop.Web.Framework.Models;
using Nop.Web.Framework.Mvc.ModelBinding;
namespace Nop.Plugin.Misc.Clickatell.Models
{
public class ClickatellModel : BaseNopModel
{
public int ActiveStoreScopeConfiguration { get; set; }
[NopResourceDisplayName("Plugins.Misc.Clickatell.Fields.Enabled")]
public bool Enabled { get; set; }
public bool Enabled_OverrideForStore { get; set; }
[NopResourceDisplayName("Plugins.Misc.Clickatell.Fields.ApiKey")]
public string ApiKey { get; set; }
[NopResourceDisplayName("Plugins.Misc.Clickatell.Fields.PhoneNumber")]
public string PhoneNumber { get; set; }
public bool PhoneNumber_OverrideForStore { get; set; }
[NopResourceDisplayName("Plugins.Misc.Clickatell.Fields.TestMessage")]
public string TestMessage { get; set; }
}
}
<file_sep>/Nop.Plugin.Misc.Clickatell/Controller/ClickatellController.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Nop.Core;
using Nop.Plugin.Misc.Clickatell.Models;
using Nop.Services.Configuration;
using Nop.Services.Localization;
using Nop.Services.Messages;
using Nop.Services.Plugins;
using Nop.Services.Security;
using Nop.Services.Stores;
using Nop.Web.Framework;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Mvc.Filters;
namespace Nop.Plugin.Misc.Clickatell.Controller
{
[AuthorizeAdmin]
[Area(AreaNames.Admin)]
public class ClickatellController : BasePluginController
{
#region Fields
private readonly ILocalizationService _localizationService;
private readonly IPluginService _pluginFinder;
private readonly ISettingService _settingService;
private readonly IPermissionService _permissionService;
private readonly IStoreContext _storeContext;
private readonly INotificationService _notificationService;
#endregion
#region Ctor
public ClickatellController(ILocalizationService localizationService,
IPermissionService permissionService,
IPluginService pluginFinder,
ISettingService settingService,
IStoreContext storeContext,
INotificationService notificationService,
IStoreService storeService)
{
this._localizationService = localizationService;
this._permissionService = permissionService;
this._pluginFinder = pluginFinder;
this._settingService = settingService;
this._storeContext = storeContext;
this._notificationService = notificationService;
}
#endregion
#region Methods
public IActionResult Configure()
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins))
return AccessDeniedView();
//load settings for a chosen store scope
var storeScope = _storeContext.ActiveStoreScopeConfiguration;
var clickatellSettings = _settingService.LoadSetting<ClickatellSettings>(storeScope);
var model = new ClickatellModel
{
Enabled = clickatellSettings.Enabled,
ApiKey = clickatellSettings.ApiKey,
PhoneNumber = clickatellSettings.PhoneNumber,
ActiveStoreScopeConfiguration = storeScope
};
if (storeScope > 0)
{
model.Enabled_OverrideForStore = _settingService.SettingExists(clickatellSettings, x => x.Enabled, storeScope);
model.PhoneNumber_OverrideForStore = _settingService.SettingExists(clickatellSettings, x => x.PhoneNumber, storeScope);
}
return View("~/Plugins/Misc.Clickatell/Views/Configure.cshtml", model);
}
[HttpPost, ActionName("Configure")]
[FormValueRequired("save")]
public IActionResult Configure(ClickatellModel model)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins))
return AccessDeniedView();
if (!ModelState.IsValid)
return Configure();
//load settings for a chosen store scope
var storeScope = _storeContext.ActiveStoreScopeConfiguration;
var clickatellSettings = _settingService.LoadSetting<ClickatellSettings>(storeScope);
//save settings
clickatellSettings.Enabled = model.Enabled;
clickatellSettings.ApiKey = model.ApiKey;
clickatellSettings.PhoneNumber = model.PhoneNumber;
/* We do not clear cache after each setting update.
* This behavior can increase performance because cached settings will not be cleared
* and loaded from database after each update */
_settingService.SaveSetting(clickatellSettings, x => x.ApiKey, storeScope, false);
_settingService.SaveSettingOverridablePerStore(clickatellSettings, x => x.Enabled, model.Enabled_OverrideForStore, storeScope, false);
_settingService.SaveSettingOverridablePerStore(clickatellSettings, x => x.PhoneNumber, model.PhoneNumber_OverrideForStore, storeScope, false);
//now clear settings cache
_settingService.ClearCache();
_notificationService.SuccessNotification(_localizationService.GetResource("Admin.Plugins.Saved"));
return Configure();
}
[HttpPost, ActionName("Configure")]
[FormValueRequired("test")]
public async Task<IActionResult> TestSms(ClickatellModel model)
{
if (!ModelState.IsValid)
return Configure();
var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName<ClickatellPlugin>("Misc.Clickatell", LoadPluginsMode.InstalledOnly);
if (pluginDescriptor == null)
throw new Exception("Cannot load the plugin");
var plugin = pluginDescriptor.Instance<ClickatellPlugin>();
if (plugin == null)
throw new Exception("Cannot load the plugin");
//load settings for a chosen store scope
var storeScope = _storeContext.ActiveStoreScopeConfiguration;
var clickatellSettings = _settingService.LoadSetting<ClickatellSettings>(storeScope);
//test SMS send
if (await plugin.SendSms(model.TestMessage, model.PhoneNumber, "sms"))
_notificationService.SuccessNotification(_localizationService.GetResource("Plugins.Misc.Clickatell.TestSuccess"));
else
_notificationService.ErrorNotification(_localizationService.GetResource("Plugins.Misc.Clickatell.TestFailed"));
return Configure();
}
#endregion
}
}
<file_sep>/README.md
# NopCommerceClickatellSMS
SMS Sender Plugin for NopCommerce
<file_sep>/Nop.Plugin.Misc.Clickatell/ClickatellPlugin.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Castle.Core.Logging;
using Newtonsoft.Json;
using Nop.Core;
using Nop.Services.Common;
using Nop.Services.Configuration;
using Nop.Services.Localization;
using Nop.Services.Orders;
using Nop.Services.Plugins;
using RestSharp;
namespace Nop.Plugin.Misc.Clickatell
{
public class ClickatellPlugin : BasePlugin, IMiscPlugin
{
#region Fields
private readonly ClickatellSettings _clickatellSettings;
private readonly ILogger _logger;
private readonly ISettingService _settingService;
private readonly IWebHelper _webHelper;
private readonly ILocalizationService _localizationService;
#endregion
public ClickatellPlugin(ClickatellSettings clickatellSettings,
ILogger logger,
IOrderService orderService,
ISettingService settingService,
IWebHelper webHelper,
IWorkContext workContext,
ILocalizationService localizationService)
{
this._clickatellSettings = clickatellSettings;
this._logger = logger;
this._settingService = settingService;
this._webHelper = webHelper;
this._localizationService = localizationService;
}
#region Methods
/// Send SMS
/// </summary>
/// <param name="message">Text</param>
/// <param name="to">recipient number</param>
/// <param name="channel">channel wherewith to send message, either SMS or WhatsApp</param>
/// <param name="settings">Clickatel config setting</param>
/// <returns>True if SMS was successfully sent; otherwise false</returns>
public async Task<bool> SendSms(string message, string to, string channel = "sms", ClickatellSettings settings = null)
{
try
{
var clickatellSettings = settings ?? _clickatellSettings;
if (!clickatellSettings.Enabled)
return false;
var client = new RestClient("https://platform.clickatell.com/v1/message");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", clickatellSettings.ApiKey);
request.AddHeader("Content-Type", "application/json");
List<object> messages = new List<object>();
messages.Add(new { channel = channel, content = message, to = to });
request.AddParameter("application/json", JsonConvert.SerializeObject(messages), ParameterType.RequestBody);
IRestResponse response = await client.ExecuteAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
_logger.Debug("Clickatell SMS OK: " + response.Content);
return true;
}
else
{
_logger.Debug(response.Content);
return false;
}
}
catch (Exception ex)
{
_logger.Error("Clickatell SMS Error: ", ex);
return false;
}
}
public async Task<bool> SendSms(string jsonBody, ClickatellSettings settings = null)
{
try
{
var clickatellSettings = settings ?? _clickatellSettings;
if (!clickatellSettings.Enabled)
return false;
var client = new RestClient("https://platform.clickatell.com/v1/message");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", clickatellSettings.ApiKey);
request.AddHeader("Content-Type", "application/json");
List<object> messages = new List<object>();
request.AddParameter("application/json", jsonBody, ParameterType.RequestBody);
IRestResponse response = await client.ExecuteAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
return true;
else
{
_logger.Debug(response.Content);
return false;
}
}
catch (Exception ex)
{
_logger.Error("Clickatell SMS to Vendors Error", ex);
return false;
}
}
public override string GetConfigurationPageUrl()
{
return $"{_webHelper.GetStoreLocation()}Admin/Clickatell/Configure";
}
/// <summary>
/// Install the plugin
/// </summary>
public override void Install()
{
//settings
_settingService.SaveSetting(new ClickatellSettings());
//locales
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.ApiKey", "API KEY");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.ApiKey.Hint", "API KEY HINT");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.ApiId", "API ID");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.ApiId.Hint", "Specify Clickatell API ID.");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Enabled", "Enabled");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Enabled.Hint", "Check to enable SMS provider.");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Password", "<PASSWORD>");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Password.Hint", "Specify Clickatell API password.");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.PhoneNumber", "Phone number");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.PhoneNumber.Hint", "Enter your phone number.");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.TestMessage", "Message text");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.TestMessage.Hint", "Enter text of the test message.");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Username", "Username");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Username.Hint", "Specify Clickatell API username.");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.SendTest", "Send");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.SendTest.Hint", "Send test message");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.TestFailed", "Test message sending failed");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Misc.Clickatell.TestSuccess", "Test message was sent");
base.Install();
}
/// <summary>
/// Uninstall the plugin
/// </summary>
public override void Uninstall()
{
//settings
_settingService.DeleteSetting<ClickatellSettings>();
//locales
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.ApiId");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.ApiId.Hint");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Enabled");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Enabled.Hint");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Password");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Password.Hint");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.PhoneNumber");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.PhoneNumber.Hint");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.TestMessage");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.TestMessage.Hint");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Username");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.Fields.Username.Hint");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.SendTest");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.SendTest.Hint");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.TestFailed");
_localizationService.DeletePluginLocaleResource("Plugins.Misc.Clickatell.TestSuccess");
base.Uninstall();
}
#endregion
}
}
<file_sep>/Nop.Plugin.Misc.Clickatell/EventConsumers/CustomerRegisteredEventConsumer.cs
using System;
using System.Collections.Generic;
using System.Text;
using Castle.Core.Logging;
using Nop.Core.Domain.Customers;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Events;
using Nop.Services.Plugins;
namespace Nop.Plugin.Misc.Clickatell.EventConsumers
{
public class CustomerRegisteredEventConsumer : IConsumer<CustomerRegisteredEvent>
{
private readonly IPluginService _pluginService;
private readonly ICustomerService _customerService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly ILogger _logger;
public CustomerRegisteredEventConsumer(IPluginService pluginService,
ICustomerService customerService,
IGenericAttributeService genericAttributeService,
ILogger logger)
{
_pluginService = pluginService;
_customerService = customerService;
_genericAttributeService = genericAttributeService;
_logger = logger;
}
public async void HandleEvent(CustomerRegisteredEvent eventMessage)
{
try
{
//check that plugin is installed
var pluginDescriptor = _pluginService.GetPluginDescriptorBySystemName<ClickatellPlugin>("Misc.Clickatell", LoadPluginsMode.InstalledOnly);
var plugin = pluginDescriptor?.Instance<ClickatellPlugin>();
var customer = _customerService.GetCustomerById(eventMessage.Customer.Id);
var phone = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.PhoneAttribute);
phone = FormatNumber(phone);
var success = await plugin?.SendSms($"Hi {customer.Username}, welcome to BuyBloem.com. Your account has been succesfully registered", phone, "sms");
}
catch (Exception ex)
{
_logger.Error("Clickatell.Error.CustomerRegisterEvent:" + ex.Message);
}
}
/// <summary>
/// Replaces the first '0' character in a phone number with '27'
/// Is static so as to be shareable across classes
/// </summary>
/// <param name="number">The number to action</param>
/// <returns></returns>
public string FormatNumber(string number)
{
char[] numArr = number.ToCharArray();
if (numArr.Length == 10 && numArr[0] == '0')
{
number = number.Remove(0, 1);
number = number.Insert(0, "27");
}
return number;
}
}
}
<file_sep>/Nop.Plugin.Misc.Clickatell/EventConsumers/OrderRefundedEventConsumer.cs
using System;
using System.Collections.Generic;
using System.Text;
using Castle.Core.Logging;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Orders;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Events;
using Nop.Services.Orders;
using Nop.Services.Plugins;
namespace Nop.Plugin.Misc.Clickatell.EventConsumers
{
public class OrderRefundedEventConsumer : IConsumer<OrderRefundedEvent>
{
private readonly IPluginService _pluginFinder;
private readonly ICustomerService _customerService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly IOrderService _orderService;
private readonly ILogger _logger;
public OrderRefundedEventConsumer(IPluginService pluginService, ILogger logger)
{
_pluginFinder = pluginService;
_logger = logger;
}
public async void HandleEvent(OrderRefundedEvent eventMessage)
{
try
{
//check that plugin is installed
var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName<ClickatellPlugin>("Misc.Clickatell", LoadPluginsMode.InstalledOnly);
var plugin = pluginDescriptor?.Instance<ClickatellPlugin>();
var order = eventMessage.Order;
//order note
if (order != null)
{
var customer = _customerService.GetCustomerById(order.CustomerId);
var phone = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.PhoneAttribute);
phone = OrderPlacedEventConsumer.FormatNumber(phone);
var success = await plugin?.SendSms($"Dear valued customer, your refund request for order #{order.Id} of R{order.OrderTotal} been processed - buybloem.com", phone, "sms");
if (success)
{
order.OrderNotes.Add(new OrderNote()
{
Note = $"\"Order Refunded\" SMS alert {customer.Email} has been sent",
DisplayToCustomer = false,
CreatedOnUtc = DateTime.UtcNow
});
_orderService.UpdateOrder(order);
}
}
}
catch (Exception ex)
{
_logger.Error("Clickatell.Error.OrderRefundedEvent:" + ex.Message);
}
}
}
}
<file_sep>/Nop.Plugin.Misc.Clickatell/EventConsumers/OrderCancelledEventConsumer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Core.Logging;
using Newtonsoft.Json;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Orders;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Events;
using Nop.Services.Orders;
using Nop.Services.Plugins;
using Nop.Services.Vendors;
namespace Nop.Plugin.Misc.Clickatell.EventConsumers
{
public class OrderCancelledEventConsumer : IConsumer<OrderCancelledEvent>
{
#region Fields
private readonly IPluginService _pluginFinder;
private readonly ICustomerService _customerService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly IOrderService _orderService;
private readonly IVendorService _vendorService;
private readonly IAddressService _addressService;
private readonly ClickatellSettings _clickatellSettings;
private readonly ILogger _logger;
#endregion
#region Ctor
public OrderCancelledEventConsumer(IPluginService pluginFinder,
ICustomerService customerService,
IGenericAttributeService genericAttributeService,
IOrderService orderService,
IVendorService vendorService,
IAddressService addressService,
ILogger logger,
ClickatellSettings clickatellSettings)
{
this._pluginFinder = pluginFinder;
this._customerService = customerService;
this._genericAttributeService = genericAttributeService;
this._orderService = orderService;
this._vendorService = vendorService;
this._addressService = addressService;
this._clickatellSettings = clickatellSettings;
_logger = logger;
}
#endregion
#region Methods
/// <summary>
/// Handles the event.
/// </summary>
/// <param name="eventMessage">The event message.</param>
public void HandleEvent(OrderCancelledEvent eventMessage)
{
try
{
//check that plugin is installed
var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName<ClickatellPlugin>("Misc.Clickatell", LoadPluginsMode.InstalledOnly);
var plugin = pluginDescriptor?.Instance<ClickatellPlugin>();
var order = eventMessage.Order;
if (order != null)
{
//Send SMS to customer
SmsToCustomer(plugin, order);
//Send SMS to Vendor
SmsToVendors(plugin, order);
SmsToAdmin(plugin, order);
}
}
catch (Exception ex)
{
_logger.Error("Clickatell.Error.OrderCancelledEvent:" + ex.Message);
}
}
async void SmsToAdmin(ClickatellPlugin plugin, Order order, ClickatellSettings settings = null)
{
var adminNumber = FormatNumber(_clickatellSettings.PhoneNumber);
var success = await plugin?.SendSms($"Hi Admin, new order #{order.Id} R{order.OrderTotal} has been PAID", adminNumber);
}
async void SmsToCustomer(ClickatellPlugin plugin, Order order)
{
var customer = _customerService.GetCustomerById(order.CustomerId);
var phone = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.PhoneAttribute);
phone = FormatNumber(phone);
var success = await plugin?.SendSms($"Dear valued shopper, your order #{order.Id} of R{order.OrderTotal} on BuyBloem.com has been Cancelled.", phone, "sms");
if (success)
{
order.OrderNotes.Add(new OrderNote()
{
Note = $"\"Order Cancelled\" SMS alert {customer.Email} has been sent",
DisplayToCustomer = false,
CreatedOnUtc = DateTime.UtcNow
});
_orderService.UpdateOrder(order);
}
}
async void SmsToVendors(ClickatellPlugin plugin, Order order)
{
var vendorDict = GetVendorPhoneAndOrderItems(order);
List<object> messages = new List<object>();
foreach (var dictItem in vendorDict)
{
messages.Add(new { channel = "sms", content = $"Hello vendor, Order #{order.Id} has been Cancelled. Items: {dictItem.Value}", to = dictItem.Key });
}
var jsonBody = JsonConvert.SerializeObject(messages);
var success = await plugin?.SendSms(jsonBody);
if (success)
{
order.OrderNotes.Add(new OrderNote()
{
Note = $"\"Order Cancelled\" SMS alert to vendors has been sent",
DisplayToCustomer = false,
CreatedOnUtc = DateTime.UtcNow
});
_orderService.UpdateOrder(order);
}
}
/// <summary>
/// Replaces the first '0' character in a phone number with '27'
/// Is static so as to be shareable across classes
/// </summary>
/// <param name="number">The number to action</param>
/// <returns></returns>
public string FormatNumber(string number)
{
char[] numArr = number.ToCharArray();
if (numArr.Length == 10 && numArr[0] == '0')
{
number = number.Remove(0, 1);
number = number.Insert(0, "27");
}
return number;
}
/// <summary>
/// scans for vendorIds in order
/// </summary>
/// <param name="order"></param>
/// <returns></returns>
public List<int> GetVendorsFromOrder(Order order)
{
var orderItems = order.OrderItems.ToList();
var vendorIds = new List<int>();
orderItems.ForEach((orderItem) => { vendorIds.Add(orderItem.Product.VendorId); });
return vendorIds.Distinct().ToList();
}
/// <summary>
/// retrieves vendor phone numbers and list of items bought from them
/// </summary>
/// <param name="order">the order processed</param>
/// <returns></returns>
Dictionary<string, string> GetVendorPhoneAndOrderItems(Order order)
{
var dictionary = new Dictionary<string, string>();
var vendorIds = GetVendorsFromOrder(order);
vendorIds.ForEach((vendorId) =>
{
var vendor = _vendorService.GetVendorById(vendorId);
var vendorAddress = _addressService.GetAddressById(vendor.AddressId);
var vendorPhone = FormatNumber(vendorAddress.PhoneNumber);
var items = order.OrderItems.ToList();
var vendorItems = items.Where(x => x.Product.VendorId == vendorId).ToList();
var itemsTotal = vendorItems.Select(x => x.PriceInclTax).Sum();
StringBuilder sb = new StringBuilder();
vendorItems.ForEach(item => { sb.Append(item.Product.Name + ", "); });
dictionary.Add(vendorPhone, sb.ToString());
});
return dictionary;
}
#endregion
}
}
<file_sep>/Nop.Plugin.Misc.Clickatell/ClickatellSettings.cs
using System;
using System.Collections.Generic;
using System.Text;
using Nop.Core.Configuration;
namespace Nop.Plugin.Misc.Clickatell
{
public class ClickatellSettings : ISettings
{
/// <summary>
/// Gets or sets the value indicting whether this SMS provider is enabled
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// Gets or sets the Clickatell API Key
/// </summary>
public string ApiKey { get; set; }
/// <summary>
/// Gets or sets the store owner phone number
/// </summary>
public string PhoneNumber { get; set; }
/// <summary>
/// Gets or sets the store owner phone number
/// </summary>
public string TestMessage { get; set; }
}
}
| ddc5d992f78e479e4bb2173c4022d41c8cb5c79a | [
"Markdown",
"C#"
] | 8 | C# | tshepoblom-dev/NopCommerceClickatellSMS | abf2deb0638405cd35c6364cf328b04313923d63 | a537837392f2502f31e70c6d7afaa7c3d5db6b6d |
refs/heads/main | <repo_name>syozo1201/DWC_PF_-<file_sep>/app/models/user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :omniauthable, omniauth_providers: [:twitter]
attachment :profile_image
attr_accessor :twitter_image_url
has_many :posts, dependent: :destroy
has_many :favorites, dependent: :destroy
has_many :post_comments, dependent: :destroy
has_many :sns_credentials, dependent: :destroy
# 自分がフォローされる(被フォロー)側の関係性
has_many :reverse_of_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy
# 自分がフォローする(与フォロー)側の関係性
has_many :relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
# 被フォロー関係を通じて参照→自分をフォローしている人
has_many :followers, through: :reverse_of_relationships, source: :follower
# 与フォロー関係を通じて参照→自分がフォローしている人
has_many :followings, through: :relationships, source: :followed
def follow(user_id)
relationships.create(followed_id: user_id)
end
def unfollow(user_id)
relationships.find_by(followed_id: user_id).destroy
end
def following?(user)
followings.include?(user)
end
def self.from_omniauth(auth)
sns = SnsCredential.where(provider: auth.provider, uid: auth.uid).first_or_create
user = User.where(email: auth.info.email).first_or_initialize(
name: auth.info.name,
email: auth.info.email
)
user.twitter_image_url = auth.info.image
if user.persisted?
sns.user = user
sns.save
end
{ user: user, sns: sns }
end
validates :name, presence: true
validates :name, length: { minimum: 1, maximum: 20 }
end
<file_sep>/README.md
# お笑いびより
## サイト概要
自分が面白いと思った画像を共有できるサイト
### サイトテーマ
笑顔ををもっと増やそう
### テーマを選んだ理由
人間誰しも生活の中で大なり小なり面白いと思う物に出会うはずです。
そんなみなさんの感性の違いを感じられるような場を作ろうと思い、このテーマにいたしました。
### ターゲットユーザ
全ての方
### 主な利用シーン
生活の中でくすっと来る物があったら投稿しましょう
## チャレンジ要素一覧
https://docs.google.com/spreadsheets/d/1LHkDHbEPq17tjKbGB-YzsG21pktu64EnjN02IORqql8/edit#gid=0
## 開発環境
- OS:Linux(CentOS)
- 言語:HTML,CSS,JavaScript,Ruby,SQL
- フレームワーク:Ruby on Rails
- JSライブラリ:jQuery
- IDE:Cloud9
## 使用素材
<file_sep>/config/routes.rb
Rails.application.routes.draw do
get 'homes/about'
devise_for :users, controllers: {
omniauth_callbacks: 'users/omniauth_callbacks',
registrations: 'users/registrations'
}
root 'homes#top'
get '/search' => 'searchs#search'
resources :users, only: [:index, :show, :edit, :update] do
resource :relationships, only: [:create, :destroy]
get 'followings' => 'relationships#followings', as: 'followings'
get 'followers' => 'relationships#followers', as: 'followers'
end
resources :posts do
resource :favorites, only: [:create, :destroy, :index]
resources :post_comments, only: [:create, :destroy, :show]
end
get 'post/ranking' => 'posts#rank'
get 'post/random' => 'posts#random'
end
<file_sep>/app/controllers/searchs_controller.rb
class SearchsController < ApplicationController
def search
@posts = Post.joins(:user).where('title LIKE ? OR post_content LIKE ? OR name LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%", "%#{params[:search]}%") if params[:search].present?
@posts = Kaminari.paginate_array(@posts).page(params[:page]).per(5)
end
end
<file_sep>/app/controllers/homes_controller.rb
class HomesController < ApplicationController
def top
if ActiveRecord::Base.connection_config[:adapter] == 'sqlite3' #ローカル。DBで判断
@posts = Post.order("RANDOM()").limit(3)
else
@posts = Post.order("RAND()").limit(3)
end
end
def about
end
end
| 850ebeb73b75be5a8f3c7ef5d41e4e848e8bc6c4 | [
"Markdown",
"Ruby"
] | 5 | Ruby | syozo1201/DWC_PF_- | 058ba05b158394ee1c0b67d1a83950a0295e5dbc | d7b9b0b268b6459c20c08a67b3d904544dce3a18 |
refs/heads/master | <repo_name>OsamaAhmed1999/Inheritance<file_sep>/main.cpp
#include <iostream>
#include "AdjTableLamp.h"
using namespace std;
int main()
{
AdjTableLamp *Lamp = new AdjTableLamp();
cout << *Lamp << endl;
Lamp->print(cout);
Lamp->dim();
Lamp->dim();
Lamp->dim();
Lamp->print(cout);
Lamp->press_switch();
Lamp->print(cout);
system("pause");
}<file_sep>/TableLamp.h
#include <iostream>
using namespace std;
class TableLamp
{
public:
//CONSTRUCTOR
TableLamp();
//GETTERS
//state getonoff()
//{
// this->on_off = ON;
//}
//SETTERS
//MEMBER FUNCTIONS
void press_switch();
//DISPLAY FUNCTION
friend ostream& operator << (ostream& output , const TableLamp& object);
//OPERATOR OVERLOADING
protected:
private:
enum state{ON,OFF}on_off;
};
TableLamp::TableLamp()
{
this->on_off = ON;
}
void TableLamp::press_switch()
{
on_off = (on_off == ON)? OFF:ON;
}
ostream& operator << (ostream& output , const TableLamp& object)
{
return((object.on_off == 0)? output << "Lamp is ON" : output << "Lamp is OFF");
}<file_sep>/AdjTableLamp.h
#include <iostream>
#include "TableLamp.h"
using namespace std;
class AdjTableLamp : public TableLamp
{
public:
//CONSTRUCTOR
AdjTableLamp();
//GETTERS
//SETTERS
//MEMBER FUNCTIONS
void dim();
//DISPLAY FUNCTION
void print(ostream& output);
//OPERATOR OVERLOADING
protected:
private:
float brightness;
};
AdjTableLamp::AdjTableLamp()
{
this->brightness = 1.0;
}
void AdjTableLamp::dim()
{
if(brightness > 0.1)
{
brightness = brightness - 0.1;
}
}
void AdjTableLamp::print(ostream& output)
{
output << *this << " with Brightness " << brightness << endl;
} | 7be5f17ddc4c4992c743871417dc1c9c1efd5775 | [
"C++"
] | 3 | C++ | OsamaAhmed1999/Inheritance | 8eff7761f0dcc1ea21a689051462a69c7cf5dce4 | 5a3f3c28a16734f0cfa4f82fbf7e577b071d563b |
refs/heads/master | <repo_name>InfiniteDivs/defistation-web<file_sep>/src/components/defiList/DefiList.js
import React, { Fragment, Suspense, useState, useEffect } from "react";
import { observer, inject } from 'mobx-react';
import { useHistory, useLocation } from 'react-router-dom';
import ReactTooltip from 'react-tooltip';
import useStores from '../../useStores';
import _ from "lodash";
import '../../App.css';
import defistationApplicationList from "../../defistationApplicationList.json";
import { numberWithCommas, capitalize, replaceAll, getOfficialDefiName, getOfficialCategoryName, getCurrencyDigit, getCurrencyUnit, convertDateFormat2, generateRandom } from '../../util/Util';
// table icon
import rankIcon1 from "../../assets/images/rank1@2x.png";
import rankIcon2 from "../../assets/images/rank2@2x.png";
import rankIcon3 from "../../assets/images/rank3@2x.png";
import verifiedIcon from "../../assets/images/verifiedic.svg";
import noVerifiedIcon from "../../assets/images/verifiedic_none.svg";
import questionIcon from "../../assets/images/question_ic.svg";
// coin image
import defaultIcon from "../../assets/images/defiLogo/project-none@2x.png";
import acryptos from "../../assets/images/coins/acryptos.png";
import anyswap from "../../assets/images/coins/anyswap.png";
import autofarm from "../../assets/images/coins/auto.png";
import bakeryswap from "../../assets/images/coins/bakery.png";
import bdollar from "../../assets/images/coins/bdollar.png";
import beefyfinance from "../../assets/images/coins/beefy-finance.png";
import bnexchange from "../../assets/images/coins/bnex.svg";
import bscswap from "../../assets/images/coins/bscswap.png";
import bstablefinance from "../../assets/images/coins/bstable.png";
import burgerswap from "../../assets/images/coins/burger-swap.png";
import cberry from "../../assets/images/coins/cberry.png";
// import creamfinance from "../../assets/images/coins/cream-finance.png";
import creamfinance from "../../assets/images/defiLogo/creamfinance@2x.png";
import fortube from "../../assets/images/coins/fortube.png";
import fryworld from "../../assets/images/coins/fryworld.png";
import jetfuel from "../../assets/images/coins/jetfuel.png";
import julswap from "../../assets/images/coins/julswap.png";
import milk from "../../assets/images/coins/milk.png";
import narwhalswap from "../../assets/images/coins/narwhalswap.png";
import pancakebunny from "../../assets/images/coins/pancakebunny.png";
import pancake from "../../assets/images/coins/pancakeswap.png";
import qian from "../../assets/images/coins/qian-kun.png";
import spartanprotocol from "../../assets/images/coins/spartan-protocol.png";
import stormswap from "../../assets/images/coins/storm.png";
import thugs from "../../assets/images/coins/thugs.png";
import venus from "../../assets/images/coins/venus.png";
import MidasDollar from "../../assets/images/defiLogo/MidasDollar@2x.png";
import LinearFinance from "../../assets/images/defiLogo/LinearFinance@2x.png";
import KEEP3RBSC from "../../assets/images/defiLogo/KEEP3RBSC@2x.png";
import kebab from "../../assets/images/defiLogo/kebab@2x.png";
import goosefinance from "../../assets/images/defiLogo/goosefinance@2x.png";
import CrowFinance from "../../assets/images/defiLogo/CrowFinance@2x.png";
import CheeseSwap from "../../assets/images/defiLogo/CheeseSwap@2x.png";
import bscex from "../../assets/images/defiLogo/bscex@2x.png";
import derifinance from "../../assets/images/defiLogo/derifinance@2x.png";
import beltfinance from "../../assets/images/defiLogo/belt@2x.png";
import bifi from "../../assets/images/defiLogo/bififinance@2x.png";
import blackholeswap from "../../assets/images/defiLogo/blackholeswap@2x.png";
import multiplier from "../../assets/images/defiLogo/multiplier@2x.png";
import pikafinance from "../../assets/images/defiLogo/pikafinance@2x.png";
import bscrunner from "../../assets/images/defiLogo/bscrunner@2x.png";
import ellipsisfinance from "../../assets/images/defiLogo/ellipsisfinance@2x.png";
import demex from "../../assets/images/defiLogo/demex@2x.png";
import dodo from "../../assets/images/defiLogo/dodo@2x.png";
import helmet from "../../assets/images/defiLogo/helmet@2x.png";
import ariesfinancial from "../../assets/images/defiLogo/ariesfinancial@2x.png";
import alphahomora from "../../assets/images/defiLogo/alphahomora@2x.png";
import cobaltfinance from "../../assets/images/defiLogo/cobaltfinance@2x.png";
import swampfinance from "../../assets/images/defiLogo/swampfinance@2x.png";
const DefiList = observer((props) => {
const { global } = useStores();
const history = useHistory();
const [responseError, setResponseError] = useState();
const [defiListTableCode, setDefiListTableCode] = useState();
const [volumeTag, setVolumeTag] = useState();
function findLogoUrl(defiName) {
// defistationApplicationList 에서 Official Project Name 이 defiName와 일치하는 것 찾기
// 예외처리
if (defiName == "pancake") {
defiName = "PancakeSwap";
}
let logoUrl = "";
for (var i = 0; i < defistationApplicationList.length; i++) {
if (defistationApplicationList[i]["Official Project Name"] == defiName) {
logoUrl = defistationApplicationList[i]["Project Logo URL (68px*68px png ONLY. Given link should directly DISPLAY Logo image without any BACKGROUND. Google drive link is NOT accepted.)"];
break;
}
}
return logoUrl;
}
function findCategoryName(defiName) {
// defistationApplicationList 에서 Official Project Name 이 defiName와 일치하는 것 찾기
// 예외처리
if (defiName == "pancake") {
defiName = "PancakeSwap";
}
let categoryName = "";
for (var i = 0; i < defistationApplicationList.length; i++) {
if (defistationApplicationList[i]["Official Project Name"] == defiName) {
categoryName = defistationApplicationList[i]["Project Category"];
break;
}
}
return categoryName;
}
function selectCoinImg(defiName) {
let resultImg = "";
switch (defiName) {
case "pancake":
resultImg = pancake;
break;
case "bscSwap":
resultImg = bscswap;
break;
case "Spartan Protocol":
resultImg = spartanprotocol;
break;
case "Burger Swap":
resultImg = burgerswap;
break;
case "Stakecow":
resultImg = milk;
break;
case "Cream Finance":
resultImg = creamfinance;
break;
case "Bakery Swap":
resultImg = bakeryswap;
break;
case "ForTube":
resultImg = fortube;
break;
case "FryWorld":
resultImg = fryworld;
break;
case "beefy.finance":
resultImg = beefyfinance;
break;
case "Narwhalswap":
resultImg = narwhalswap;
break;
case "STORMSWAP":
resultImg = stormswap;
break;
case "BnEX":
resultImg = bnexchange;
break;
case "bStable.finance":
resultImg = bstablefinance;
break;
case "QIAN":
resultImg = qian;
break;
case "PancakeBunny":
resultImg = pancakebunny;
break;
case "JulSwap":
resultImg = julswap;
break;
case "AnySwap":
resultImg = anyswap;
break;
case "Venus":
resultImg = venus;
break;
case "Thugs":
resultImg = thugs;
break;
case "CBerry":
resultImg = cberry;
break;
case "Jetfuel.Finance":
resultImg = jetfuel;
break;
case "ACryptoS":
resultImg = acryptos;
break;
case "bDollar Protocol":
resultImg = bdollar;
break;
case "Autofarm":
resultImg = autofarm;
break;
case "Kebab Finance":
resultImg = kebab;
break;
case "KEEP3R BSC NETWORK":
resultImg = KEEP3RBSC;
break;
case "CheeseSwap":
resultImg = CheeseSwap;
break;
case "Midas Dollar":
resultImg = MidasDollar;
break;
case "CrowFinance":
resultImg = CrowFinance;
break;
case "Goose Finance":
resultImg = goosefinance;
break;
case "BSCex":
resultImg = bscex;
break;
case "Linear Finance":
resultImg = LinearFinance;
break;
case "Deri Protocol":
resultImg = derifinance;
break;
case "Belt Finance":
resultImg = beltfinance;
break;
case "BiFi":
resultImg = bifi;
break;
case "Multi-Chain Lend (MCL)":
resultImg = multiplier;
break;
case "BlackHoleSwap":
resultImg = blackholeswap;
break;
case "Pika Finance":
resultImg = pikafinance;
break;
case "Bscrunner":
resultImg = bscrunner;
break;
case "Ellipsis Finance":
resultImg = ellipsisfinance;
break;
case "DODO":
resultImg = dodo;
break;
case "Demex":
resultImg = demex;
break;
case "Helmet":
resultImg = helmet;
break;
case "ARIES FINANCIAL":
resultImg = ariesfinancial;
break;
case "Alpha Homora":
resultImg = alphahomora;
break;
case "Cobalt.finance":
resultImg = cobaltfinance;
break;
case "SwampFinance":
resultImg = swampfinance;
break;
default:
resultImg = findLogoUrl(defiName);
break;
}
return resultImg;
}
const [urlFlag1, setUrlFlag1] = useState(false);
async function getDefiList() {
if (urlFlag1) return;
setUrlFlag1(true);
console.count("getDefiListCall");
// if (global.chartDataDetails == null) return;
// console.log("global.chartDataDetails.pancake[1603274430]: ", global.chartDataDetails.pancake[1603274430]);
const res = await fetch(global.defistationApiUrl + "/defiTvlList", {
method: 'GET',
headers: {
Authorization: global.auth
}
});
res
.json()
.then(res => {
// console.log("res: ", res);
let tableCodeArr = [];
let rankingCount = 1;
// AD random
let adNum = generateRandom(0, res.length);
for (var i = 0; i < res.length; i++) {
let chainName;
// let rankNum = i + 1;
let rankNum = rankingCount;
let defiName = res[i].name;
let coinImg = selectCoinImg(res[i].name);
// beefy.finance 같은 경우 기호, 공백 제거(url 용도)
defiName = replaceAll(defiName, ".", "");
defiName = replaceAll(defiName, " ", "");
defiName = defiName.toLowerCase();
if (i == 0) {
rankNum = <img src={rankIcon1} style={{ "width": "24px", marginTop: "4px" }} />;
} else if (i == 1) {
rankNum = <img src={rankIcon2} style={{ "width": "24px", marginTop: "4px" }} />;
} else if (i == 2) {
rankNum = <img src={rankIcon3} style={{ "width": "24px", marginTop: "4px" }} />;
}
if (res[i].chain == "bsc") {
chainName = "BSC";
} else {
chainName = res[i].chain;
}
// 현재 기준 변화량
let change24hValue = res[i].tvlPercentChange24h;
let change24hTag;
if (change24hValue == 1) {
// 100% 는 표기하지 않는다
change24hTag = <span>-</span>;
} else {
if (change24hValue > 0) {
// +
change24hTag = <span className="textGreen">+{(change24hValue * 100).toFixed(2)}%</span>;
} else if (change24hValue == 0) {
change24hTag = <span>{(change24hValue * 100).toFixed(2)}%</span>;
} else if (change24hValue < 0) {
change24hTag = <span className="textRed">{(change24hValue * 100).toFixed(2)}%</span>;
}
}
let verifiedTag;
if (res[i].verified) {
verifiedTag = <img src={verifiedIcon} />
} else {
verifiedTag = <img src={noVerifiedIcon} />
}
// Last updated(UTC) 표현에서 앞에 20, 뒤에 초 제거
let tempDate;
// console.log("res[i].lastUpdated: ", res[i].lastUpdated);
if (res[i].lastUpdated == 0) {
tempDate = "-";
} else {
tempDate = new Date(res[i].lastUpdated * 1000).toISOString().replace(/T/, ' ').replace(/\..+/, '');
tempDate = tempDate.substring(0, tempDate.length - 3);
}
// tvl
let digit = getCurrencyDigit(res[i].lockedUsd);
let currencyUnit = getCurrencyUnit(res[i].lockedUsd);
let currencyNum;
// tvl이 M 이하 단위인 경우 소숫점 1자리만, B 단위 이상은 소숫점 2자리로 표현
if (digit <= 1000000) {
currencyNum = (res[i].lockedUsd / digit).toFixed(1) * 1;
} else {
currencyNum = (res[i].lockedUsd / digit).toFixed(2) * 1;
}
// volume
let digit2 = getCurrencyDigit(res[i].volume);
let currencyUnitForVolume = getCurrencyUnit(res[i].volume);
let currencyVolume = (res[i].volume / digit2).toFixed(2) * 1;
let volumeStr;
if (res[i].volume > 0) {
volumeStr = "$ " + currencyVolume + currencyUnitForVolume;
} else {
volumeStr = "-";
}
if (res[i].contractNum == 0) {
// tableCodeArr.push(
// <tr key={i}>
// <td>{rankNum}</td>
// <td>{verifiedTag}</td>
// <td>{getOfficialDefiName(res[i].name)}</td>
// <td>{chainName}</td>
// <td>{getOfficialCategoryName(res[i].category)}</td>
// {/* <td></td> */}
// <td></td>
// <td></td>
// <td></td>
// <td><span className="comingSoon">Coming Soon</span></td>
// </tr>
// );
} else {
rankingCount++;
// 괄호 안 내용 제거
let tempCategory = findCategoryName(res[i].name);
tempCategory = tempCategory.replace(/\(.*\)/gi, '');
if (tempCategory == "") {
tempCategory = "Other";
}
if (res[i].name == "Autofarm") {
console.log("tempCategory: ", tempCategory);
}
// if (i == adNum) {
if (getOfficialDefiName(res[i].name) == "BakerySwap") {
// AD: 가장 앞에
tableCodeArr.unshift(
<tr className="defiListTableTr" onClick={() => movePage("/" + defiName)}>
<td>Ad</td>
<td><img class="tokenImg" src={coinImg} onError={(e)=>{e.target.onerror = null; e.target.src=defaultIcon}} /></td>
{/* <td>{coinImg}</td> */}
<td>{getOfficialDefiName(res[i].name)}</td>
<td>{verifiedTag}</td>
<td>{chainName}</td>
{/* <td>{getOfficialCategoryName(res[i].category)}</td> */}
<td>{tempCategory}</td>
{/* <td>{res[i].contractNum}</td> */}
<td>{res[i].volume > 0 ? volumeStr : <div><p data-tip="24hr trading volume hasn't been posted by project team."> {volumeStr} </p><ReactTooltip /></div>}</td>
<td>$ {numberWithCommas(res[i].lockedUsd)}</td>
<td>$ {currencyNum + currencyUnit}</td>
<td>{change24hTag}</td>
{/* <td>{tempDate}</td> */}
</tr>
);
}
tableCodeArr.push(
<tr key={i} className="defiListTableTr" onClick={() => movePage("/" + defiName)}>
<td>{rankNum}</td>
<td><img class="tokenImg" key={i} src={coinImg} onError={(e)=>{e.target.onerror = null; e.target.src=defaultIcon}} /></td>
{/* <td>{coinImg}</td> */}
<td>{getOfficialDefiName(res[i].name)}</td>
<td>{verifiedTag}</td>
<td>{chainName}</td>
{/* <td>{getOfficialCategoryName(res[i].category)}</td> */}
<td>{tempCategory}</td>
{/* <td>{res[i].contractNum}</td> */}
<td>
{res[i].volume > 0 ? volumeStr : <div><p data-tip="24hr trading volume hasn't been posted by project team."> {volumeStr} </p><ReactTooltip /></div>}
</td>
<td>$ {numberWithCommas(res[i].lockedUsd)}</td>
<td>$ {currencyNum + currencyUnit}</td>
<td>{change24hTag}</td>
{/* <td>{tempDate}</td> */}
</tr>
);
}
}
console.count("DefiList Call");
// console.log("tableCodeArr: ", tableCodeArr);
setDefiListTableCode(tableCodeArr);
})
.catch(err => setResponseError(err));
}
function movePage(path) {
history.push(path);
}
useEffect(() => {
getDefiList();
return () => {
};
}, [global.chartDataDetails])
return (
<div className="defiList">
<table className="defiListTable">
<thead className="defiListTableHead">
<tr>
<th>Rank</th>
<th></th>
<th>Name</th>
<th>
<ul className="defiListTableHeadCell">
<li>Audit</li>
{/* <li><img src={questionIcon} onClick={() => movePage("/about")} /></li> */}
</ul>
</th>
<th>Chain</th>
<th>Category</th>
{/* <th>Contract(#)</th> */}
<th>Volume 24h</th>
<th>Locked</th>
<th>Locked</th>
<th>
<ul className="defiListTableHeadCellRight">
<li>Change 24h</li>
<li className="change24h"><img src={questionIcon} onClick={() => movePage("/about")} /></li>
</ul>
</th>
{/* <th>Last updated(UTC)</th> */}
</tr>
</thead>
<tbody className="defiListTableBody">
{defiListTableCode}
</tbody>
</table>
<br />
</div>
);
})
export default DefiList;<file_sep>/src/components/miniCards/MiniCards.js
import React, { Fragment, Suspense, useState, useEffect } from "react";
import { observer, inject } from 'mobx-react';
import { useHistory, useLocation } from 'react-router-dom';
import useStores from '../../useStores';
import { numberWithCommas, capitalize, replaceAll, getCurrencyUnit, getCurrencyDigit } from '../../util/Util';
import '../../App.css';
import MiniCard from './miniCard/MiniCard';
const MiniCards = observer((props) => {
const { global } = useStores();
const [responseError, setResponseError] = useState();
const [response, setResponse] = useState({});
const [miniCardTitle3, setMiniCardTitle3] = useState();
const [miniCardData3, setMiniCardData3] = useState("");
const [totalBnbLockedNum, setTotalBnbLockedNum] = useState(0);
const [projectNum, setProjectNum] = useState(0);
const [lockedBnbAmount, setLockedBnbAmount] = useState();
const [tvl1DayPercentTag, setTvl1DayPercentTag] = useState();
const [urlFlag1, setUrlFlag1] = useState(false);
const [urlFlagDetail, setUrlFlagDetail] = useState("");
async function getTotalBnbLocked(defiName) {
if (defiName == "DeFi") {
if (urlFlag1) return;
}
setUrlFlag1(true);
// console.log("getTotalBnbLocked 함수 시작");
let urlStr = "";
if (defiName == "DeFi") {
// urlStr = "all";
urlStr = "all?days=30";
} else {
// urlStr = defiName;
urlStr = defiName + "?days=30";
}
// detail
if (urlFlagDetail == urlStr) return;
setUrlFlagDetail(urlStr);
// console.log("urlStr: ", urlStr);
if (urlStr == "" || urlStr == "?days=30") return;
const res = await fetch(global.defistationApiUrl + "/bnblockedList/" + urlStr, {
method: 'GET',
headers: {
Authorization: global.auth
}
});
res
.json()
.then(res => {
// res.result 를 배열로 바꾸고 가장 마지막 요소(최신) 확인
let resultObj = res.result;
var resultArr = Object.keys(resultObj).map((key) => [Number(key), resultObj[key]]);
// console.log("res: ", res);
setTotalBnbLockedNum(numberWithCommas(Math.floor(resultArr[resultArr.length - 1][1])));
// setLockedBnbAmount(resultArr[resultArr.length - 1][1]);
// 해당 Defi BNB와 전체 BNB 유통량 비율
if (props.defiName != "DeFi") {
// 유통량: 147883948
setMiniCardData3(((resultArr[resultArr.length - 1][1] * 1 / 147883948 * 100).toFixed(4) * 1) + "%");
}
// Last updated(UTC) 표현에서 앞에 20, 뒤에 초 제거
let tempDate;
console.log("resultArr[resultArr.length - 1][0]: ", resultArr[resultArr.length - 1][0]);
if (resultArr[resultArr.length - 1][0] == 0) {
tempDate = "-";
} else {
tempDate = new Date(resultArr[resultArr.length - 1][0] * 1000).toISOString().replace(/T/, ' ').replace(/\..+/, '');
tempDate = tempDate.substring(0, tempDate.length - 3);
}
// Last updated(UTC)
setMiniCardData3(tempDate);
})
.catch(err => setResponseError(err));
}
function showTvl1Day() {
if (global.tvl1DayPercent > 0) {
setTvl1DayPercentTag("+" + global.tvl1DayPercent + "%");
} else {
setTvl1DayPercentTag(global.tvl1DayPercent + "%");
}
}
useEffect(() => {
getTotalBnbLocked(props.defiName);
showTvl1Day();
setMiniCardTitle3("Last updated(UTC)");
// minicard 0 으로 보이는 현상 임시
if (tvl1DayPercentTag == "0%") {
setTimeout(function() {
if (tvl1DayPercentTag != "0%") return;
console.log("global.totalValueLockedUsd: ", global.totalValueLockedUsd);
showTvl1Day();
}, 3000);
}
return () => {
};
}, [props.defiName, global.totalValueLockedUsd, tvl1DayPercentTag])
return (
<div className="miniCards">
<ul className="miniCardUl">
<MiniCard title="Total Value Locked" dataNum={global.totalValueLockedUsd} />
<MiniCard title="TVL Change 24h" dataNum={tvl1DayPercentTag} />
<MiniCard title="Total BNB Locked" dataNum={totalBnbLockedNum} symbol="BNB" />
<MiniCard title={miniCardTitle3} dataNum={miniCardData3} />
</ul>
</div>
);
})
export default MiniCards;<file_sep>/src/components/miniCards/miniCard/MiniCard.js
import React, { Fragment, Suspense, useState, useEffect } from "react";
import { observer, inject } from 'mobx-react';
import { useHistory, useLocation } from 'react-router-dom';
import '../../../App.css';
const MiniCard = observer((props) => {
useEffect(() => {
return () => {
};
}, [props.dataNum])
return (
<li className="miniCardList">
<span className="miniCardTitle">{props.title}</span>
<p style={props.symbol == "BNB" ? undefined : { display: "none" } } className="miniCardDataNum">{props.dataNum} <span style={{"color":"#f0b923"}}>BNB</span></p>
<p style={props.symbol == "BNB" ? { display: "none" } : undefined } className="miniCardDataNum">{props.dataNum}</p>
</li>
);
})
export default MiniCard;<file_sep>/src/components/defiOverview/DefiOverview.js
import React, { Fragment, Suspense, useState, useEffect } from "react";
import { observer, inject } from 'mobx-react';
import { useHistory, useLocation } from 'react-router-dom';
import { getOfficialDefiName } from '../../util/Util';
import defistationApplicationList from "../../defistationApplicationList.json";
import '../../App.css';
import binanceImg1 from "../../assets/images/binance_img@2x.png";
const DefiOverview = observer((props) => {
const [overviewTag, setOverviewTag] = useState();
function findDescription(defiName) {
// defistationApplicationList 에서 Official Project Name 이 defiName와 일치하는 것 찾기
// 예외처리
if (defiName == "pancake") {
defiName = "PancakeSwap";
}
let result = "";
for (var i = 0; i < defistationApplicationList.length; i++) {
if (defistationApplicationList[i]["Official Project Name"] == defiName) {
result = defistationApplicationList[i]["Detailed Project Description"];
// Audit 정보에 https 가 포함 있으면 Description 아래에 추가
if (defistationApplicationList[i]["Security Information"] != undefined) {
if (defistationApplicationList[i]["Security Information"].indexOf("https://") != -1) {
result += "\n\n" + defistationApplicationList[i]["Security Information"];
}
}
break;
}
}
return result;
}
useEffect(() => {
// defistationApplicationList
// if (props.defiName =)
let overviewStr = findDescription(props.defiName);
setOverviewTag(
<div className="defiOverview">
<span className="defiOverviewContent">
{overviewStr}
</span>
</div>
);
return () => {
};
}, [props.defiName])
return (
<>
{overviewTag}
</>
);
})
export default DefiOverview;<file_sep>/src/components/defiDetailList/DefiDetailList.js
import React, { Fragment, Suspense, useState, useEffect } from "react";
import { observer, inject } from 'mobx-react';
import { useHistory, useLocation } from 'react-router-dom';
import useStores from '../../useStores';
import '../../App.css';
import defistationApplicationList from "../../defistationApplicationList.json";
import { numberWithCommas, capitalize, replaceAll, getCurrencyUnit, getCurrencyDigit, convertDateFormat } from '../../util/Util';
const DefiDetailList = observer((props) => {
const { global } = useStores();
const history = useHistory();
// all, 1year, 90days
const [chartPeriod, setChartPeriod] = useState("30"); // 7, 30, 90, 365
const [responseError, setResponseError] = useState();
const [response, setResponse] = useState({});
const [defiDataTag, setDefiDataTag] = useState();
const [defiListTableCode, setDefiListTableCode] = useState();
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
function getMonthAndDay(date) {
let monthName = monthNames[date.getMonth()];
let day = date.getDate();
return monthName + " " + day;
}
async function getBnbLockedList(defiName) {
return new Promise(async function(resolve, reject) {
const res = await fetch(global.defistationApiUrl + "/bnblockedList/" + defiName + "?days=30", {
method: 'GET',
headers: {
Authorization: global.auth
}
});
res
.json()
.then(res => {
if (res.result == null) return;
let resultObj = res.result;
var resultArr = Object.keys(resultObj).map((key) => [Number(key), resultObj[key]]);
resolve(resultArr);
});
});
}
async function getChart(defiName) {
// console.log("getChart 함수 시작");
let urlStr = "";
if (defiName == "DeFi") {
urlStr = "all";
} else {
urlStr = defiName;
}
console.log("urlStr: ", urlStr);
if (urlStr == "") return;
let lockedBnbArr = await getBnbLockedList(defiName);
console.log("lockedBnbArr: ", lockedBnbArr);
let chartFullUrl;
if (chartPeriod == 7) {
// default
chartFullUrl = "/chart/" + urlStr;
} else {
chartFullUrl = "/chart/" + urlStr + "?days=" + chartPeriod;
}
const res = await fetch(global.defistationApiUrl + chartFullUrl, {
method: 'GET',
headers: {
Authorization: global.auth
}
});
res
.json()
.then(res => {
if (res.result == null) return;
// console.log("test1111111");
// res.result 를 배열로 바꾸기
let resultObj = res.result;
var resultArr = Object.keys(resultObj).map((key) => [Number(key), resultObj[key]]);
let initTimestamp = 0;
let tempMinTvl = 0;
// K, M, B 기준은 최초 0번째 데이터
let digit = getCurrencyDigit(resultArr[0][1]);
let currencyUnit = getCurrencyUnit(resultArr[0][1]);
let defiDataTagArr = [];
// console.log("test111111111111");
let tvlChangeTag;
let bnbChangeTag;
for (var i = 0; i < resultArr.length; i++) {
if (i == 0) {
initTimestamp = resultArr[i][0];
}
if (resultArr[i][1] == 0) {
continue;
}
// console.log("resultArr[i][0]: ", resultArr[i][0]);
// console.log("resultArr[i][1]: ", resultArr[i][1]);
// let digit = getCurrencyDigit(resultArr[i][1]);
// console.log("digit: ", digit);
// let currencyNum = (resultArr[i][1] / digit).toFixed(3) * 1;
// if (i == 0) {
// tempMinTvl = currencyNum;
// } else {
// // 가장 작은 값 찾기(vAxis 최솟값)
// if (tempMinTvl > currencyNum) {
// tempMinTvl = currencyNum;
// }
// }
let tvlChange = 0;
if (i > 0) {
tvlChange = (1 - resultArr[i - 1][1] / resultArr[i][1]);
if (tvlChange > 0) {
// +
tvlChangeTag = <span className="textGreen">+{(tvlChange * 100).toFixed(2)}%</span>;
} else if (tvlChange == 0) {
tvlChangeTag = <span>{(tvlChange * 100).toFixed(2)}%</span>;
} else if (tvlChange < 0) {
tvlChangeTag = <span className="textRed">{(tvlChange * 100).toFixed(2)}%</span>;
}
}
// BNB locked 변화량(개수로 표현)
let bnbChange = 0;
if (i > 0) {
bnbChange = lockedBnbArr[i][1] - lockedBnbArr[i - 1][1];
// if (bnbChange > 0) {
// // +
// bnbChangeTag = <span className="textGreen">+{numberWithCommas(Math.floor(bnbChange))}</span>;
// } else if (bnbChange == 0) {
// bnbChangeTag = <span>{numberWithCommas(Math.floor(bnbChange))}</span>;
// } else if (bnbChange < 0) {
// bnbChangeTag = <span className="textRed">{numberWithCommas(Math.floor(bnbChange))}</span>;
// }
if (bnbChange > 0) {
// +
bnbChangeTag = <span>+{numberWithCommas(Math.floor(bnbChange))}</span>;
} else if (bnbChange == 0) {
bnbChangeTag = <span>{numberWithCommas(Math.floor(bnbChange))}</span>;
} else if (bnbChange < 0) {
bnbChangeTag = <span>{numberWithCommas(Math.floor(bnbChange))}</span>;
}
}
// tvl
let digit = getCurrencyDigit(resultArr[i][1]);
let currencyUnit = getCurrencyUnit(resultArr[i][1]);
let currencyNum;
// tvl이 M 이하 단위인 경우 소숫점 1자리만, B 단위 이상은 소숫점 2자리로 표현
if (digit <= 1000000) {
currencyNum = (resultArr[i][1] / digit).toFixed(1) * 1;
} else {
currencyNum = (resultArr[i][1] / digit).toFixed(2) * 1;
}
// 30일의 change 24h 를 보여주려면 제일 첫번째껀 change 값이 Null 이다. null인 row는 가리기
if (tvlChangeTag != null) {
defiDataTagArr.unshift(<tr key={i}>
<td>{convertDateFormat(new Date(resultArr[i][0] * 1000))}</td>
<td>$ {numberWithCommas(resultArr[i][1])}</td>
<td>$ {currencyNum + currencyUnit}</td>
<td>{tvlChangeTag}</td>
<td>{numberWithCommas(Math.floor(lockedBnbArr[i][1]))} <span style={{"color":"#f0b923"}}>BNB</span></td>
<td>{bnbChangeTag} <span style={{"color":"#f0b923"}}>BNB</span></td>
</tr>);
}
}
setDefiDataTag(defiDataTagArr);
// // 차트 데이터가 7개가 안채워졌으면 앞에 채워넣기
// if (chartPeriod - resultArr.length > 0) {
// let createEmptyDataLength = chartPeriod - resultArr.length;
// // console.log("createEmptyDataLength: ", createEmptyDataLength);
// for (var i = 0; i < createEmptyDataLength; i++) {
// let calTimestamp = initTimestamp - (86400 * (i + 1));
// // tempChartData 의 제일 앞에 넣어야함
// tempChartData.unshift([getMonthAndDay(new Date(calTimestamp * 1000)), 0]);
// }
// }
})
.catch(err => setResponseError(err));
}
function movePage(path) {
history.push(path);
}
useEffect(() => {
// getDefiList();
console.log("props.defiName22222: ", props.defiName);
getChart(props.defiName);
return () => {
};
}, [props.defiName])
return (
<div className="defiDetailList">
<table className="defiDetailListTable">
<thead className="defiDetailListTableHead">
<tr>
<th>Date</th><th>TVL</th><th>TVL</th><th>TVL Change 24h</th><th>Total BNB Locked</th><th>BNB Locked 24h</th>
</tr>
</thead>
<tbody className="defiDetailListTableBody">
{defiDataTag}
{/* <tr>
<td>2020-10-13</td>
<td>$00.00B</td>
<td><span className="textGreen">+ 0.00M</span></td>
<td>108.65 <span style={{"color":"#f0b923"}}>BNB</span></td>
<td><span className="textGreen">+ 000.00</span></td>
</tr>
<tr>
<td>2020-10-13</td>
<td>$00.00B</td>
<td><span className="textGreen">+ 0.00M</span></td>
<td>108.65 <span style={{"color":"#f0b923"}}>BNB</span></td>
<td><span className="textGreen">+ 000.00</span></td>
</tr>
<tr>
<td>2020-10-13</td>
<td>$00.00B</td>
<td><span className="textGreen">+ 0.00M</span></td>
<td>108.65 <span style={{"color":"#f0b923"}}>BNB</span></td>
<td><span className="textGreen">+ 000.00</span></td>
</tr>
<tr>
<td>2020-10-13</td>
<td>$00.00B</td>
<td><span className="textGreen">+ 0.00M</span></td>
<td>108.65 <span style={{"color":"#f0b923"}}>BNB</span></td>
<td><span className="textGreen">+ 000.00</span></td>
</tr>
<tr>
<td>2020-10-13</td>
<td>$00.00B</td>
<td><span className="textGreen">+ 0.00M</span></td>
<td>108.65 <span style={{"color":"#f0b923"}}>BNB</span></td>
<td><span className="textGreen">+ 000.00</span></td>
</tr>
<tr>
<td>2020-10-13</td>
<td>$00.00B</td>
<td><span className="textGreen">+ 0.00M</span></td>
<td>108.65 <span style={{"color":"#f0b923"}}>BNB</span></td>
<td><span className="textGreen">+ 000.00</span></td>
</tr>
<tr>
<td>2020-10-13</td>
<td>$00.00B</td>
<td><span className="textGreen">+ 0.00M</span></td>
<td>108.65 <span style={{"color":"#f0b923"}}>BNB</span></td>
<td><span className="textGreen">+ 000.00</span></td>
</tr>
<tr>
<td>2020-10-13</td>
<td>$00.00B</td>
<td><span className="textGreen">+ 0.00M</span></td>
<td>108.65 <span style={{"color":"#f0b923"}}>BNB</span></td>
<td><span className="textGreen">+ 000.00</span></td>
</tr>
<tr>
<td>2020-10-13</td>
<td>$00.00B</td>
<td><span className="textGreen">+ 0.00M</span></td>
<td>108.65 <span style={{"color":"#f0b923"}}>BNB</span></td>
<td><span className="textGreen">+ 000.00</span></td>
</tr>
<tr>
<td>2020-10-13</td>
<td>$00.00B</td>
<td><span className="textGreen">+ 0.00M</span></td>
<td>108.65 <span style={{"color":"#f0b923"}}>BNB</span></td>
<td><span className="textGreen">+ 000.00</span></td>
</tr> */}
</tbody>
</table>
<br />
</div>
);
})
export default DefiDetailList; | 1c5f573430d3c56ef67132703d8ee4f1a824ebbb | [
"JavaScript"
] | 5 | JavaScript | InfiniteDivs/defistation-web | abacac7d00d5119047089c39f514018fe9bc7540 | 8e6db067bb24d0fbd9363c35ff0f0441a3897dd4 |
refs/heads/master | <file_sep>/*
* Triangle.h
*
* Created on: Oct 28, 2009
* Author: juanmarcus
*/
#ifndef TRIANGLE_H_
#define TRIANGLE_H_
#include "ibi_internal.h"
#include "Vector3.h"
BEGIN_NAMESPACE_IBI
class Triangle
{
public:
Triangle()
{
}
Triangle(const Vector3& v0, const Vector3& v1, const Vector3& v2)
{
vertices[0] = v0;
vertices[1] = v1;
vertices[2] = v2;
}
~Triangle()
{
}
void setVertices(const Vector3& v0, const Vector3& v1, const Vector3& v2)
{
vertices[0] = v0;
vertices[1] = v1;
vertices[2] = v2;
}
Vector3 getVertex(int v) const
{
assert(v < 3);
return vertices[v];
}
private:
Vector3 vertices[3];
};
END_NAMESPACE_IBI
#endif /* TRIANGLE_H_ */
<file_sep>/*
* test_geometry.cpp
*
* Created on: Oct 26, 2009
* Author: <NAME>
*/
#include "ibi_gl/ibi_gl.h"
#include <QtGui/QApplication>
#include <QGLViewer/qglviewer.h>
#include <iostream>
#include "ibi_geometry/Ray.h"
#include "ibi_geometry/Vector3.h"
#include "ibi_geometry/Matrix4.h"
#include "ibi_geometry/AxisAlignedBox.h"
#include "ibi_gl/GeometryDrawer.h"
#include "ibi_geometry/Transform.h"
using namespace std;
using namespace ibi;
class Viewer: public QGLViewer
{
public:
Viewer(QWidget* parent = 0) :
QGLViewer(parent)
{
}
~Viewer()
{
}
void init()
{
setManipulatedFrame(new qglviewer::ManipulatedFrame());
setSceneRadius(2.0);
showEntireScene();
// restoreStateFromFile();
box.setExtents(-1, -1, -1, 1, 1, 1);
}
void draw()
{
const GLdouble* mod = manipulatedFrame()->matrix();
Matrix4 m(mod[0], mod[4], mod[8], mod[12], mod[1], mod[5], mod[9],
mod[13], mod[2], mod[6], mod[10], mod[14], mod[3], mod[7],
mod[11], mod[15]);
// Transform ray
Ray tray = Transform::TransformRay(m, ray);
// Draw ray
drawer.drawRay(tray, 4, 0.005);
// Draw point at the origin
drawer.drawPoint(Vector3::ZERO);
// Draw a box
drawer.drawAxisAlignedBox(box);
}
private:
GeometryDrawer drawer;
Ray ray;
AxisAlignedBox box;
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
Viewer w;
w.showMaximized();
return app.exec();
}
<file_sep>/*
* Math.cpp
*
* Created on: Oct 26, 2009
* Author: <NAME>
*/
#include "Math.h"
#include <limits>
BEGIN_NAMESPACE_IBI
const Real Math::POS_INFINITY = std::numeric_limits<Real>::infinity();
const Real Math::NEG_INFINITY = -std::numeric_limits<Real>::infinity();
const Real Math::PI = Real(4.0 * atan(1.0));
const Real Math::TWO_PI = Real(2.0 * PI);
const Real Math::HALF_PI = Real(0.5 * PI);
const Real Math::fDeg2Rad = PI / Real(180.0);
const Real Math::fRad2Deg = Real(180.0) / PI;
//-----------------------------------------------------------------------
int Math::ISign(int iValue)
{
return (iValue > 0 ? +1 : (iValue < 0 ? -1 : 0));
}
//-----------------------------------------------------------------------
Radian Math::ACos(Real fValue)
{
if (-1.0 < fValue)
{
if (fValue < 1.0)
return Radian(acos(fValue));
else
return Radian(0.0);
}
else
{
return Radian(PI);
}
}
//-----------------------------------------------------------------------
Radian Math::ASin(Real fValue)
{
if (-1.0 < fValue)
{
if (fValue < 1.0)
return Radian(asin(fValue));
else
return Radian(HALF_PI);
}
else
{
return Radian(-HALF_PI);
}
}
//-----------------------------------------------------------------------
Real Math::Sign(Real fValue)
{
if (fValue > 0.0)
return 1.0;
if (fValue < 0.0)
return -1.0;
return 0.0;
}
//-----------------------------------------------------------------------
Real Math::InvSqrt(Real fValue)
{
return Real(1. / sqrt(fValue));
}
//-----------------------------------------------------------------------
Real Math::UnitRandom()
{
return rand() / Real(RAND_MAX);
}
//-----------------------------------------------------------------------
Real Math::RangeRandom(Real fLow, Real fHigh)
{
return (fHigh - fLow) * UnitRandom() + fLow;
}
//-----------------------------------------------------------------------
Real Math::SymmetricRandom()
{
return 2.0f * UnitRandom() - 1.0f;
}
//-----------------------------------------------------------------------
bool Math::RealEqual(Real a, Real b, Real tolerance)
{
if (fabs(b - a) <= tolerance)
return true;
else
return false;
}
//-----------------------------------------------------------------------
Real Math::gaussianDistribution(Real x, Real offset, Real scale)
{
Real nom = Math::Exp(-Math::Sqr(x - offset) / (2 * Math::Sqr(scale)));
Real denom = scale * Math::Sqrt(2 * Math::PI);
return nom / denom;
}
END_NAMESPACE_IBI
<file_sep>/*
* Wrapper.cpp
*
* Created on: Oct 27, 2009
* Author: <NAME>
*/
#include "GL.h"
BEGIN_NAMESPACE_IBI
END_NAMESPACE_IBI
<file_sep>/*
* SceneNode.h
*
* Created on: Dec 1, 2009
* Author: <NAME>
*/
#ifndef SCENENODE_H_
#define SCENENODE_H_
#include "ibi_internal.h"
#include "Renderable.h"
#include "ibi_geometry/Matrix4.h"
#include <vector>
BEGIN_NAMESPACE_IBI
class SceneNode
{
public:
SceneNode();
virtual ~SceneNode();
SceneNode* createChildSceneNode();
void addChildSceneNode(SceneNode* node);
void setParentSceneNode(SceneNode* node);
void setRenderable(Renderable* renderable);
void setTranslation(Vector3& translation);
SceneNode* getParentSceneNode();
Renderable* getRenderable();
std::vector<SceneNode*> getChildren();
Vector3 getTranslation();
void update(bool render);
private:
/*
* Children SceneNodes.
*/
std::vector<SceneNode*> children;
/**
* SceneNode that holds this node.
*/
SceneNode* parent;
/**
* Renderable object.
*/
Renderable* renderable;
/*
* SceneNode translation relative to parent.
*/
Vector3 translation;
};
END_NAMESPACE_IBI
#endif /* SCENENODE_H_ */
<file_sep>/*
* texture_loader_qt.cpp
*
* Created on: Nov 2, 2009
* Author: juanmarcus
*/
#include "ibi_internal.h"
#include "ibi_gl/ibi_gl.h"
#include "ibi_texturemanager/TextureManager.h"
#include "ibi_gl/Texture.h"
#include <boost/any.hpp>
#include <iostream>
using BEGIN_NAMESPACE_IBI;
class TextureLoader_empty: public TextureLoader
{
void load(TextureLoadingInfo& info, Texture* texture)
{
int width = boost::any_cast<int>(info.options["width"]);
int height = boost::any_cast<int>(info.options["height"]);
GLint internalformat = boost::any_cast<GLint>(
info.options["internalformat"]);
// std::cout << boost::any_cast<unsigned int>(info.options["format"]) << std::endl;
// std::cout << GL_RGBA << std::endl;
GLenum format = boost::any_cast<int>(info.options["format"]);
GLenum type = boost::any_cast<int>(info.options["type"]);
glTexImage2D(info.target, 0, internalformat, width, height, 0, format,
type, NULL);
texture->setDimensions(width, height);
}
};
class TextureLoaderFactory_empty: public TextureLoaderFactory
{
TextureLoader* create()
{
TextureLoader* loader = new TextureLoader_empty();
return loader;
}
};
extern "C"
{
void registerPlugin(TextureManager& manager)
{
TextureLoaderFactory_empty* loaderF = new TextureLoaderFactory_empty();
manager.registerTextureLoader(String("empty"), loaderF);
}
}
<file_sep>/*
* Transform.cpp
*
* Created on: Oct 27, 2009
* Author: <NAME>
*/
#include "Transform.h"
BEGIN_NAMESPACE_IBI
END_NAMESPACE_IBI
<file_sep>/*
* GeometryDrawer.h
*
* Created on: Oct 26, 2009
* Author: <NAME>
*/
#ifndef GEOMETRYDRAWER_H_
#define GEOMETRYDRAWER_H_
#include "ibi_internal.h"
#include "ibi_gl.h"
#include <vector>
#include "ibi_geometry/Ray.h"
#include "ibi_geometry/AxisAlignedBox.h"
#include "ibi_geometry/Vector3.h"
#include "ibi_geometry/Triangle.h"
BEGIN_NAMESPACE_IBI
class GeometryDrawer
{
public:
GeometryDrawer();
~GeometryDrawer();
void drawCylinder(Vector3& from, Vector3& to, float radius = -1.0,
int nbSubdivisions = 12);
void drawCylinder(float length, float radius = -1.0, int nbSubdivisions =
12);
void drawArrow(float length, float radius = -1.0, int nbSubdivisions = 12);
void drawRay(Ray& ray, float length, float radius = -1.0,
int nbSubdivisions = 12);
void
drawPoint(const Vector3& point, float radius = 0.01, int nbSubdivisions =
12);
void drawPoints(std::vector<Vector3>& points, float radius = 0.01,
int nbSubdivisions = 12);
void drawAxisAlignedBox(const AxisAlignedBox& box, float radius = 0.01,
int nbSubdivisions = 12);
void drawTriangle(const Triangle& t, float radius = 0.01,
int nbSubdivisions = 12);
private:
GLUquadric* quadric;
};
END_NAMESPACE_IBI
#endif /* GEOMETRYDRAWER_H_ */
<file_sep>/*
* AxisAlignedBox.cpp
*
* Created on: Oct 26, 2009
* Author: <NAME>
*/
#include "AxisAlignedBox.h"
BEGIN_NAMESPACE_IBI
const AxisAlignedBox AxisAlignedBox::BOX_NULL;
const AxisAlignedBox AxisAlignedBox::BOX_INFINITE(
AxisAlignedBox::EXTENT_INFINITE);
END_NAMESPACE_IBI
<file_sep>#-----------------------------------------------------------------------------
#
# IBIConfig.cmake - IBI CMake configuration file for external projects.
#
# This file is configured by IBI and used by the IBIUse.cmake module
# to load IBI's settings for an external project.
# The directory of IBIConfig.cmake is, by definition, IBI_DIR.
# (this_dir == IBI_DIR)
#
GET_FILENAME_COMPONENT(this_dir "${CMAKE_CURRENT_LIST_FILE}" PATH)
GET_FILENAME_COMPONENT(IBI_ROOT_DIR "${this_dir}/@IBI_CV_CONFIG_TO_ROOT@" ABSOLUTE)
# CMake files required to build client applications that use IBI.
SET(IBI_BUILD_SETTINGS_FILE "@IBI_CV_BUILD_SETTINGS_FILE@")
SET(IBI_USE_FILE "@IBI_CV_USE_FILE@")
# The IBI directories.
#SET(IBI_EXECUTABLE_DIRS "@IBI_CV_EXECUTABLE_DIRS@")
SET(IBI_LIBRARY_DIRS "@IBI_CV_LIBRARY_DIRS@")
SET(IBI_INCLUDE_DIRS "@IBI_CV_INCLUDE_DIRS@")
#SET(IBI_EXTRA_INCLUDE_DIRS "@IBI_CV_EXTRA_INCLUDE_DIRS@")
# The IBI libraries.
SET(IBI_LIBRARIES "@IBI_CV_BUILT_LIBRARIES@")
#SET(IBI_EXTRA_LIBRARY_DIRS "@IBI_CV_EXTRA_LIBRARY_DIRS@")
# The C flags added by IBI to the cmake-configured flags.
#SET(IBI_REQUIRED_C_FLAGS "@IBI_REQUIRED_C_FLAGS@")
# The IBI version number
SET(IBI_VERSION_MAJOR "@IBI_VERSION_MAJOR@")
SET(IBI_VERSION_MINOR "@IBI_VERSION_MINOR@")
SET(IBI_VERSION_PATCH "@IBI_VERSION_PATCH@")
# The IBI library dependencies.
IF(NOT IBI_NO_LIBRARY_DEPENDS)
INCLUDE("@IBI_CV_LIBRARY_DEPENDS_FILE@")
ENDIF(NOT IBI_NO_LIBRARY_DEPENDS)
<file_sep>/*
* Exception.cpp
*
* Created on: Oct 9, 2009
* Author: <NAME>
*/
#include "Exception.h"
BEGIN_NAMESPACE_IBI
using namespace std;
Exception::Exception(String file, String general, String detail) :
exception()
{
this->file = file;
this->general = general;
this->detail = detail;
}
Exception::~Exception() throw ()
{
}
END_NAMESPACE_IBI
<file_sep>/*
* FramebufferObject.h
*
* Created on: Nov 5, 2009
* Author: juanmarcus
*/
#ifndef FramebufferObject_H_
#define FramebufferObject_H_
#include "ibi_internal.h"
#include "ibi_gl/ibi_gl.h"
#include "ibi_gl/Texture.h"
BEGIN_NAMESPACE_IBI
class FramebufferObject
{
public:
FramebufferObject();
~FramebufferObject();
void init();
void bind();
void release();
void setTarget(Texture* t);
void checkStatus();
private:
bool enabled;
/**
* Generated OpenGL name.
*/
GLuint name;
/*
* Texture to render to.
*/
Texture* target;
/*
* Temporary viewport.
*/
int oldViewport[4];
};
END_NAMESPACE_IBI
#endif /* FramebufferObject_H_ */
<file_sep>/*
* Interpolation.h
*
* Created on: Oct 29, 2009
* Author: <NAME>
*/
#ifndef INTERPOLATION_H_
#define INTERPOLATION_H_
#include "ibi_internal.h"
#include <vector>
#include "ibi_geometry/Vector3.h"
#include "ibi_geometry/Ray.h"
BEGIN_NAMESPACE_IBI
class Interpolation
{
public:
Interpolation();
~Interpolation();
static inline std::vector<Vector3> interpolate(const Vector3& p1,
const Vector3& p2, int npoints)
{
std::vector<Vector3> points;
Vector3 dir = p2 - p1;
Real len = dir.length();
dir.normalise();
Ray ray(p1, dir);
Real pos = 0.0;
Real step = len / (npoints + 1);
for (int i = 0; i < npoints; ++i)
{
pos += step;
Vector3 np = ray * pos;
points.push_back(np);
}
return points;
}
};
END_NAMESPACE_IBI
#endif /* INTERPOLATION_H_ */
<file_sep>/*
* Transform.h
*
* Created on: Oct 27, 2009
* Author: <NAME>
*/
#ifndef TRANSFORM_H_
#define TRANSFORM_H_
#include "ibi_internal.h"
#include "Ray.h"
#include "Matrix4.h"
BEGIN_NAMESPACE_IBI
class Transform
{
public:
static inline Ray TransformRay(Matrix4& mat, Ray& ray)
{
Ray rray;
Matrix3 mrot;
rray.setOrigin(mat * ray.getOrigin());
mat.extract3x3Matrix(mrot);
rray.setDirection(mrot * ray.getDirection());
return rray;
}
};
END_NAMESPACE_IBI
#endif /* TRANSFORM_H_ */
<file_sep>/*
* GPUProgramManager.h
*
* Created on: Nov 4, 2009
* Author: juanmarcus
*/
#ifndef GPUPROGRAMMANAGER_H_
#define GPUPROGRAMMANAGER_H_
#include "ibi_internal.h"
#include "ibi_gl/ibi_gl.h"
#include "Cg/cg.h"
#include "VertexProgram.h"
#include "FragmentProgram.h"
BEGIN_NAMESPACE_IBI
class GPUProgramManager
{
public:
GPUProgramManager();
virtual ~GPUProgramManager();
/*
* Initialize the context and profiles.
*/
void init();
VertexProgram* loadVertexProgram(String path, String entry = "main");
FragmentProgram* loadFragmentProgram(String path, String entry = "main");
/*
* Checks current context for errors.
*/
void checkError();
private:
/*
* CG context.
*/
CGcontext context;
/*
* Current vertex profile.
*/
CGprofile vertex_profile;
/*
* * Current fragment profile.
*/
CGprofile fragment_profile;
};
END_NAMESPACE_IBI
#endif /* GPUPROGRAMMANAGER_H_ */
<file_sep>/*
* Interpolation.cpp
*
* Created on: Oct 29, 2009
* Author: <NAME>
*/
#include "Interpolation.h"
BEGIN_NAMESPACE_IBI
Interpolation::Interpolation()
{
// TODO Auto-generated constructor stub
}
Interpolation::~Interpolation()
{
// TODO Auto-generated destructor stub
}
END_NAMESPACE_IBI
<file_sep>/*
* SceneNode.cpp
*
* Created on: Dec 1, 2009
* Author: <NAME>
*/
#include "SceneNode.h"
#include "ibi_gl/ibi_gl.h"
#include "ibi_gl/GL.h"
BEGIN_NAMESPACE_IBI
SceneNode::SceneNode() :
parent(0), renderable(0)
{
translation = Vector3::ZERO;
}
SceneNode::~SceneNode()
{
}
SceneNode* SceneNode::createChildSceneNode()
{
SceneNode* node = new SceneNode();
addChildSceneNode(node);
}
void SceneNode::addChildSceneNode(SceneNode* node)
{
children.push_back(node);
node->setParentSceneNode(this);
}
void SceneNode::setParentSceneNode(SceneNode* node)
{
this->parent = node;
}
void SceneNode::setRenderable(Renderable* renderable)
{
this->renderable = renderable;
}
void SceneNode::setTranslation(Vector3& translation)
{
this->translation = translation;
}
SceneNode* SceneNode::getParentSceneNode()
{
return parent;
}
Renderable* SceneNode::getRenderable()
{
return renderable;
}
std::vector<SceneNode*> SceneNode::getChildren()
{
return children;
}
Vector3 SceneNode::getTranslation()
{
return translation;
}
void SceneNode::update(bool render)
{
if (render)
{
glPushMatrix();
GL::Translate(translation);
if (renderable)
{
renderable->render();
}
}
std::vector<SceneNode*>::iterator it = children.begin();
std::vector<SceneNode*>::iterator itEnd = children.end();
for (; it != itEnd; ++it)
{
(*it)->update(render);
}
if (render)
{
glPopMatrix();
}
}
END_NAMESPACE_IBI
<file_sep>/*
* TextureManager.cpp
*
* Created on: Nov 2, 2009
* Author: juanmarcus
*/
#include "TextureManager.h"
#include "ibi_error/Exception.h"
#include <dlfcn.h>
BEGIN_NAMESPACE_IBI
{
TextureManager* TextureManager::instance = 0;
TextureManager* TextureManager::getInstance()
{
if (!instance)
{
instance = new TextureManager();
}
return instance;
}
TextureManager::TextureManager()
{
}
TextureManager::~TextureManager()
{
std::vector<void*>::iterator it = loadedPlugins.begin();
std::vector<void*>::iterator itEnd = loadedPlugins.end();
for (; it != itEnd; ++it)
{
dlclose(*it);
}
}
void TextureManager::registerTextureLoader(String type,
TextureLoaderFactory* textureLoaderFactory)
{
loaders[type] = textureLoaderFactory->create();
}
void TextureManager::loadPlugin(String filename)
{
void* phandle = dlopen(filename.c_str(), RTLD_NOW);
if (!phandle)
{
throw Exception("TextureManager.cpp", "Problem loading plugin.",
"File not found: " + filename);
}
// load the entry point
typedef void (*registerPlugin_t)(TextureManager&);
// reset errors
dlerror();
registerPlugin_t registerPlugin = (registerPlugin_t) dlsym(phandle,
"registerPlugin");
const char *dlsym_error = dlerror();
if (dlsym_error)
{
throw Exception("TextureManager.cpp", "Problem loading entry point.",
"Can't find a function called 'registerPlugin' in the library.");
dlclose(phandle);
}
registerPlugin(*this);
}
Texture* TextureManager::load(TextureLoadingInfo& info)
{
if (info.texture_type == "")
{
throw Exception("TextureManager.cpp", "Texture type not specified.");
}
if (loaders.count(info.texture_type) == 0)
{
throw Exception("TextureManager.cpp",
"Problem finding loader for type.", "Type: "
+ info.texture_type);
}
// Get loader
TextureLoader* loader = loaders[info.texture_type];
// Initialize texture
Texture* texture = new Texture();
texture->setTarget(info.target);
texture->init();
// Call plugin loader
loader->load(info, texture);
// Disable texture to avoid problems
texture->disable();
return texture;
}
END_NAMESPACE_IBI
<file_sep>/*
* TextureLoader.h
*
* Created on: Nov 23, 2009
* Author: <NAME>
*/
#ifndef TEXTURELOADER_H_
#define TEXTURELOADER_H_
#include "ibi_internal.h"
#include "ibi_error/Exception.h"
#include "Texture.h"
#include "TextureLoadingInfo.h"
BEGIN_NAMESPACE_IBI
class TextureLoader
{
public:
static inline Texture* load(TextureLoadingInfo& info)
{
// Create and init texture
Texture* t = new Texture();
t->setTarget(info.target);
t->setDimensions(info.width, info.height, info.depth);
t->setDimension(info.dim);
t->init();
load(t, info.level, info.internalformat, info.border, info.format,
info.type, info.data);
return t;
}
static inline void load(Texture* t, int level, int internalformat,
int border, GLenum format, GLenum type, void* data)
{
// Enable texture
t->enable();
int dim = t->getDimension();
switch (dim)
{
case 1:
load1D(t, level, internalformat, border, format, type, data);
break;
case 2:
load2D(t, level, internalformat, border, format, type, data);
break;
case 3:
load3D(t, level, internalformat, border, format, type, data);
break;
default:
throw Exception("TextureLoader.h", "Problem loading texture.",
"Wrong texture dimension.");
}
// Set texture parameters
glTexParameteri(t->getTarget(), GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(t->getTarget(), GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// Disable texture
t->disable();
}
private:
static inline void load1D(Texture* t, int level, int internalformat,
int border, GLenum format, GLenum type, void* data)
{
glTexImage1D(t->getTarget(), level, internalformat, t->getWidth(),
border, format, type, data);
}
static inline void load2D(Texture* t, int level, int internalformat,
int border, GLenum format, GLenum type, void* data)
{
glTexImage2D(t->getTarget(), level, internalformat, t->getWidth(),
t->getHeight(), border, format, type, data);
}
static inline void load3D(Texture* t, int level, int internalformat,
int border, GLenum format, GLenum type, void* data)
{
glTexImage3D(t->getTarget(), level, internalformat, t->getWidth(),
t->getHeight(), t->getDepth(), border, format, type, data);
}
};
END_NAMESPACE_IBI
#endif /* TEXTURELOADER_H_ */
<file_sep>/*
* Renderable.cpp
*
* Created on: Dec 1, 2009
* Author: <NAME>
*/
#include "Renderable.h"
BEGIN_NAMESPACE_IBI
Renderable::Renderable()
{
}
Renderable::~Renderable()
{
}
END_NAMESPACE_IBI
<file_sep>/*
* Factory.h
*
* Created on: Nov 2, 2009
* Author: juanmarcus
*/
#ifndef FACTORY_H_
#define FACTORY_H_
BEGIN_NAMESPACE_IBI
{
template<typename Interface>
class Factory
{
public:
virtual Interface* create() = 0;
};
END_NAMESPACE_IBI
#endif /* FACTORY_H_ */
<file_sep>/*
* ibi_gl.h
*
* Created on: Nov 3, 2009
* Author: <NAME>
*/
#ifndef IBI_GL_H_
#define IBI_GL_H_
#include "ibi_internal.h"
#include <GL/glew.h>
#include <GL/glut.h>
BEGIN_NAMESPACE_IBI
END_NAMESPACE_IBI
#endif /* IBI_GL_H_ */
<file_sep>/*
* TextureLoadingInfo.h
*
* Created on: Nov 23, 2009
* Author: <NAME>
*/
#ifndef TEXTURELOADINGINFO_H_
#define TEXTURELOADINGINFO_H_
#include "ibi_internal.h"
#include "ibi_gl.h"
BEGIN_NAMESPACE_IBI
/*
* Loading time information for textures.
*/
class TextureLoadingInfo
{
public:
TextureLoadingInfo();
virtual ~TextureLoadingInfo();
public:
/*
* Target GL enum.
*
* For instance GL_TEXTURE_2D.
*/
GLenum target;
/*
* Number of dimensions;
*/
int dim;
/*
* Texture width.
*/
int width;
/*
* Texture height.
*
* Does not apply to 1D textures.
*/
int height;
/*
* Texture depth.
*
* Does not apply to 2D textures.
*/
int depth;
/*
* Mipmap level.
*/
int level;
/*
* Format to represent texture internally.
*/
int internalformat;
/*
* Border width.
*/
int border;
/*
* Data format on memory.
*/
GLenum format;
/*
* Data type on memory.
*/
GLenum type;
/*
* Actual data.
*/
void* data;
/*
* Determines of data should be destroyed after loading.
*/
bool destroydata;
};
END_NAMESPACE_IBI
#endif /* TEXTURELOADINGINFO_H_ */
<file_sep>/*
* GeometryDrawer2D.cpp
*
* Created on: Nov 11, 2009
* Author: <NAME>
*/
#include "GeometryDrawer2D.h"
BEGIN_NAMESPACE_IBI
GeometryDrawer2D::GeometryDrawer2D()
{
}
GeometryDrawer2D::~GeometryDrawer2D()
{
}
void GeometryDrawer2D::drawCircle(Vector3& center, float radius,
float nbSubdivisions)
{
float step = 360.0 / nbSubdivisions;
glBegin(GL_TRIANGLE_FAN);
glVertex2f(center.x, center.y);
for (float angle = 0.0; angle <= 360; angle += step)
{
glVertex2f(center.x + Math::Sin(Degree(angle)) * radius, center.y
+ Math::Cos(Degree(angle)) * radius);
}
glEnd();
}
END_NAMESPACE_IBI
<file_sep>/*
* VertexProgram.cpp
*
* Created on: Nov 4, 2009
* Author: juanmarcus
*/
#include "VertexProgram.h"
BEGIN_NAMESPACE_IBI
VertexProgram::VertexProgram(GPUProgramManager* parent) :
GPUProgram(parent)
{
}
VertexProgram::~VertexProgram()
{
}
END_NAMESPACE_IBI
<file_sep>/*
* GLMode2D.cpp
*
* Created on: Oct 14, 2009
* Author: <NAME>
*/
#include "GLMode2D.h"
BEGIN_NAMESPACE_IBI
GLMode2D::GLMode2D() :
active(false), width(0), height(0)
{
}
GLMode2D::~GLMode2D()
{
}
void GLMode2D::setScreenDimensions(int w, int h)
{
this->width = w;
this->height = h;
}
void GLMode2D::enable()
{
if (!active)
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0, width, 0, height, -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
// Make sure depth testing and lighting are disabled for 2D rendering until
// we are finished rendering in 2D
glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_LIGHTING_BIT);
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
active = true;
}
}
void GLMode2D::disable()
{
if (active)
{
// Restore lighting and depth testing state
glPopAttrib();
// Restore matrices
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
active = false;
}
}
void GLMode2D::drawFullScreenQuad()
{
glBegin(GL_QUADS);
glTexCoord2d(0.0, 0.0);
glVertex2d(0.0, 0.0);
glTexCoord2d(1.0, 0.0);
glVertex2d(width, 0.0);
glTexCoord2d(1.0, 1.0);
glVertex2d(width, height);
glTexCoord2d(0.0, 1.0);
glVertex2d(0.0, height);
glEnd();
}
END_NAMESPACE_IBI
<file_sep>/*
* texture_loader_qt.cpp
*
* Created on: Nov 2, 2009
* Author: juanmarcus
*/
#include "ibi_internal.h"
#include "ibi_texturemanager/TextureManager.h"
#include "ibi_gl/Texture.h"
#include <boost/any.hpp>
#include <teem/nrrd.h>
#include "nrrdGLutils.h"
using BEGIN_NAMESPACE_IBI;
class TextureLoader_nrrd3D: public TextureLoader
{
void load(TextureLoadingInfo& info, Texture* texture)
{
Nrrd* nin = boost::any_cast<Nrrd*>(info.options["nrrd"]);
// Nrrd* nout = nrrdNew();
// nrrdConvert(nout,nin,nrrdTypeUChar);
// nrrdQuantize(nout, nin, 0, 8);
int width = nin->axis[0].size;
int height = nin->axis[1].size;
int depth = nin->axis[2].size;
// TODO Copy memory upside-down
// char* tmpdata = (char*) malloc(width * height * depth * elemsize);
//
// for (int i = 0; i < height; ++i)
// {
// char* src = (char*) nin->data;
// int linesize = width * elemsize;
// memcpy(&tmpdata[(height - i - 1) * linesize], &src[i * linesize],
// linesize);
// }
// GLuint name = texture->getGLName();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(info.target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(info.target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
glTexParameteri(info.target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexImage3D(info.target, 0, GL_ALPHA, width, height, depth, 0,
GL_ALPHA, convert_type_to_enum(nin->type), nin->data);
texture->setDimensions(width, height, depth);
// free( tmpdata);
// nrrdNuke(nout);
}
};
class TextureLoaderFactory_nrrd3D: public TextureLoaderFactory
{
TextureLoader* create()
{
TextureLoader* loader = new TextureLoader_nrrd3D();
return loader;
}
};
extern "C"
{
void registerPlugin(TextureManager& manager)
{
TextureLoaderFactory_nrrd3D* loaderF = new TextureLoaderFactory_nrrd3D();
manager.registerTextureLoader(String("nrrd3D"), loaderF);
}
}
<file_sep>/*
* Intersection.h
*
* Created on: Oct 28, 2009
* Author: juanmarcus
*/
#ifndef INTERSECTION_H_
#define INTERSECTION_H_
#include "ibi_internal.h"
#include "ibi_geometry/Ray.h"
#include "ibi_geometry/AxisAlignedBox.h"
#include "ibi_geometry/Triangle.h"
BEGIN_NAMESPACE_IBI
class Intersection
{
public:
/** Ray / box intersection, returns boolean result and distance. */
static std::pair<bool, RealPair > intersects(const Ray& ray,
const AxisAlignedBox& box);
static std::pair<bool, Real> intersects(const Ray& ray,
const Triangle& triangle);
};
END_NAMESPACE_IBI
#endif /* INTERSECTION_H_ */
<file_sep>/*
* Vector3.cpp
*
* Created on: Oct 26, 2009
* Author: <NAME>
*/
#include "Vector3.h"
BEGIN_NAMESPACE_IBI
const Vector3 Vector3::ZERO(0, 0, 0);
const Vector3 Vector3::UNIT_X(1, 0, 0);
const Vector3 Vector3::UNIT_Y(0, 1, 0);
const Vector3 Vector3::UNIT_Z(0, 0, 1);
const Vector3 Vector3::NEGATIVE_UNIT_X(-1, 0, 0);
const Vector3 Vector3::NEGATIVE_UNIT_Y(0, -1, 0);
const Vector3 Vector3::NEGATIVE_UNIT_Z(0, 0, -1);
const Vector3 Vector3::UNIT_SCALE(1, 1, 1);
END_NAMESPACE_IBI
<file_sep>/*
* GPUProgramManager.cpp
*
* Created on: Nov 4, 2009
* Author: juanmarcus
*/
#include "GPUProgramManager.h"
#include <Cg/cgGL.h>
#include "ibi_error/Exception.h"
#include <iostream>
using namespace std;
BEGIN_NAMESPACE_IBI
GPUProgramManager::GPUProgramManager()
{
}
GPUProgramManager::~GPUProgramManager()
{
}
void GPUProgramManager::init()
{
context = cgCreateContext();
checkError();
cgGLRegisterStates(context);
checkError();
vertex_profile = cgGLGetLatestProfile(CG_GL_VERTEX);
fragment_profile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
}
VertexProgram* GPUProgramManager::loadVertexProgram(String path, String entry)
{
VertexProgram* prog = new VertexProgram(this);
cgGLEnableProfile(vertex_profile);
CGprogram program = cgCreateProgramFromFile(context, CG_SOURCE,
path.c_str(), vertex_profile, entry.c_str(), NULL);
if (!cgIsProgramCompiled(program))
cgCompileProgram(program);
cgGLLoadProgram(program);
cgGLDisableProfile(vertex_profile);
checkError();
prog->profile = vertex_profile;
prog->program = program;
return prog;
}
FragmentProgram* GPUProgramManager::loadFragmentProgram(String path,
String entry)
{
FragmentProgram* prog = new FragmentProgram(this);
cgGLEnableProfile(fragment_profile);
CGprogram program = cgCreateProgramFromFile(context, CG_SOURCE,
path.c_str(), fragment_profile, entry.c_str(), NULL);
if (!cgIsProgramCompiled(program))
cgCompileProgram(program);
cgGLLoadProgram(program);
cgGLDisableProfile(fragment_profile);
checkError();
prog->profile = fragment_profile;
prog->program = program;
return prog;
}
void GPUProgramManager::checkError()
{
CGerror lastError = cgGetError();
if (lastError)
{
// cout << cgGetErrorString(lastError) << endl;
// if (context != NULL)
// cout << cgGetLastListing(context) << endl;
throw Exception("GPUProgramManager.cpp", cgGetErrorString(lastError),
cgGetLastListing(context));
}
}
END_NAMESPACE_IBI
<file_sep>cmake_minimum_required (VERSION 2.6)
project (IBI)
#-----------------------------------------------------------------------------
# IBI version number.
SET(IBI_VERSION_MAJOR "0")
SET(IBI_VERSION_MINOR "1")
SET(IBI_VERSION_PATCH "0")
#-----------------------------------------------------------------------------
# Extra cmake stuff
SET (CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/CMake")
#-----------------------------------------------------------------------------
# Uninstall target
CONFIGURE_FILE (
"${CMAKE_CURRENT_SOURCE_DIR}/CMake/cmake_uninstall.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/CMake/cmake_uninstall.cmake"
IMMEDIATE @ONLY)
ADD_CUSTOM_TARGET (uninstall
"${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/CMake/cmake_uninstall.cmake")
#-----------------------------------------------------------------------------
# Verbose makefile for helping eclise
SET (CMAKE_VERBOSE_MAKEFILE ON)
#-----------------------------------------------------------------------------
# Find required packages
find_package (Qt4 REQUIRED)
find_package (Boost 1.39.0 COMPONENTS program_options REQUIRED)
find_package (QGLViewer REQUIRED)
find_package (GLEW REQUIRED)
find_package (GLUT REQUIRED)
find_package (Cg REQUIRED)
#-----------------------------------------------------------------------------
# Use files
set(QT_USE_QTOPENGL TRUE)
set(QT_USE_QTXML TRUE)
include (${QT_USE_FILE})
#-----------------------------------------------------------------------------
# Include directories
INCLUDE_DIRECTORIES (
${QGLVIEWER_INCLUDE_DIR}
${CG_INCLUDE_PATH}
${GLEW_INCLUDE_PATH}
${GLUT_INCLUDE_DIR}
)
#-----------------------------------------------------------------------------
# Definitions
ADD_DEFINITIONS(
${QGLVIEWER_DEFINITIONS}
)
#-----------------------------------------------------------------------------
# Save include directories
#set(EXTRA_INCLUDE_DIRS ${Teem_INCLUDE_DIRS} ${QT_INCLUDE_DIRS})
#-----------------------------------------------------------------------------
# Save library directories
#set(EXTRA_LIBRARY_DIRS ${Teem_LIBRARY_DIRS} ${QT_LIBRARY_DIRS})
#-----------------------------------------------------------------------------
# Configure libraries
set(LIBS ${LIBS} ${CG_LIBRARY} ${CG_GL_LIBRARY} ${QT_LIBRARIES} ${Boost_LIBRARIES} ${QGLVIEWER_LIBRARY} ${GLUT_LIBRARIES} ${GLEW_LIBRARY})
#-----------------------------------------------------------------------------
# Configure destination dirs
SET (LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib CACHE INTERNAL "Single output directory for building all libraries.")
MARK_AS_ADVANCED (LIBRARY_OUTPUT_PATH)
SET (IBI_LIBRARY_PATH "${LIBRARY_OUTPUT_PATH}")
#-----------------------------------------------------------------------------
# Dispatch the build into source subdirectory
ADD_SUBDIRECTORY (src)
#-----------------------------------------------------------------------------
# Prepare installation
#FOREACH (libname ${IBI_SUBLIBS})
#ENDFOREACH (libname ${IBI_SUBLIBS})
#-----------------------------------------------------------------------------
# Help outside projects build IBI projects.
INCLUDE (CMakeExportBuildSettings)
EXPORT_LIBRARY_DEPENDENCIES(${IBI_BINARY_DIR}/IBILibraryDepends.cmake)
CMAKE_EXPORT_BUILD_SETTINGS(${IBI_BINARY_DIR}/IBIBuildSettings.cmake)
# IBI_CV_ prefixed variables are only used inside IBIConfig.cmake.in for
# replacement during the following two CONFIGURE_FILE calls. One is for use
# from the build tree, one is for use from the install tree.
# For build tree usage
# In the build tree, IBIConfig.cmake is in IBI_BINARY_DIR. The root of the
# tree for finding include files relative to IBIConfig.cmake is "."
#
SET(IBI_CV_CONFIG_TO_ROOT ".")
SET(IBI_CV_LIBRARY_DEPENDS_FILE ${IBI_BINARY_DIR}/IBILibraryDepends.cmake)
#SET(IBI_CV_EXECUTABLE_DIRS ${IBI_EXECUTABLE_DIRS})
#MESSAGE (STATUS "${IBI_LIBRARY_PATH}")
SET(IBI_CV_LIBRARY_DIRS ${LIBRARY_OUTPUT_PATH})
SET(IBI_CV_USE_FILE ${IBI_SOURCE_DIR}/CMake/IBIUse.cmake)
SET(IBI_CV_INCLUDE_DIRS "${IBI_SOURCE_DIR}/src/ibi")
SET(IBI_CV_BUILD_SETTINGS_FILE ${IBI_BINARY_DIR}/IBIBuildSettings.cmake)
SET(IBI_CV_BUILT_LIBRARIES ibi) # The libraries built by ibi.
CONFIGURE_FILE("${IBI_SOURCE_DIR}/CMake/IBIConfig.cmake"
"${IBI_BINARY_DIR}/IBIConfig.cmake" @ONLY IMMEDIATE)
# For install tree usage
# In the install tree, TeemConfig.cmake is in lib or lib/Teem-X.Y based on the
# value of Teem_USE_LIB_INSTALL_SUBDIR. The root of the tree for finding
# include files relative to TeemConfig.cmake is therefore ".." or "../.."
#
#IF(Teem_USE_LIB_INSTALL_SUBDIR)
# SET(Teem_CV_CONFIG_TO_ROOT "../..")
#ELSE(Teem_USE_LIB_INSTALL_SUBDIR)
# SET(Teem_CV_CONFIG_TO_ROOT "..")
#ENDIF(Teem_USE_LIB_INSTALL_SUBDIR)
#SET(Teem_CV_LIBRARY_DEPENDS_FILE "\${Teem_ROOT_DIR}/lib${EXTRA_INSTALL_PATH}/TeemLibraryDepends.cmake")
#SET(Teem_CV_EXECUTABLE_DIRS "\${Teem_ROOT_DIR}/bin")
#SET(Teem_CV_LIBRARY_DIRS "\${Teem_ROOT_DIR}/lib${EXTRA_INSTALL_PATH}")
#SET(Teem_CV_USE_FILE "\${Teem_ROOT_DIR}/lib${EXTRA_INSTALL_PATH}/TeemUse.cmake")
#SET(Teem_CV_INCLUDE_DIRS "\${Teem_ROOT_DIR}/include")
#SET(Teem_CV_BUILD_SETTINGS_FILE "\${Teem_ROOT_DIR}/lib${EXTRA_INSTALL_PATH}/TeemBuildSettings.cmake")
#SET(Teem_CV_BUILT_LIBRARIES teem) # The libraries built by teem. Currently we only build the mega library.
#CONFIGURE_FILE("${Teem_SOURCE_DIR}/CMake/TeemConfig.cmake.in"
# "${Teem_BINARY_DIR}/CMake/TeemConfig.cmake" @ONLY IMMEDIATE)
#INSTALL(FILES ${Teem_INSTALLED_HEADER_FILES}
# DESTINATION include/teem
# )
#INSTALL(FILES
# "${Teem_BINARY_DIR}/CMake/TeemConfig.cmake"
# "${Teem_SOURCE_DIR}/CMake/TeemUse.cmake"
# "${Teem_BINARY_DIR}/TeemBuildSettings.cmake"
# "${Teem_BINARY_DIR}/TeemLibraryDepends.cmake"
# DESTINATION lib${EXTRA_INSTALL_PATH}
# )
<file_sep>/*
* Texture.cpp
*
* Created on: Oct 15, 2009
* Author: <NAME>
*/
#include "Texture.h"
#include "ibi_error/Exception.h"
BEGIN_NAMESPACE_IBI
using namespace std;
Texture::Texture() :
glname(0), dimension(2), width(0), height(0), depth(0)
{
target = GL_TEXTURE_2D;
}
Texture::~Texture()
{
glDeleteTextures(1, &glname);
}
void Texture::setGLName(GLuint name)
{
this->glname = name;
}
void Texture::setTarget(GLenum target)
{
this->target = target;
}
void Texture::setDimensions(int w, int h, int d)
{
this->width = w;
this->height = h;
this->depth = d;
}
void Texture::setDimension(int dim)
{
this->dimension = dim;
}
int Texture::getDimension()
{
return dimension;
}
int Texture::getWidth()
{
return this->width;
}
int Texture::getHeight()
{
return this->height;
}
int Texture::getDepth()
{
return this->depth;
}
GLuint Texture::getGLName()
{
return this->glname;
}
GLenum Texture::getTarget()
{
return this->target;
}
void Texture::enable()
{
if (glname)
{
glEnable(target);
glBindTexture(target, glname);
}
else
{
throw Exception("Texture.cpp", "Problem with texture.",
"Missing texture name.");
}
}
void Texture::disable()
{
glDisable(target);
}
void Texture::init()
{
// Generate a name
glGenTextures(1, &this->glname);
}
END_NAMESPACE_IBI
<file_sep>/*
* TextureLoadingInfo.cpp
*
* Created on: Nov 23, 2009
* Author: <NAME>
*/
#include "TextureLoadingInfo.h"
BEGIN_NAMESPACE_IBI
TextureLoadingInfo::TextureLoadingInfo()
{
target = GL_TEXTURE_2D;
dim = 2;
width = 256;
height = 256;
depth = 0;
level = 0;
internalformat = GL_RGBA;
border = 0;
format = GL_RGBA;
type = GL_FLOAT;
data = 0;
destroydata = false;
}
TextureLoadingInfo::~TextureLoadingInfo()
{
if (destroydata)
{
delete[] (char*) data;
}
}
}
<file_sep>/*
* texture_loader_qt.cpp
*
* Created on: Nov 2, 2009
* Author: juanmarcus
*/
#include "ibi_internal.h"
#include "ibi_texturemanager/TextureManager.h"
#include "ibi_gl/Texture.h"
#include <boost/any.hpp>
#include <teem/nrrd.h>
#include "nrrdGLutils.h"
using BEGIN_NAMESPACE_IBI;
class TextureLoader_nrrd: public TextureLoader
{
void load(TextureLoadingInfo& info, Texture* texture)
{
Nrrd* nin = boost::any_cast<Nrrd*>(info.options["nrrd"]);
// Nrrd* nout = nrrdNew();
// nrrdConvert(nout,nin,nrrdTypeUChar);
// nrrdQuantize(nout, nin, 0, 8);
int width = nin->axis[0].size;
int height = nin->axis[1].size;
int elemsize = nrrdElementSize(nin);
// Copy memory upside-down
char* tmpdata = (char*) malloc(width * height * elemsize);
char* src = (char*) nin->data;
for (int i = 0; i < height; ++i)
{
int linesize = width * elemsize;
memcpy(&tmpdata[(height - i - 1) * linesize], &src[i * linesize],
linesize);
}
GLuint name = texture->getGLName();
glTexImage2D(info.target, 0, 1, width, height, 0, GL_LUMINANCE,
convert_type_to_enum(nin->type), tmpdata);
texture->setDimensions(width, height);
free(tmpdata);
// nrrdNuke(nout);
}
};
class TextureLoaderFactory_nrrd: public TextureLoaderFactory
{
TextureLoader* create()
{
TextureLoader* loader = new TextureLoader_nrrd();
return loader;
}
};
extern "C"
{
void registerPlugin(TextureManager& manager)
{
TextureLoaderFactory_nrrd* loaderF = new TextureLoaderFactory_nrrd();
manager.registerTextureLoader(String("nrrd"), loaderF);
}
}
<file_sep>/*
* TextureManager.h
*
* Created on: Nov 2, 2009
* Author: juanmarcus
*/
#ifndef TEXTUREMANAGER_H_
#define TEXTUREMANAGER_H_
#include "ibi_internal.h"
#include <vector>
#include "TextureLoader.h"
BEGIN_NAMESPACE_IBI
{
class TextureManager
{
protected:
TextureManager();
public:
static TextureManager* getInstance();
~TextureManager();
void registerTextureLoader(String type,
TextureLoaderFactory* textureLoaderFactory);
void loadPlugin(String filename);
Texture* load(TextureLoadingInfo& info);
private:
std::map<String, TextureLoader*> loaders;
std::vector<void*> loadedPlugins;
static TextureManager* instance;
};
END_NAMESPACE_IBI
#endif /* TEXTUREMANAGER_H_ */
<file_sep>/*
* FramebufferObject.cpp
*
* Created on: Nov 5, 2009
* Author: juanmarcus
*/
#include "FramebufferObject.h"
#include "ibi_error/Exception.h"
BEGIN_NAMESPACE_IBI
FramebufferObject::FramebufferObject() :
enabled(false)
{
glewInit();
}
FramebufferObject::~FramebufferObject()
{
glDeleteFramebuffersEXT(1, &name);
}
void FramebufferObject::init()
{
glGenFramebuffersEXT(1, &name);
}
void FramebufferObject::bind()
{
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, name);
// Bind target texture
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
target->getTarget(), target->getGLName(), 0);
checkStatus();
// Save old viewport
glGetIntegerv(GL_VIEWPORT, oldViewport);
glViewport(0, 0, target->getWidth(), target->getHeight());
enabled = true;
}
void FramebufferObject::release()
{
if (!enabled)
{
throw Exception("FramebufferObject.cpp", "Problem finishing render.",
"Trying to operate on a disabled FramebufferObject object.");
}
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
// Restore old viewport
glViewport(oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3]);
enabled = false;
}
void FramebufferObject::setTarget(Texture* t)
{
this->target = t;
}
void FramebufferObject::checkStatus()
{
GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
{
throw Exception("FramebufferObject.cpp",
"FramebufferObject consistence problem.",
"FramebufferObject state incomplete.");
}
}
END_NAMESPACE_IBI
<file_sep>/*
* Matrix3.h
*
* Created on: Oct 27, 2009
* Author: <NAME>
*/
#ifndef MATRIX3_H_
#define MATRIX3_H_
#include "ibi_internal.h"
#include "Vector3.h"
#include <memory>
BEGIN_NAMESPACE_IBI
class Matrix3
{
public:
/** Default constructor.
@note
It does <b>NOT</b> initialize the matrix for efficiency.
*/
inline Matrix3()
{
}
;
inline explicit Matrix3(const Real arr[3][3])
{
memcpy(m, arr, 9 * sizeof(Real));
}
inline Matrix3(const Matrix3& rkMatrix)
{
memcpy(m, rkMatrix.m, 9 * sizeof(Real));
}
Matrix3(Real fEntry00, Real fEntry01, Real fEntry02, Real fEntry10,
Real fEntry11, Real fEntry12, Real fEntry20, Real fEntry21,
Real fEntry22)
{
m[0][0] = fEntry00;
m[0][1] = fEntry01;
m[0][2] = fEntry02;
m[1][0] = fEntry10;
m[1][1] = fEntry11;
m[1][2] = fEntry12;
m[2][0] = fEntry20;
m[2][1] = fEntry21;
m[2][2] = fEntry22;
}
// member access, allows use of construct mat[r][c]
inline Real* operator[](size_t iRow) const
{
return (Real*) m[iRow];
}
/*inline operator Real* ()
{
return (Real*)m[0];
}*/
Vector3 GetColumn(size_t iCol) const;
void SetColumn(size_t iCol, const Vector3& vec);
void FromAxes(const Vector3& xAxis, const Vector3& yAxis,
const Vector3& zAxis);
// assignment and comparison
inline Matrix3& operator=(const Matrix3& rkMatrix)
{
memcpy(m, rkMatrix.m, 9 * sizeof(Real));
return *this;
}
bool operator==(const Matrix3& rkMatrix) const;
inline bool operator!=(const Matrix3& rkMatrix) const
{
return !operator==(rkMatrix);
}
// arithmetic operations
Matrix3 operator+(const Matrix3& rkMatrix) const;
Matrix3 operator-(const Matrix3& rkMatrix) const;
Matrix3 operator*(const Matrix3& rkMatrix) const;
Matrix3 operator-() const;
// matrix * vector [3x3 * 3x1 = 3x1]
Vector3 operator*(const Vector3& rkVector) const;
// vector * matrix [1x3 * 3x3 = 1x3]
friend Vector3 operator*(const Vector3& rkVector, const Matrix3& rkMatrix);
// matrix * scalar
Matrix3 operator*(Real fScalar) const;
// scalar * matrix
friend Matrix3 operator*(Real fScalar, const Matrix3& rkMatrix);
// utilities
Matrix3 Transpose() const;
bool Inverse(Matrix3& rkInverse, Real fTolerance = 1e-06) const;
Matrix3 Inverse(Real fTolerance = 1e-06) const;
Real Determinant() const;
// singular value decomposition
void
SingularValueDecomposition(Matrix3& rkL, Vector3& rkS, Matrix3& rkR) const;
void SingularValueComposition(const Matrix3& rkL, const Vector3& rkS,
const Matrix3& rkR);
// Gram-Schmidt orthonormalization (applied to columns of rotation matrix)
void Orthonormalize();
// orthogonal Q, diagonal D, upper triangular U stored as (u01,u02,u12)
void QDUDecomposition(Matrix3& rkQ, Vector3& rkD, Vector3& rkU) const;
Real SpectralNorm() const;
// matrix must be orthonormal
void ToAxisAngle(Vector3& rkAxis, Radian& rfAngle) const;
inline void ToAxisAngle(Vector3& rkAxis, Degree& rfAngle) const
{
Radian r;
ToAxisAngle(rkAxis, r);
rfAngle = r;
}
void FromAxisAngle(const Vector3& rkAxis, const Radian& fRadians);
// The matrix must be orthonormal. The decomposition is yaw*pitch*roll
// where yaw is rotation about the Up vector, pitch is rotation about the
// Right axis, and roll is rotation about the Direction axis.
bool
ToEulerAnglesXYZ(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const;
bool
ToEulerAnglesXZY(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const;
bool
ToEulerAnglesYXZ(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const;
bool
ToEulerAnglesYZX(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const;
bool
ToEulerAnglesZXY(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const;
bool
ToEulerAnglesZYX(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const;
void FromEulerAnglesXYZ(const Radian& fYAngle, const Radian& fPAngle,
const Radian& fRAngle);
void FromEulerAnglesXZY(const Radian& fYAngle, const Radian& fPAngle,
const Radian& fRAngle);
void FromEulerAnglesYXZ(const Radian& fYAngle, const Radian& fPAngle,
const Radian& fRAngle);
void FromEulerAnglesYZX(const Radian& fYAngle, const Radian& fPAngle,
const Radian& fRAngle);
void FromEulerAnglesZXY(const Radian& fYAngle, const Radian& fPAngle,
const Radian& fRAngle);
void FromEulerAnglesZYX(const Radian& fYAngle, const Radian& fPAngle,
const Radian& fRAngle);
// eigensolver, matrix must be symmetric
void
EigenSolveSymmetric(Real afEigenvalue[3], Vector3 akEigenvector[3]) const;
static void TensorProduct(const Vector3& rkU, const Vector3& rkV,
Matrix3& rkProduct);
/** Determines if this matrix involves a scaling. */
inline bool hasScale() const
{
// check magnitude of column vectors (==local axes)
Real t = m[0][0] * m[0][0] + m[1][0] * m[1][0] + m[2][0] * m[2][0];
if (!Math::RealEqual(t, 1.0, 1e-04))
return true;
t = m[0][1] * m[0][1] + m[1][1] * m[1][1] + m[2][1] * m[2][1];
if (!Math::RealEqual(t, 1.0, 1e-04))
return true;
t = m[0][2] * m[0][2] + m[1][2] * m[1][2] + m[2][2] * m[2][2];
if (!Math::RealEqual(t, 1.0, 1e-04))
return true;
return false;
}
static const Real EPSILON;
static const Matrix3 ZERO;
static const Matrix3 IDENTITY;
protected:
// support for eigensolver
void Tridiagonal(Real afDiag[3], Real afSubDiag[3]);
bool QLAlgorithm(Real afDiag[3], Real afSubDiag[3]);
// support for singular value decomposition
static const Real ms_fSvdEpsilon;
static const unsigned int ms_iSvdMaxIterations;
static void Bidiagonalize(Matrix3& kA, Matrix3& kL, Matrix3& kR);
static void GolubKahanStep(Matrix3& kA, Matrix3& kL, Matrix3& kR);
// support for spectral norm
static Real MaxCubicRoot(Real afCoeff[3]);
Real m[3][3];
// for faster access
friend class Matrix4;
};
END_NAMESPACE_IBI
#endif /* MATRIX3_H_ */
<file_sep>/*
* texture_loader_qt.cpp
*
* Created on: Nov 2, 2009
* Author: juanmarcus
*/
#include "ibi_internal.h"
#include "ibi_texturemanager/TextureManager.h"
#include "ibi_gl/Texture.h"
#include "ibi_error/Exception.h"
#include <boost/any.hpp>
#include <QtGui/QImage>
#include <QtOpenGL/QGLWidget>
using BEGIN_NAMESPACE_IBI;
class TextureLoader_transfer_func: public TextureLoader
{
void load(TextureLoadingInfo& info, Texture* texture)
{
String filename = boost::any_cast<String>(info.options["filename"]);
QImage t;
QImage b;
if (!b.load(filename.c_str()))
{
throw Exception("texture_loader_transfer_func.cpp",
"Problem loading texture.", "File not found: " + filename);
}
t = QGLWidget::convertToGLFormat(b);
glTexParameteri(info.target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexImage1D(info.target, 0, GL_RGBA, t.width(), 0, GL_RGBA,
GL_UNSIGNED_BYTE, t.bits());
texture->setDimensions(t.width());
}
};
class TextureLoaderFactory_transfer_func: public TextureLoaderFactory
{
TextureLoader* create()
{
TextureLoader* loader = new TextureLoader_transfer_func();
return loader;
}
};
extern "C"
{
void registerPlugin(TextureManager& manager)
{
TextureLoaderFactory_transfer_func* loaderF =
new TextureLoaderFactory_transfer_func();
manager.registerTextureLoader(String("transfer_func"), loaderF);
}
}
<file_sep>/*
* Triangle.cpp
*
* Created on: Oct 28, 2009
* Author: juanmarcus
*/
#include "Triangle.h"
BEGIN_NAMESPACE_IBI
END_NAMESPACE_IBI
<file_sep>/*
* TestScene.h
*
* Created on: Nov 4, 2009
* Author: juanmarcus
*/
#ifndef TESTSCENE_H_
#define TESTSCENE_H_
class TestScene
{
public:
static inline void draw()
{
glEnable( GL_LIGHTING);
glEnable( GL_LIGHT0);
GLfloat diffuse[3] =
{ 1.0, 1.0, 1.0 };
GLfloat black[3] =
{ 0.0, 0.0, 0.0 };
GLfloat ambient[] =
{ 0.2f, 0.2f, 0.2f, 1.0f };
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
glLightfv(GL_LIGHT0, GL_SPECULAR, diffuse);
GLfloat lightPosition[4];
lightPosition[0] = 0;
lightPosition[1] = 3;
lightPosition[2] = 0;
lightPosition[3] = 1;
glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
glDisable( GL_COLOR_MATERIAL);
glMaterialfv(GL_FRONT, GL_EMISSION, diffuse);
GLfloat materialDiffuseRed[3] =
{ 1.0, 0.0, 0.0 };
GLfloat materialDiffuseGreen[3] =
{ 0.0, 1.0, 0.0 };
GLfloat materialDiffuseBlue[3] =
{ 0.0, 0.0, 1.0 };
GLfloat materialDiffuseYellow[3] =
{ 1.0, 1.0, 0.0 };
GLfloat materialDiffuseMagenta[3] =
{ 1.0, 0.0, 1.0 };
GLfloat materialDiffusef[3] =
{ 0.0, 1.0, 1.0 };
glMaterialfv(GL_FRONT, GL_EMISSION, black);
glMaterialfv(GL_FRONT, GL_SPECULAR, diffuse);
glMaterialf(GL_FRONT, GL_SHININESS, 60);
glTranslatef(2, 0, 0);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, materialDiffuseRed);
glutSolidTeapot(1.0f);
glTranslatef(0, 2, 0);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, materialDiffuseGreen);
glutSolidTeapot(1.0f);
glTranslatef(0, -4, 0);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, materialDiffuseBlue);
glutSolidTeapot(1.0f);
glTranslatef(0, 2, 0);
glTranslatef(-4, 0, 0);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, materialDiffuseYellow);
glutSolidTeapot(1.0f);
glTranslatef(0, 2, 0);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, materialDiffuseMagenta);
glutSolidTeapot(1.0f);
glTranslatef(0, -4, 0);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, materialDiffusef);
glutSolidTeapot(1.0f);
}
};
#endif /* TESTSCENE_H_ */
<file_sep>/*
* SceneGraph.cpp
*
* Created on: Dec 1, 2009
* Author: <NAME>
*/
#include "SceneGraph.h"
BEGIN_NAMESPACE_IBI
SceneGraph::SceneGraph()
{
rootSceneNode = new SceneNode();
}
SceneGraph::~SceneGraph()
{
delete rootSceneNode;
}
SceneNode* SceneGraph::getRootSceneNode()
{
return rootSceneNode;
}
void SceneGraph::update(bool render)
{
rootSceneNode->update(render);
}
END_NAMESPACE_IBI
<file_sep>/*
* Renderable.h
*
* Created on: Dec 1, 2009
* Author: <NAME>
*/
#ifndef RENDERABLE_H_
#define RENDERABLE_H_
#include "ibi_internal.h"
BEGIN_NAMESPACE_IBI
class Renderable
{
public:
Renderable();
virtual ~Renderable();
virtual void render() = 0;
};
END_NAMESPACE_IBI
#endif /* RENDERABLE_H_ */
<file_sep>/*
* test_cmdline.cpp
*
* Created on: Oct 22, 2009
* Author: <NAME>
*/
#include "ibi_cmdline/CommandLineParser.h"
#include <string>
using namespace std;
using namespace ibi;
int main(int argc, char **argv)
{
string input;
int intvalue;
float floatvalue;
CommandLineParser p;
p.addOption("input,i", value<string> (&input), "input file", false);
p.addOption("intvalue,e", value<int> (&intvalue), "int value", true);
p.addOption("floatvalue,f", value<float> (&floatvalue), "float value", true);
if (!p.parse(argc, argv))
{
return 1;
}
return 0;
}
<file_sep>/*
* GPUProgram.cpp
*
* Created on: Nov 4, 2009
* Author: juanmarcus
*/
#include "GPUProgram.h"
#include <Cg/cgGL.h>
#include "GPUProgramManager.h"
BEGIN_NAMESPACE_IBI
GPUProgram::GPUProgram(GPUProgramManager* a_parent) :
parent(a_parent)
{
}
GPUProgram::~GPUProgram()
{
}
void GPUProgram::enable()
{
cgGLBindProgram(program);
cgGLEnableProfile(profile);
parent->checkError();
}
void GPUProgram::disable()
{
cgGLDisableProfile(profile);
}
GPUProgram::Parameter GPUProgram::getNamedParameter(String name)
{
GPUProgram::Parameter par;
CGparameter cgparam = cgGetNamedParameter(program, name.c_str());
parent->checkError();
par.cgparameter = cgparam;
return par;
}
void GPUProgram::Parameter::setTexture(Texture* t)
{
cgGLSetTextureParameter(cgparameter, t->getGLName());
cgGLEnableTextureParameter(cgparameter);
}
END_NAMESPACE_IBI
<file_sep>
# plugins
FILE (GLOB cpp_sources "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
FOREACH (cpp_source ${cpp_sources})
get_filename_component (target ${cpp_source} NAME_WE)
add_library (${target} SHARED ${cpp_source})
target_link_libraries (${target} ${LIBS})
ENDFOREACH (cpp_source)<file_sep>/*
* GPUProgram.h
*
* Created on: Nov 4, 2009
* Author: juanmarcus
*/
#ifndef GPUPROGRAM_H_
#define GPUPROGRAM_H_
#include "ibi_internal.h"
#include "ibi_gl/ibi_gl.h"
#include "ibi_gl/Texture.h"
#include <Cg/cg.h>
BEGIN_NAMESPACE_IBI
class GPUProgramManager;
class GPUProgram
{
public:
friend class GPUProgramManager;
class Parameter
{
public:
void setTexture(Texture* t);
public:
CGparameter cgparameter;
};
GPUProgram(GPUProgramManager* parent);
~GPUProgram();
void enable();
void disable();
Parameter getNamedParameter(String name);
protected:
CGprofile profile;
CGprogram program;
GPUProgramManager* parent;
};
END_NAMESPACE_IBI
#endif /* GPUPROGRAM_H_ */
<file_sep>/*
* TextureLoader.h
*
* Created on: Oct 15, 2009
* Author: <NAME>
*/
#ifndef TEXTURELOADER_H_
#define TEXTURELOADER_H_
#include "ibi_internal.h"
#include "ibi_factory/Factory.h"
#include "ibi_gl/Texture.h"
BEGIN_NAMESPACE_IBI
{
/*
* Texture loader interface.
*/
class TextureLoader
{
public:
virtual void load(TextureLoadingInfo& info, Texture* t) = 0;
};
/*
* Creates texture loaders.
*/
typedef Factory<TextureLoader> TextureLoaderFactory;
END_NAMESPACE_IBI
#endif /* TEXTURELOADER_H_ */
<file_sep>#include "ibiQFunctorGLViewer.h"
BEGIN_NAMESPACE_IBI
ibiQFunctorGLViewer::ibiQFunctorGLViewer(InitializeFunctor& a_initer,
DrawFunctor& a_painter) :
ibiQGLViewer(), initer(a_initer), drawer(a_painter)
{
}
ibiQFunctorGLViewer::~ibiQFunctorGLViewer()
{
}
void ibiQFunctorGLViewer::draw()
{
drawer(this);
}
void ibiQFunctorGLViewer::init()
{
initer(this);
}
//void ibiQFunctorGLViewer::resizeGL(int w, int h)
//{
// resizer(this, w, h);
//}
END_NAMESPACE_IBI
<file_sep>/*
* Intersection.cpp
*
* Created on: Oct 28, 2009
* Author: juanmarcus
*/
#include "Intersection.h"
BEGIN_NAMESPACE_IBI
std::pair<bool, RealPair> Intersection::intersects(const Ray& ray,
const AxisAlignedBox& box)
{
if (box.isNull())
return std::pair<bool, RealPair>(false, RealPair(0, 0));
if (box.isInfinite())
{
return std::pair<bool, RealPair>(true, RealPair(0, Math::POS_INFINITY));
}
const Vector3& min = box.getMinimum();
const Vector3& max = box.getMaximum();
const Vector3& rayorig = ray.getOrigin();
const Vector3& raydir = ray.getDirection();
Vector3 absDir;
absDir[0] = Math::Abs(raydir[0]);
absDir[1] = Math::Abs(raydir[1]);
absDir[2] = Math::Abs(raydir[2]);
// Sort the axis, ensure check minimise floating error axis first
int imax = 0, imid = 1, imin = 2;
if (absDir[0] < absDir[2])
{
imax = 2;
imin = 0;
}
if (absDir[1] < absDir[imin])
{
imid = imin;
imin = 1;
}
else if (absDir[1] > absDir[imax])
{
imid = imax;
imax = 1;
}
Real start = 0, end = Math::POS_INFINITY;
#define _CALC_AXIS(i) \
do { \
Real denom = 1 / raydir[i]; \
Real newstart = (min[i] - rayorig[i]) * denom; \
Real newend = (max[i] - rayorig[i]) * denom; \
if (newstart > newend) std::swap(newstart, newend); \
if (newstart > end || newend < start) return std::pair<bool, RealPair>(false, RealPair(0, 0)); \
if (newstart > start) start = newstart; \
if (newend < end) end = newend; \
} while(0)
// Check each axis in turn
_CALC_AXIS(imax);
if (absDir[imid] < std::numeric_limits<Real>::epsilon())
{
// Parallel with middle and minimise axis, check bounds only
if (rayorig[imid] < min[imid] || rayorig[imid] > max[imid]
|| rayorig[imin] < min[imin] || rayorig[imin] > max[imin])
return std::pair<bool, RealPair>(false, RealPair(0, 0));
}
else
{
_CALC_AXIS(imid);
if (absDir[imin] < std::numeric_limits<Real>::epsilon())
{
// Parallel with minimise axis, check bounds only
if (rayorig[imin] < min[imin] || rayorig[imin] > max[imin])
return std::pair<bool, RealPair>(false, RealPair(0, 0));
}
else
{
_CALC_AXIS(imin);
}
}
#undef _CALC_AXIS
return std::pair<bool, RealPair>(true, RealPair(start, end));
}
std::pair<bool, Real> Intersection::intersects(const Ray& ray,
const Triangle& triangle)
{
Vector3 u, v, n; // triangle vectors
Vector3 dir, w0, w; // ray vectors
Real r, a, b; // params to calc ray-plane intersect
// get triangle edge vectors and plane normal
u = triangle.getVertex(1) - triangle.getVertex(0);
v = triangle.getVertex(2) - triangle.getVertex(0);
n = u.crossProduct(v);
if (n == Vector3::ZERO) // triangle is degenerate
return std::pair<bool, Real>(false, 0);
dir = ray.getDirection(); // ray direction vector
w0 = ray.getOrigin() - triangle.getVertex(0);
a = -n.dotProduct(w0);
b = n.dotProduct(dir);
if (Math::Abs(b) < 0.00000001)
{ // ray is parallel to triangle plane
if (a == 0) // ray lies in triangle plane
return std::pair<bool, Real>(false, 0);
else
return std::pair<bool, Real>(false, 0); // ray disjoint from plane
}
// get intersect point of ray with triangle plane
r = a / b;
if (r < 0.0) // ray goes away from triangle
return std::pair<bool, Real>(false, 0); // => no intersect
Vector3 I = ray * r; // intersect point of ray and plane
// is I inside T?
float uu, uv, vv, wu, wv, D;
uu = u.dotProduct(u);
uv = u.dotProduct(v);
vv = v.dotProduct(v);
w = I - triangle.getVertex(0);
wu = w.dotProduct(u);
wv = w.dotProduct(v);
D = uv * uv - uu * vv;
// get and test parametric coords
float s, t;
s = (uv * wv - vv * wu) / D;
if (s < 0.0 || s > 1.0) // I is outside T
return std::pair<bool, Real>(false, 0);
t = (uv * wu - uu * wv) / D;
if (t < 0.0 || (s + t) > 1.0) // I is outside T
return std::pair<bool, Real>(false, 0);
return std::pair<bool, Real>(true, r); // I is in T
}
END_NAMESPACE_IBI
<file_sep>/*
* test_interpolation.cpp
*
* Created on: Oct 29, 2009
* Author: <NAME>
*/
#include "ibi_gl/ibi_gl.h"
#include <QtGui/QApplication>
#include <QGLViewer/qglviewer.h>
#include <iostream>
#include "ibi_geometry/Ray.h"
#include "ibi_geometry/Vector3.h"
#include "ibi_geometry/Matrix4.h"
#include "ibi_geometry/AxisAlignedBox.h"
#include "ibi_gl/GeometryDrawer.h"
#include "ibi_geometry/Transform.h"
#include "ibi_interpolation/Interpolation.h"
using namespace std;
using namespace ibi;
class Viewer: public QGLViewer
{
public:
Viewer(QWidget* parent = 0) :
QGLViewer(parent)
{
}
~Viewer()
{
}
void init()
{
setSceneRadius(2.0);
showEntireScene();
// restoreStateFromFile();
box.setExtents(-1, -1, -1, 1, 1, 1);
p1 = Vector3(1, 1, 1);
p2 = Vector3(-1, -1, -1);
}
void draw()
{
glColor3f(1.0, 1.0, 1.0);
// Draw point at the origin
drawer.drawPoint(Vector3::ZERO);
// Draw a box
drawer.drawAxisAlignedBox(box);
glColor3f(0.0, 0.0, 1.0);
ipoints = Interpolation::interpolate(p1, p2, 100);
drawer.drawPoints(ipoints);
}
private:
GeometryDrawer drawer;
AxisAlignedBox box;
Vector3 p1, p2;
std::vector<Vector3> ipoints;
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
Viewer w;
w.showMaximized();
return app.exec();
}
<file_sep>/*
* SceneGraph.h
*
* Created on: Dec 1, 2009
* Author: <NAME>
*/
#ifndef SCENEGRAPH_H_
#define SCENEGRAPH_H_
#include "ibi_internal.h"
#include "SceneNode.h"
BEGIN_NAMESPACE_IBI
class SceneGraph
{
public:
SceneGraph();
virtual ~SceneGraph();
SceneNode* getRootSceneNode();
void update(bool render = true);
private:
/**
* Root SceneNode.
*/
SceneNode* rootSceneNode;
};
END_NAMESPACE_IBI
#endif /* SCENEGRAPH_H_ */
<file_sep>IF(NOT IBI_FOUND)
MESSAGE(FATAL_ERROR "Something went wrong. You are including IBIUse.cmake but IBI was not found")
ENDIF(NOT IBI_FOUND)
# Make IBI easier to use
LINK_DIRECTORIES(${IBI_LIBRARY_DIRS})
INCLUDE_DIRECTORIES (${IBI_INCLUDE_DIRS})
# Load the compiler settings used for IBI.
IF(IBI_BUILD_SETTINGS_FILE)
INCLUDE(CMakeImportBuildSettings)
CMAKE_IMPORT_BUILD_SETTINGS(${IBI_BUILD_SETTINGS_FILE})
ENDIF(IBI_BUILD_SETTINGS_FILE)
#IF (IBI_AUTO)
# MESSAGE (STATUS "including all IBI include dirs")
# INCLUDE_DIRECTORIES (${IBI_EXTRA_INCLUDE_DIRS})
#
# MESSAGE (STATUS "including all IBI extra library dirs")
# LINK_DIRECTORIES (${IBI_EXTRA_LIBRARY_DIRS})
#ENDIF (IBI_AUTO)<file_sep>/*
* Ray.h
*
* Created on: Oct 26, 2009
* Author: <NAME>
*/
#ifndef RAY_H_
#define RAY_H_
#include "ibi_internal.h"
#include "Vector3.h"
BEGIN_NAMESPACE_IBI
class Ray
{
protected:
Vector3 mOrigin;
Vector3 mDirection;
public:
Ray() :
mOrigin(Vector3::ZERO), mDirection(Vector3::UNIT_Z)
{
}
Ray(const Vector3& origin, const Vector3& direction) :
mOrigin(origin), mDirection(direction)
{
}
/** Sets the origin of the ray. */
void setOrigin(const Vector3& origin)
{
mOrigin = origin;
}
/** Gets the origin of the ray. */
const Vector3& getOrigin(void) const
{
return mOrigin;
}
/** Sets the direction of the ray. */
void setDirection(const Vector3& dir)
{
mDirection = dir;
}
/** Gets the direction of the ray. */
const Vector3& getDirection(void) const
{
return mDirection;
}
/** Gets the position of a point t units along the ray. */
Vector3 getPoint(Real t) const
{
return Vector3(mOrigin + (mDirection * t));
}
/** Gets the position of a point t units along the ray. */
Vector3 operator*(Real t) const
{
return getPoint(t);
}
;
};
END_NAMESPACE_IBI
#endif /* RAY_H_ */
<file_sep>#ifndef IBIQTSMARTGLWIDGET_H
#define IBIQTSMARTGLWIDGET_H
#include "ibi_internal.h"
#include "ibi_gl/ibi_gl.h"
#include "ibi_gl/GLMode2D.h"
#include "ibi_gl/Texture.h"
#include "ibi_gl/TextureLoadingInfo.h"
#include "ibi_geometry/Vector3.h"
#include <QGLViewer/qglviewer.h>
namespace ibi { // BEGIN_NAMESPACE_IBI
class ibiQGLViewer: public QGLViewer
{
Q_OBJECT
public:
ibiQGLViewer(QWidget *parent = 0, const QGLWidget *shareWidget = 0,
Qt::WFlags flags = 0);
ibiQGLViewer(QGLContext *context, QWidget *parent = 0,
const QGLWidget *shareWidget = 0, Qt::WFlags flags = 0);
ibiQGLViewer(const QGLFormat &format, QWidget *parent = 0,
const QGLWidget *shareWidget = 0, Qt::WFlags flags = 0);
~ibiQGLViewer();
// void init();
/*
* Starts drawing in 2D.
*/
void start2DMode();
/*
* Stops drawing in 2D and restores previous state.
*/
void stop2DMode();
/*
* Draws a full screen quad.
*/
void drawFullScreenQuad();
/**
* Returns normalized screen coordinates from Qt screen coordinates.
*/
Vector3 normalizedViewportCoordinates(int x, int y);
/*
* Return absolute screen coordinates from normalized coordinates.
*/
Vector3 absoluteViewportCoordinates(Vector3& point);
void resizeGL(int w, int h);
void setDesiredAspectRatio(float ratio);
void saveViewport();
void restoreViewport();
Texture* loadTexture(TextureLoadingInfo& info);
private:
GLMode2D mode2d;
int savedViewport[4];
float desiredAspectRatio;
};
} // END_NAMESPACE_IBI
#endif // IBIQTSMARTGLWIDGET_H
<file_sep>/*
* test_gpuprogram.cpp
*
* Created on: Nov 4, 2009
* Author: juanmarcus
*/
#include "ibi_gl/ibi_gl.h"
#include <QtGui/QApplication>
#include <iostream>
#include "ibi_qt/ibiQFunctorGLViewer.h"
#include "ibi_gl/Texture.h"
#include "ibi_gpuprogrammanager/GPUProgramManager.h"
#include "ibi_test_utils/TestScene.h"
using namespace std;
using namespace ibi;
Texture* t = 0;
VertexProgram* vertex_program;
FragmentProgram* fragment_program;
struct draw
{
void operator()(ibiQGLViewer* widget)
{
vertex_program->enable();
fragment_program->enable();
TestScene::draw();
vertex_program->disable();
fragment_program->disable();
}
};
struct init
{
GPUProgramManager shaderManager;
void operator()(ibiQGLViewer* widget)
{
shaderManager.init();
vertex_program = shaderManager.loadVertexProgram("Shaders/Phong.cg",
"MainVS");
fragment_program = shaderManager.loadFragmentProgram(
"Shaders/Phong.cg", "MainPS");
widget->setSceneRadius(4.0);
widget->showEntireScene();
// TextureLoadingInfo tinfo;
// tinfo.texture_type = "qt";
// tinfo.target = GL_TEXTURE_2D;
// tinfo.options["filename"] = String("data/image.png");
//
// TextureManager manager;
// manager.loadPlugin("build/lib/libtexture_loader_qt.so");
//
// t = manager.load(tinfo);
}
};
InitializeFunctor initer = init();
DrawFunctor drawer = draw();
int main(int argc, char **argv)
{
glutInit(&argc, argv);
QApplication app(argc, argv);
ibiQFunctorGLViewer w(initer, drawer);
w.showMaximized();
return app.exec();
}
<file_sep>/*
* TextureConfigurator_Qt.h
*
* Created on: Nov 24, 2009
* Author: <NAME>
*/
#ifndef TEXTURECONFIGURATOR_QT_H_
#define TEXTURECONFIGURATOR_QT_H_
BEGIN_NAMESPACE_IBI
class TextureConfigurator_Qt
{
public:
static inline TextureLoadingInfo fromQImage(QImage &image)
{
// Create the resulting object
TextureLoadingInfo info;
// Convert the image to OpenGL format
QImage t = QGLWidget::convertToGLFormat(image);
// Allocate and set memory
char* data = new char[t.numBytes()];
memcpy(data, t.bits(), t.numBytes());
info.internalformat = GL_RGBA;
info.width = t.width();
info.height = t.height();
info.format = GL_RGBA;
info.type = GL_UNSIGNED_BYTE;
info.data = data;
info.destroydata = true;
return info;
}
static inline TextureLoadingInfo fromQImage1D(QImage &image)
{
// Create the resulting object
TextureLoadingInfo info;
// Convert the image to OpenGL format
QImage t = QGLWidget::convertToGLFormat(image);
// Allocate and set memory
char* data = new char[t.bytesPerLine()];
memcpy(data, t.bits(), t.bytesPerLine());
info.target = GL_TEXTURE_1D;
info.dim = 1;
info.internalformat = GL_RGBA;
info.width = t.width();
info.format = GL_RGBA;
info.type = GL_UNSIGNED_BYTE;
info.data = data;
info.destroydata = true;
return info;
}
static inline TextureLoadingInfo fromFilename(QString filename)
{
QImage img(filename);
return fromQImage(img);
}
};
}
#endif /* TEXTURECONFIGURATOR_QT_H_ */
<file_sep>/*
* Wrapper.h
*
* Created on: Oct 27, 2009
* Author: <NAME>
*/
#ifndef WRAPPER_H_
#define WRAPPER_H_
#include "ibi_internal.h"
#include "ibi_gl.h"
#include "ibi_geometry/Vector3.h"
#include "ibi_geometry/Matrix3.h"
BEGIN_NAMESPACE_IBI
class GL
{
public:
static inline void Translate(const Vector3& vec)
{
glTranslatef(vec.x, vec.y, vec.z);
}
static inline void Rotate(const Quaternion& q)
{
Matrix3 m3;
Vector3 axis;
Radian angle;
q.ToRotationMatrix(m3);
m3.ToAxisAngle(axis, angle);
glRotatef(angle.valueDegrees(), axis.x, axis.y, axis.z);
}
};
END_NAMESPACE_IBI
#endif /* WRAPPER_H_ */
<file_sep>/*
* GLMode2D.h
*
* Created on: Oct 14, 2009
* Author: <NAME>
*/
#ifndef GLMODE2D_H_
#define GLMODE2D_H_
#include "ibi_internal.h"
#include "ibi_gl.h"
BEGIN_NAMESPACE_IBI
class GLMode2D
{
public:
GLMode2D();
~GLMode2D();
void setScreenDimensions(int w, int h);
void enable();
void disable();
void drawFullScreenQuad();
private:
bool active;
int width;
int height;
};
END_NAMESPACE_IBI
#endif /* GLMODE2D_H_ */
<file_sep>#ifndef IBIQGLWIDGET_H
#define IBIQGLWIDGET_H
#include "ibi_internal.h"
#include "ibi_gl/ibi_gl.h"
#include <boost/function.hpp>
#include "ibiQGLViewer.h"
namespace ibi { // BEGIN_NAMESPACE_IBI
typedef boost::function<void(ibiQGLViewer* widget)> DrawFunctor;
typedef boost::function<void(ibiQGLViewer* widget)> InitializeFunctor;
typedef boost::function<void(ibiQGLViewer* widget, int w, int h)> ResizeFunctor;
//struct Resizer_AutoViewport
//{
// bool keepAspect;
//
// Resizer_AutoViewport(bool a_keepAspect = true)
// {
// keepAspect = a_keepAspect;
// }
//
// void operator()(ibiQGLViewer* widget, int w, int h)
// {
// widget->setViewportAuto(keepAspect);
// }
//};
class ibiQFunctorGLViewer: public ibiQGLViewer
{
Q_OBJECT
public:
ibiQFunctorGLViewer(InitializeFunctor& init, DrawFunctor& a_painter);
~ibiQFunctorGLViewer();
void draw();
void init();
private:
InitializeFunctor& initer;
DrawFunctor& drawer;
};
} // END_NAMESPACE_IBI
#endif // IBIQGLWIDGET_H
<file_sep>/*
* Quaternion.h
*
* Created on: Oct 27, 2009
* Author: <NAME>
*/
#ifndef QUATERNION_H_
#define QUATERNION_H_
#include "ibi_internal.h"
#include "ibi_math/Math.h"
#include <cassert>
BEGIN_NAMESPACE_IBI
class Matrix3;
class Vector3;
class Quaternion
{
public:
inline Quaternion(Real fW = 1.0, Real fX = 0.0, Real fY = 0.0, Real fZ =
0.0)
{
w = fW;
x = fX;
y = fY;
z = fZ;
}
/// Construct a quaternion from a rotation matrix
inline Quaternion(const Matrix3& rot)
{
this->FromRotationMatrix(rot);
}
/// Construct a quaternion from an angle/axis
inline Quaternion(const Radian& rfAngle, const Vector3& rkAxis)
{
this->FromAngleAxis(rfAngle, rkAxis);
}
/// Construct a quaternion from 3 orthonormal local axes
inline Quaternion(const Vector3& xaxis, const Vector3& yaxis,
const Vector3& zaxis)
{
this->FromAxes(xaxis, yaxis, zaxis);
}
/// Construct a quaternion from 3 orthonormal local axes
inline Quaternion(const Vector3* akAxis)
{
this->FromAxes(akAxis);
}
/// Construct a quaternion from 4 manual w/x/y/z values
inline Quaternion(Real* valptr)
{
memcpy(&w, valptr, sizeof(Real) * 4);
}
/// Array accessor operator
inline Real operator [](const size_t i) const
{
assert(i < 4);
return *(&w + i);
}
/// Array accessor operator
inline Real& operator [](const size_t i)
{
assert(i < 4);
return *(&w + i);
}
/// Pointer accessor for direct copying
inline Real* ptr()
{
return &w;
}
/// Pointer accessor for direct copying
inline const Real* ptr() const
{
return &w;
}
void FromRotationMatrix(const Matrix3& kRot);
void ToRotationMatrix(Matrix3& kRot) const;
void FromAngleAxis(const Radian& rfAngle, const Vector3& rkAxis);
void ToAngleAxis(Radian& rfAngle, Vector3& rkAxis) const;
inline void ToAngleAxis(Degree& dAngle, Vector3& rkAxis) const
{
Radian rAngle;
ToAngleAxis(rAngle, rkAxis);
dAngle = rAngle;
}
void FromAxes(const Vector3* akAxis);
void FromAxes(const Vector3& xAxis, const Vector3& yAxis,
const Vector3& zAxis);
void ToAxes(Vector3* akAxis) const;
void ToAxes(Vector3& xAxis, Vector3& yAxis, Vector3& zAxis) const;
/// Get the local x-axis
Vector3 xAxis(void) const;
/// Get the local y-axis
Vector3 yAxis(void) const;
/// Get the local z-axis
Vector3 zAxis(void) const;
inline Quaternion& operator=(const Quaternion& rkQ)
{
w = rkQ.w;
x = rkQ.x;
y = rkQ.y;
z = rkQ.z;
return *this;
}
Quaternion operator+(const Quaternion& rkQ) const;
Quaternion operator-(const Quaternion& rkQ) const;
Quaternion operator*(const Quaternion& rkQ) const;
Quaternion operator*(Real fScalar) const;
friend Quaternion operator*(Real fScalar, const Quaternion& rkQ);
Quaternion operator-() const;
inline bool operator==(const Quaternion& rhs) const
{
return (rhs.x == x) && (rhs.y == y) && (rhs.z == z) && (rhs.w == w);
}
inline bool operator!=(const Quaternion& rhs) const
{
return !operator==(rhs);
}
// functions of a quaternion
Real Dot(const Quaternion& rkQ) const; // dot product
Real Norm() const; // squared-length
/// Normalises this quaternion, and returns the previous length
Real normalise(void);
Quaternion Inverse() const; // apply to non-zero quaternion
Quaternion UnitInverse() const; // apply to unit-length quaternion
Quaternion Exp() const;
Quaternion Log() const;
// rotation of a vector by a quaternion
Vector3 operator*(const Vector3& rkVector) const;
/** Calculate the local roll element of this quaternion.
@param reprojectAxis By default the method returns the 'intuitive' result
that is, if you projected the local Y of the quaternion onto the X and
Y axes, the angle between them is returned. If set to false though, the
result is the actual yaw that will be used to implement the quaternion,
which is the shortest possible path to get to the same orientation and
may involve less axial rotation.
*/
Radian getRoll(bool reprojectAxis = true) const;
/** Calculate the local pitch element of this quaternion
@param reprojectAxis By default the method returns the 'intuitive' result
that is, if you projected the local Z of the quaternion onto the X and
Y axes, the angle between them is returned. If set to true though, the
result is the actual yaw that will be used to implement the quaternion,
which is the shortest possible path to get to the same orientation and
may involve less axial rotation.
*/
Radian getPitch(bool reprojectAxis = true) const;
/** Calculate the local yaw element of this quaternion
@param reprojectAxis By default the method returns the 'intuitive' result
that is, if you projected the local Z of the quaternion onto the X and
Z axes, the angle between them is returned. If set to true though, the
result is the actual yaw that will be used to implement the quaternion,
which is the shortest possible path to get to the same orientation and
may involve less axial rotation.
*/
Radian getYaw(bool reprojectAxis = true) const;
/// Equality with tolerance (tolerance is max angle difference)
bool equals(const Quaternion& rhs, const Radian& tolerance) const;
// spherical linear interpolation
static Quaternion Slerp(Real fT, const Quaternion& rkP,
const Quaternion& rkQ, bool shortestPath = false);
static Quaternion SlerpExtraSpins(Real fT, const Quaternion& rkP,
const Quaternion& rkQ, int iExtraSpins);
// setup for spherical quadratic interpolation
static void Intermediate(const Quaternion& rkQ0, const Quaternion& rkQ1,
const Quaternion& rkQ2, Quaternion& rka, Quaternion& rkB);
// spherical quadratic interpolation
static Quaternion Squad(Real fT, const Quaternion& rkP,
const Quaternion& rkA, const Quaternion& rkB,
const Quaternion& rkQ, bool shortestPath = false);
// normalised linear interpolation - faster but less accurate (non-constant rotation velocity)
static Quaternion nlerp(Real fT, const Quaternion& rkP,
const Quaternion& rkQ, bool shortestPath = false);
// cutoff for sine near zero
static const Real ms_fEpsilon;
// special values
static const Quaternion ZERO;
static const Quaternion IDENTITY;
Real w, x, y, z;
};
END_NAMESPACE_IBI
#endif /* QUATERNION_H_ */
<file_sep>/*
* CommandLineParser.cpp
*
* Created on: Oct 8, 2009
* Author: <NAME>
*/
#include "CommandLineParser.h"
#include <boost/algorithm/string.hpp>
#include <iostream>
BEGIN_NAMESPACE_IBI
using namespace std;
using namespace boost;
CommandLineParser::CommandLineParser()
{
config = new po::options_description("Allowed options");
}
CommandLineParser::~CommandLineParser()
{
}
void CommandLineParser::addOption(const char* name,
const po::value_semantic* s, const char* description, bool required)
{
config->add_options()(name, s, description);
if (required)
{
saveRequired(name);
}
}
void CommandLineParser::printUsage()
{
cout << *config << "\n";
}
bool CommandLineParser::parse(int argc, char* argv[])
{
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, *config), vm);
} catch (po::unknown_option ex)
{
cout << ex.what() << "\n\n";
printUsage();
return false;
}
vector<string>::iterator it = requiredOptions.begin();
vector<string>::iterator itEnd = requiredOptions.end();
for (; it != itEnd; ++it)
{
if (!vm.count(*it))
{
cout << "Missing required option: --" << *it << "\n\n";
printUsage();
return false;
}
}
po::notify(vm);
return true;
}
void CommandLineParser::saveRequired(const char* name)
{
vector<string> tokens;
split(tokens, name, is_any_of(","));
requiredOptions.push_back(tokens[0]);
}
END_NAMESPACE_IBI
<file_sep>
# Look for headers in ibi source dir
INCLUDE_DIRECTORIES(
"${CMAKE_CURRENT_SOURCE_DIR}/ibi"
)
# Build library
ADD_SUBDIRECTORY (ibi)
# Add our library to list of libraries
SET (LIBS ${LIBS} ibi)
# Build plugins
#ADD_SUBDIRECTORY (plugins)
# Build executables
ADD_SUBDIRECTORY (bin)<file_sep>#include "ibiQGLViewer.h"
#include "ibi_error/Exception.h"
#include "ibi_gl/TextureLoader.h"
BEGIN_NAMESPACE_IBI
ibiQGLViewer::ibiQGLViewer(QWidget *parent, const QGLWidget *shareWidget,
Qt::WFlags flags) :
QGLViewer(parent, shareWidget, flags), desiredAspectRatio(0.0)
{
}
ibiQGLViewer::ibiQGLViewer(QGLContext *context, QWidget *parent,
const QGLWidget *shareWidget, Qt::WFlags flags) :
QGLViewer(context, parent, shareWidget, flags), desiredAspectRatio(0.0)
{
}
ibiQGLViewer::ibiQGLViewer(const QGLFormat &format, QWidget *parent,
const QGLWidget *shareWidget, Qt::WFlags flags) :
QGLViewer(format, parent, shareWidget, flags), desiredAspectRatio(0.0)
{
}
ibiQGLViewer::~ibiQGLViewer()
{
}
void ibiQGLViewer::start2DMode()
{
mode2d.enable();
}
void ibiQGLViewer::stop2DMode()
{
mode2d.disable();
}
void ibiQGLViewer::drawFullScreenQuad()
{
mode2d.drawFullScreenQuad();
}
Vector3 ibiQGLViewer::normalizedViewportCoordinates(int x, int y)
{
int vPort[4];
glGetIntegerv(GL_VIEWPORT, vPort);
Vector3 result;
result.x = Real(x - vPort[0]) / Real(vPort[2]);
result.y = 1.0 - (Real(y - vPort[1]) / Real(vPort[3]));
result.z = 0;
return result;
}
Vector3 ibiQGLViewer::absoluteViewportCoordinates(Vector3& point)
{
int vPort[4];
glGetIntegerv(GL_VIEWPORT, vPort);
Vector3 result;
result.x = (point.x * vPort[2]);
result.y = (point.y * vPort[3]);
result.z = 0;
return result;
}
void ibiQGLViewer::resizeGL(int width, int height)
{
QGLWidget::resizeGL(width, height);
// int side = qMin(width, height);
// glViewport((width - side) / 2, (height - side) / 2, side, side);
if (desiredAspectRatio > 0.0)
{
if (width > (desiredAspectRatio * height))
{
float actual_width = height * desiredAspectRatio;
glViewport((width - actual_width) / 2.0, 0.0, actual_width, height);
camera()->setScreenWidthAndHeight(actual_width, height);
mode2d.setScreenDimensions(actual_width, height);
}
else
{
float actual_height = width / desiredAspectRatio;
glViewport(0.0, (height - actual_height) / 2.0, width,
actual_height);
camera()->setScreenWidthAndHeight(width, actual_height);
mode2d.setScreenDimensions(width, actual_height);
}
}
else
{
glViewport(0, 0, GLint(width), GLint(height));
camera()->setScreenWidthAndHeight(width, height);
mode2d.setScreenDimensions(width, height);
}
}
void ibiQGLViewer::setDesiredAspectRatio(float ratio)
{
this->desiredAspectRatio = ratio;
}
void ibiQGLViewer::saveViewport()
{
glGetIntegerv(GL_VIEWPORT, savedViewport);
}
void ibiQGLViewer::restoreViewport()
{
glViewport(savedViewport[0], savedViewport[1], savedViewport[2],
savedViewport[3]);
}
Texture* ibiQGLViewer::loadTexture(TextureLoadingInfo& info)
{
makeCurrent();
return TextureLoader::load(info);
}
END_NAMESPACE_IBI
<file_sep>/*
* VertexProgram.h
*
* Created on: Nov 4, 2009
* Author: juanmarcus
*/
#ifndef VERTEXPROGRAM_H_
#define VERTEXPROGRAM_H_
#include "ibi_internal.h"
#include <Cg/cg.h>
#include "GPUProgram.h"
BEGIN_NAMESPACE_IBI
class VertexProgram: public GPUProgram
{
public:
VertexProgram(GPUProgramManager* parent);
~VertexProgram();
};
END_NAMESPACE_IBI
#endif /* VERTEXPROGRAM_H_ */
<file_sep>/*
* ibi.h
*
* Created on: Nov 2, 2009
* Author: juanmarcus
*/
#ifndef IBI_INTERNAL_H_
#define IBI_INTERNAL_H_
#include "ibi_common/common.h"
BEGIN_NAMESPACE_IBI
END_NAMESPACE_IBI
#endif /* IBI_INTERNAL_H_ */
<file_sep>/*
* ibi.h
*
* Created on: Nov 2, 2009
* Author: juanmarcus
*/
#ifndef IBI_H_
#define IBI_H_
#include "ibi_common/common.h"
BEGIN_NAMESPACE_IBI
class CommandLineParser;
class Exception;
END_NAMESPACE_IBI
#endif /* IBI_H_ */
<file_sep>/*
* test_texture.cpp
*
* Created on: Oct 15, 2009
* Author: <NAME>
*/
#include "ibi_gl/ibi_gl.h"
#include <QtGui/QApplication>
#include <iostream>
#include "ibi_qt/ibiQFunctorGLViewer.h"
#include "ibi_gl/TextureLoader.h"
#include "ibi_gl/Texture.h"
#include "ibi_qt/TextureConfigurator_Qt.h"
using namespace std;
using namespace ibi;
Texture* t = 0;
struct draw
{
void operator()(ibiQGLViewer* widget)
{
glColor3d(1.0, 1.0, 1.0);
t->enable();
widget->start2DMode();
widget->drawFullScreenQuad();
widget->stop2DMode();
}
};
struct init
{
void operator()(ibiQGLViewer* widget)
{
TextureLoadingInfo info = TextureConfigurator_Qt::fromFilename(
"data/image.png");
t = TextureLoader::load(info);
widget->setDesiredAspectRatio(1.0);
}
};
InitializeFunctor initer = init();
DrawFunctor drawer = draw();
int main(int argc, char **argv)
{
QApplication app(argc, argv);
ibiQFunctorGLViewer w(initer, drawer);
w.showMaximized();
return app.exec();
}
<file_sep>/*
* Texture.h
*
* Created on: Oct 15, 2009
* Author: <NAME>
*/
#ifndef TEXTURE_H_
#define TEXTURE_H_
#include "ibi_internal.h"
#include "ibi_gl.h"
#include <boost/any.hpp>
#include <map>
BEGIN_NAMESPACE_IBI
class Texture
{
friend class TextureLoader;
public:
Texture();
~Texture();
void setGLName(GLuint name);
void setTarget(GLenum target);
void setDimensions(int w, int h = 0, int d = 0);
void setDimension(int dim);
GLuint getGLName();
GLenum getTarget();
int getDimension();
int getWidth();
int getHeight();
int getDepth();
void init();
void enable();
void disable();
private:
/*
* Generated OpenGL name.
*/
GLuint glname;
/*
* Target texture enum.
*
* Defaults to GL_TEXTURE_2D.
*/
GLenum target;
/*
* Texture dimension.
*/
int dimension;
/*
* Texture width in pixels.
*/
int width;
/*
* Texture height in pixels.
*/
int height;
/*
* Texture depth in pixels.
*
* Used only for 3D textures.
*/
int depth;
};
END_NAMESPACE_IBI
#endif /* TEXTURE_H_ */
<file_sep>/*
* Exception.h
*
* Created on: Oct 9, 2009
* Author: <NAME>
*/
#ifndef EXCEPTION_H_
#define EXCEPTION_H_
#include "ibi_internal.h"
#include <exception>
BEGIN_NAMESPACE_IBI
class Exception: public std::exception
{
public:
Exception(String file, String general, String detail = "");
~Exception() throw ();
virtual const char* what() const throw ()
{
String message = file + ": " + general + "\n" + detail;
return message.c_str();
}
private:
String file;
String general;
String detail;
};
END_NAMESPACE_IBI
#endif /* EXCEPTION_H_ */
<file_sep>/*
* texture_loader_qt.cpp
*
* Created on: Nov 2, 2009
* Author: juanmarcus
*/
#include "ibi_internal.h"
#include "ibi_texturemanager/TextureManager.h"
#include "ibi_gl/Texture.h"
#include "ibi_error/Exception.h"
#include <boost/any.hpp>
#include <QtGui/QImage>
#include <QtOpenGL/QGLWidget>
using BEGIN_NAMESPACE_IBI;
class TextureLoader_qt: public TextureLoader
{
void load(TextureLoadingInfo& info, Texture* texture)
{
String filename = boost::any_cast<String>(info.options["filename"]);
QImage t;
QImage b;
if (!b.load(filename.c_str()))
{
throw Exception("texture_loader_qt.cpp",
"Problem loading texture.", "File not found: " + filename);
}
t = QGLWidget::convertToGLFormat(b);
GLuint name = texture->getGLName();
glTexImage2D(info.target, 0, GL_RGBA, t.width(), t.height(), 0,
GL_RGBA, GL_UNSIGNED_BYTE, t.bits());
texture->setDimensions(t.width(), t.height());
}
};
class TextureLoaderFactory_qt: public TextureLoaderFactory
{
TextureLoader* create()
{
TextureLoader* loader = new TextureLoader_qt();
return loader;
}
};
extern "C"
{
void registerPlugin(TextureManager& manager)
{
TextureLoaderFactory_qt* loaderF = new TextureLoaderFactory_qt();
manager.registerTextureLoader(String("qt"), loaderF);
}
}
<file_sep>/*
* Math.h
*
* Created on: Oct 26, 2009
* Author: <NAME>
*/
#ifndef MATH_H_
#define MATH_H_
#include "ibi_internal.h"
#include <cmath>
#include <cassert>
#include <limits>
#include <algorithm>
BEGIN_NAMESPACE_IBI
class Degree;
class Radian;
class Radian
{
Real mRad;
public:
explicit Radian(Real r = 0) :
mRad(r)
{
}
Radian(const Degree& d);
Radian& operator =(const Real& f)
{
mRad = f;
return *this;
}
Radian& operator =(const Radian& r)
{
mRad = r.mRad;
return *this;
}
Radian& operator =(const Degree& d);
Real valueDegrees() const; // see bottom of this file
Real valueRadians() const
{
return mRad;
}
Real valueAngleUnits() const;
const Radian& operator +() const
{
return *this;
}
Radian operator +(const Radian& r) const
{
return Radian(mRad + r.mRad);
}
Radian operator +(const Degree& d) const;
Radian& operator +=(const Radian& r)
{
mRad += r.mRad;
return *this;
}
Radian& operator +=(const Degree& d);
Radian operator -() const
{
return Radian(-mRad);
}
Radian operator -(const Radian& r) const
{
return Radian(mRad - r.mRad);
}
Radian operator -(const Degree& d) const;
Radian& operator -=(const Radian& r)
{
mRad -= r.mRad;
return *this;
}
Radian& operator -=(const Degree& d);
Radian operator *(Real f) const
{
return Radian(mRad * f);
}
Radian operator *(const Radian& f) const
{
return Radian(mRad * f.mRad);
}
Radian& operator *=(Real f)
{
mRad *= f;
return *this;
}
Radian operator /(Real f) const
{
return Radian(mRad / f);
}
Radian& operator /=(Real f)
{
mRad /= f;
return *this;
}
bool operator <(const Radian& r) const
{
return mRad < r.mRad;
}
bool operator <=(const Radian& r) const
{
return mRad <= r.mRad;
}
bool operator ==(const Radian& r) const
{
return mRad == r.mRad;
}
bool operator !=(const Radian& r) const
{
return mRad != r.mRad;
}
bool operator >=(const Radian& r) const
{
return mRad >= r.mRad;
}
bool operator >(const Radian& r) const
{
return mRad > r.mRad;
}
};
class Degree
{
Real mDeg; // if you get an error here - make sure to define/typedef 'Real' first
public:
explicit Degree(Real d = 0) :
mDeg(d)
{
}
Degree(const Radian& r) :
mDeg(r.valueDegrees())
{
}
Degree& operator =(const Real& f)
{
mDeg = f;
return *this;
}
Degree& operator =(const Degree& d)
{
mDeg = d.mDeg;
return *this;
}
Degree& operator =(const Radian& r)
{
mDeg = r.valueDegrees();
return *this;
}
Real valueDegrees() const
{
return mDeg;
}
Real valueRadians() const; // see bottom of this file
Real valueAngleUnits() const;
const Degree& operator +() const
{
return *this;
}
Degree operator +(const Degree& d) const
{
return Degree(mDeg + d.mDeg);
}
Degree operator +(const Radian& r) const
{
return Degree(mDeg + r.valueDegrees());
}
Degree& operator +=(const Degree& d)
{
mDeg += d.mDeg;
return *this;
}
Degree& operator +=(const Radian& r)
{
mDeg += r.valueDegrees();
return *this;
}
Degree operator -() const
{
return Degree(-mDeg);
}
Degree operator -(const Degree& d) const
{
return Degree(mDeg - d.mDeg);
}
Degree operator -(const Radian& r) const
{
return Degree(mDeg - r.valueDegrees());
}
Degree& operator -=(const Degree& d)
{
mDeg -= d.mDeg;
return *this;
}
Degree& operator -=(const Radian& r)
{
mDeg -= r.valueDegrees();
return *this;
}
Degree operator *(Real f) const
{
return Degree(mDeg * f);
}
Degree operator *(const Degree& f) const
{
return Degree(mDeg * f.mDeg);
}
Degree& operator *=(Real f)
{
mDeg *= f;
return *this;
}
Degree operator /(Real f) const
{
return Degree(mDeg / f);
}
Degree& operator /=(Real f)
{
mDeg /= f;
return *this;
}
bool operator <(const Degree& d) const
{
return mDeg < d.mDeg;
}
bool operator <=(const Degree& d) const
{
return mDeg <= d.mDeg;
}
bool operator ==(const Degree& d) const
{
return mDeg == d.mDeg;
}
bool operator !=(const Degree& d) const
{
return mDeg != d.mDeg;
}
bool operator >=(const Degree& d) const
{
return mDeg >= d.mDeg;
}
bool operator >(const Degree& d) const
{
return mDeg > d.mDeg;
}
};
//class Angle
//{
// Real mAngle;
//public:
// explicit Angle(Real angle) :
// mAngle(angle)
// {
// }
// operator Radian() const;
// operator Degree() const;
//};
// these functions could not be defined within the class definition of class
// Radian because they required class Degree to be defined
inline Radian::Radian(const Degree& d) :
mRad(d.valueRadians())
{
}
inline Radian& Radian::operator =(const Degree& d)
{
mRad = d.valueRadians();
return *this;
}
inline Radian Radian::operator +(const Degree& d) const
{
return Radian(mRad + d.valueRadians());
}
inline Radian& Radian::operator +=(const Degree& d)
{
mRad += d.valueRadians();
return *this;
}
inline Radian Radian::operator -(const Degree& d) const
{
return Radian(mRad - d.valueRadians());
}
inline Radian& Radian::operator -=(const Degree& d)
{
mRad -= d.valueRadians();
return *this;
}
class Math
{
public:
static inline int IAbs(int iValue)
{
return (iValue >= 0 ? iValue : -iValue);
}
static inline int ICeil(float fValue)
{
return int(ceil(fValue));
}
static inline int IFloor(float fValue)
{
return int(floor(fValue));
}
static int ISign(int iValue);
static inline Real Abs(Real fValue)
{
return Real(fabs(fValue));
}
static inline Degree Abs(const Degree& dValue)
{
return Degree(fabs(dValue.valueDegrees()));
}
static inline Radian Abs(const Radian& rValue)
{
return Radian(fabs(rValue.valueRadians()));
}
static Radian ACos(Real fValue);
static Radian ASin(Real fValue);
static inline Radian ATan(Real fValue)
{
return Radian(atan(fValue));
}
static inline Radian ATan2(Real fY, Real fX)
{
return Radian(atan2(fY, fX));
}
static inline Real Ceil(Real fValue)
{
return Real(ceil(fValue));
}
static inline Real Cos(const Radian& fValue, bool useTables = false)
{
return Real(cos(fValue.valueRadians()));
}
static inline Real Cos(Real fValue, bool useTables = false)
{
return Real(cos(fValue));
}
static inline Real Exp(Real fValue)
{
return Real(exp(fValue));
}
static inline Real Floor(Real fValue)
{
return Real(floor(fValue));
}
static inline Real Log(Real fValue)
{
return Real(log(fValue));
}
static inline Real Pow(Real fBase, Real fExponent)
{
return Real(pow(fBase, fExponent));
}
static Real Sign(Real fValue);
static inline Radian Sign(const Radian& rValue)
{
return Radian(Sign(rValue.valueRadians()));
}
static inline Degree Sign(const Degree& dValue)
{
return Degree(Sign(dValue.valueDegrees()));
}
static inline Real Sin(const Radian& fValue, bool useTables = false)
{
return Real(sin(fValue.valueRadians()));
}
static inline Real Sin(Real fValue, bool useTables = false)
{
return Real(sin(fValue));
}
static inline Real Sqr(Real fValue)
{
return fValue * fValue;
}
static inline Real Sqrt(Real fValue)
{
return Real(sqrt(fValue));
}
static inline Radian Sqrt(const Radian& fValue)
{
return Radian(sqrt(fValue.valueRadians()));
}
static inline Degree Sqrt(const Degree& fValue)
{
return Degree(sqrt(fValue.valueDegrees()));
}
/** Inverse square root i.e. 1 / Sqrt(x), good for vector
normalisation.
*/
static Real InvSqrt(Real fValue);
static Real UnitRandom(); // in [0,1]
static Real RangeRandom(Real fLow, Real fHigh); // in [fLow,fHigh]
static Real SymmetricRandom(); // in [-1,1]
static inline Real Tan(const Radian& fValue, bool useTables = false)
{
return Real(tan(fValue.valueRadians()));
}
static inline Real Tan(Real fValue, bool useTables = false)
{
return Real(tan(fValue));
}
static inline Real DegreesToRadians(Real degrees)
{
return degrees * fDeg2Rad;
}
static inline Real RadiansToDegrees(Real radians)
{
return radians * fRad2Deg;
}
/** Compare 2 reals, using tolerance for inaccuracies.
*/
static bool RealEqual(Real a, Real b, Real tolerance = std::numeric_limits<
Real>::epsilon());
/** Generates a value based on the Gaussian (normal) distribution function
with the given offset and scale parameters.
*/
static Real gaussianDistribution(Real x, Real offset = 0.0f, Real scale =
1.0f);
/** Clamp a value within an inclusive range. */
template<typename T>
static T Clamp(T val, T minval, T maxval)
{
assert(minval < maxval && "Invalid clamp range");
return std::max(std::min(val, maxval), minval);
}
static const Real POS_INFINITY;
static const Real NEG_INFINITY;
static const Real PI;
static const Real TWO_PI;
static const Real HALF_PI;
static const Real fDeg2Rad;
static const Real fRad2Deg;
};
// these functions must be defined down here, because they rely on the
// angle unit conversion functions in class Math:
inline Real Radian::valueDegrees() const
{
return Math::RadiansToDegrees(mRad);
}
inline Real Degree::valueRadians() const
{
return Math::DegreesToRadians(mDeg);
}
inline Radian operator *(Real a, const Radian& b)
{
return Radian(a * b.valueRadians());
}
inline Radian operator /(Real a, const Radian& b)
{
return Radian(a / b.valueRadians());
}
inline Degree operator *(Real a, const Degree& b)
{
return Degree(a * b.valueDegrees());
}
inline Degree operator /(Real a, const Degree& b)
{
return Degree(a / b.valueDegrees());
}
END_NAMESPACE_IBI
#endif /* MATH_H_ */
<file_sep>/*
* FragmentProgram.h
*
* Created on: Nov 4, 2009
* Author: juanmarcus
*/
#ifndef FRAGMENTPROGRAM_H_
#define FRAGMENTPROGRAM_H_
#include "ibi_internal.h"
#include <Cg/cg.h>
#include "GPUProgram.h"
BEGIN_NAMESPACE_IBI
class FragmentProgram: public GPUProgram
{
public:
FragmentProgram(GPUProgramManager* parent);
~FragmentProgram();
};
END_NAMESPACE_IBI
#endif /* FRAGMENTPROGRAM_H_ */
<file_sep>/*
* GeometryDrawer2D.h
*
* Created on: Nov 11, 2009
* Author: <NAME>
*/
#ifndef GEOMETRYDRAWER2D_H_
#define GEOMETRYDRAWER2D_H_
#include "ibi_internal.h"
#include "ibi_gl.h"
#include "ibi_geometry/Vector3.h"
BEGIN_NAMESPACE_IBI
class GeometryDrawer2D
{
public:
GeometryDrawer2D();
~GeometryDrawer2D();
void drawCircle(Vector3& center, float radius = 10.0, float nbSubdivisions =
60);
};
END_NAMESPACE_IBI
#endif /* GEOMETRYDRAWER2D_H_ */
<file_sep>/*
* FragmentProgram.cpp
*
* Created on: Nov 4, 2009
* Author: juanmarcus
*/
#include "FragmentProgram.h"
BEGIN_NAMESPACE_IBI
FragmentProgram::FragmentProgram(GPUProgramManager* parent) :
GPUProgram(parent)
{
}
FragmentProgram::~FragmentProgram()
{
}
END_NAMESPACE_IBI
<file_sep>/*
* ibi_base.h
*
* Created on: Oct 26, 2009
* Author: <NAME>
*/
#ifndef IBI_BASE_H_
#define IBI_BASE_H_
#include <utility>
#include <string>
#define BEGIN_NAMESPACE_IBI namespace ibi {
#define END_NAMESPACE_IBI }
BEGIN_NAMESPACE_IBI
//-----------------------------------------------------------------------------
// Number
/*
* Type for operating with floating point numbers.
*/
typedef float Real;
/*
* A pair of floating point numbers.
*/
typedef std::pair<Real, Real> RealPair;
//-----------------------------------------------------------------------------
// String
/*
* String type.
*/
typedef std::string String;
END_NAMESPACE_IBI
#endif /* IBI_BASE_H_ */
<file_sep>
# c++ executables
FILE (GLOB cpp_sources "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
FOREACH (cpp_source ${cpp_sources})
get_filename_component (target ${cpp_source} NAME_WE)
add_executable (${target} ${cpp_source})
target_link_libraries (${target} ${LIBS})
ENDFOREACH (cpp_source)<file_sep>/*
* nrrdGLutils.h
*
* Created on: Nov 4, 2009
* Author: juanmarcus
*/
#ifndef NRRDGLUTILS_H_
#define NRRDGLUTILS_H_
GLenum convert_type_to_enum(int type)
{
GLenum result;
switch (type)
{
case nrrdTypeUChar:
result = GL_UNSIGNED_BYTE;
break;
case nrrdTypeChar:
result = GL_BYTE;
break;
case nrrdTypeUShort:
result = GL_UNSIGNED_SHORT;
break;
case nrrdTypeShort:
result = GL_SHORT;
break;
case nrrdTypeFloat:
result = GL_FLOAT;
break;
case nrrdTypeDouble:
result = GL_DOUBLE;
break;
default:
result = GL_UNSIGNED_BYTE;
break;
}
return result;
}
#endif /* NRRDGLUTILS_H_ */
<file_sep>/*
* CommandLineParser.h
*
* Created on: Oct 8, 2009
* Author: <NAME>
*/
#ifndef COMMANDLINEPARSER_H_
#define COMMANDLINEPARSER_H_
#include "ibi_internal.h"
#include <boost/program_options.hpp>
BEGIN_NAMESPACE_IBI
namespace po = boost::program_options;
// Wrapper to avoid the calling program from using namespace boost::program_options
template<class T>
po::typed_value<T>*
value(T* v)
{
po::typed_value<T>* r = new po::typed_value<T>(v);
return r;
}
template<class T>
po::typed_value<T>*
value()
{
return value<T> (0);
}
class CommandLineParser
{
public:
CommandLineParser();
~CommandLineParser();
void addOption(const char* name, const po::value_semantic* s,
const char* description, bool required = false);
bool parse(int argc, char* argv[]);
void printUsage();
protected:
void saveRequired(const char* name);
private:
po::options_description* config;
std::vector<String> requiredOptions;
};
END_NAMESPACE_IBI
#endif /* COMMANDLINEPARSER_H_ */
<file_sep>/*
* GeometryDrawer.cpp
*
* Created on: Oct 26, 2009
* Author: <NAME>
*/
#include "GeometryDrawer.h"
#include "GL.h"
BEGIN_NAMESPACE_IBI
GeometryDrawer::GeometryDrawer()
{
quadric = gluNewQuadric();
}
GeometryDrawer::~GeometryDrawer()
{
}
void GeometryDrawer::drawCylinder(float length, float radius,
int nbSubdivisions)
{
if (radius < 0.0)
radius = 0.05 * length;
gluCylinder(quadric, radius, radius, length, nbSubdivisions, 1);
}
void GeometryDrawer::drawCylinder(Vector3& from, Vector3& to, float radius,
int nbSubdivisions)
{
Vector3 dir = to - from;
// Calculate desired rotation
Quaternion q = Vector3::UNIT_Z.getRotationTo(dir);
glPushMatrix();
// Change transformation
GL::Translate(from);
GL::Rotate(q);
drawCylinder(dir.length(), radius, nbSubdivisions);
glPopMatrix();
}
void GeometryDrawer::drawArrow(float length, float radius, int nbSubdivisions)
{
if (radius < 0.0)
radius = 0.05 * length;
const float head = 2.5 * (radius / length) + 0.1;
const float coneRadiusCoef = 4.0 - 5.0 * head;
gluCylinder(quadric, radius, radius,
length * (1.0 - head / coneRadiusCoef), nbSubdivisions, 1);
glTranslatef(0.0, 0.0, length * (1.0 - head));
gluCylinder(quadric, coneRadiusCoef * radius, 0.0, head * length,
nbSubdivisions, 1);
glTranslatef(0.0, 0.0, -length * (1.0 - head));
}
void GeometryDrawer::drawRay(Ray& ray, float length, float radius,
int nbSubdivisions)
{
// Calculate desired rotation
Quaternion q = Vector3::UNIT_Z.getRotationTo(ray.getDirection());
glPushMatrix();
// Change transformation
GL::Translate(ray.getOrigin());
GL::Rotate(q);
// Draw the arrow
drawArrow(length, radius, nbSubdivisions);
glPopMatrix();
}
void GeometryDrawer::drawPoint(const Vector3& point, float radius,
int nbSubdivisions)
{
assert(radius > 0.0);
glPushMatrix();
glTranslatef(point.x, point.y, point.z);
gluSphere(quadric, radius, nbSubdivisions, nbSubdivisions);
glPopMatrix();
}
void GeometryDrawer::drawPoints(std::vector<Vector3>& points, float radius,
int nbSubdivisions)
{
std::vector<Vector3>::iterator it = points.begin();
std::vector<Vector3>::iterator itEnd = points.end();
for (; it != itEnd; ++it)
{
drawPoint(*it, radius, nbSubdivisions);
}
}
void GeometryDrawer::drawAxisAlignedBox(const AxisAlignedBox& box,
float radius, int nbSubdivisions)
{
/*
1-----2
/| /|
/ | / |
5-----4 |
| 0--|--3
| / | /
|/ |/
6-----7
*/
// Get box corners
Vector3 corner[8];
corner[0] = box.getCorner(AxisAlignedBox::FAR_LEFT_BOTTOM);
corner[1] = box.getCorner(AxisAlignedBox::FAR_LEFT_TOP);
corner[2] = box.getCorner(AxisAlignedBox::FAR_RIGHT_TOP);
corner[3] = box.getCorner(AxisAlignedBox::FAR_RIGHT_BOTTOM);
corner[4] = box.getCorner(AxisAlignedBox::NEAR_RIGHT_TOP);
corner[5] = box.getCorner(AxisAlignedBox::NEAR_LEFT_TOP);
corner[6] = box.getCorner(AxisAlignedBox::NEAR_LEFT_BOTTOM);
corner[7] = box.getCorner(AxisAlignedBox::NEAR_RIGHT_BOTTOM);
// Draw corners
for (int i = 0; i < 8; ++i)
{
drawPoint(corner[i], radius, nbSubdivisions);
}
drawCylinder(corner[0], corner[1], radius / 2);
drawCylinder(corner[0], corner[3], radius / 2);
drawCylinder(corner[0], corner[6], radius / 2);
drawCylinder(corner[1], corner[2], radius / 2);
drawCylinder(corner[1], corner[5], radius / 2);
drawCylinder(corner[2], corner[3], radius / 2);
drawCylinder(corner[2], corner[4], radius / 2);
drawCylinder(corner[3], corner[7], radius / 2);
drawCylinder(corner[4], corner[5], radius / 2);
drawCylinder(corner[4], corner[7], radius / 2);
drawCylinder(corner[5], corner[6], radius / 2);
drawCylinder(corner[6], corner[7], radius / 2);
}
void GeometryDrawer::drawTriangle(const Triangle& t, float radius,
int nbSubdivisions)
{
Vector3 v0 = t.getVertex(0);
Vector3 v1 = t.getVertex(1);
Vector3 v2 = t.getVertex(2);
glPushMatrix();
drawPoint(v0, radius, nbSubdivisions);
drawPoint(v1, radius, nbSubdivisions);
drawPoint(v2, radius, nbSubdivisions);
glPopMatrix();
}
END_NAMESPACE_IBI
| 3f60bac4fb5b8495452acc7f96ecfbc2209a1bc2 | [
"C",
"CMake",
"C++"
] | 79 | C++ | juanmarcus/ibi | 73fc30b4587b0f0b805b948157032e7c21d9bd3b | e5e5dba81d7f36fcd65d6503a1dc0b43376573aa |
refs/heads/master | <repo_name>Divyakorat/practice1<file_sep>/target/Destination/report.js
$(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("src/test/resources/features/Category.feature");
formatter.feature({
"line": 1,
"name": "Category Scenario",
"description": "",
"id": "category-scenario",
"keyword": "Feature"
});
formatter.scenarioOutline({
"line": 3,
"name": "User should able to navigate to correct category page,",
"description": "so that he can user all product features from categories",
"id": "category-scenario;user-should-able-to-navigate-to-correct-category-page,",
"type": "scenario_outline",
"keyword": "Scenario Outline",
"tags": [
{
"line": 2,
"name": "@Category"
}
]
});
formatter.step({
"line": 5,
"name": "user is on homepage",
"keyword": "Given "
});
formatter.step({
"line": 6,
"name": "user click on \"\u003ccategory\u003e\" link on top menu",
"keyword": "When "
});
formatter.step({
"line": 7,
"name": "user should be navigate to category \"\u003crelated Category page\u003e\" successfully",
"keyword": "Then "
});
formatter.examples({
"line": 8,
"name": "",
"description": "",
"id": "category-scenario;user-should-able-to-navigate-to-correct-category-page,;",
"rows": [
{
"cells": [
"category",
"related Category page"
],
"line": 9,
"id": "category-scenario;user-should-able-to-navigate-to-correct-category-page,;;1"
},
{
"comments": [
{
"line": 10,
"value": "# | Desktops | http://tutorialsninja.com/demo/index.php?route\u003dproduct/category\u0026path\u003d20 |"
},
{
"line": 11,
"value": "# | Laptops And Notebooks | http://tutorialsninja.com/demo/index.php?route\u003dproduct/category\u0026path\u003d18 |"
},
{
"line": 12,
"value": "# | Components | http://tutorialsninja.com/demo/index.php?route\u003dproduct/category\u0026path\u003d25 |"
}
],
"cells": [
"Tablets",
"http://tutorialsninja.com/demo/index.php?route\u003dproduct/category\u0026path\u003d57"
],
"line": 13,
"id": "category-scenario;user-should-able-to-navigate-to-correct-category-page,;;2"
}
],
"keyword": "Examples"
});
formatter.before({
"duration": 150645602352,
"status": "passed"
});
formatter.scenario({
"comments": [
{
"line": 10,
"value": "# | Desktops | http://tutorialsninja.com/demo/index.php?route\u003dproduct/category\u0026path\u003d20 |"
},
{
"line": 11,
"value": "# | Laptops And Notebooks | http://tutorialsninja.com/demo/index.php?route\u003dproduct/category\u0026path\u003d18 |"
},
{
"line": 12,
"value": "# | Components | http://tutorialsninja.com/demo/index.php?route\u003dproduct/category\u0026path\u003d25 |"
}
],
"line": 13,
"name": "User should able to navigate to correct category page,",
"description": "so that he can user all product features from categories",
"id": "category-scenario;user-should-able-to-navigate-to-correct-category-page,;;2",
"type": "scenario",
"keyword": "Scenario Outline",
"tags": [
{
"line": 2,
"name": "@Category"
}
]
});
formatter.step({
"line": 5,
"name": "user is on homepage",
"keyword": "Given "
});
formatter.step({
"line": 6,
"name": "user click on \"Tablets\" link on top menu",
"matchedColumns": [
0
],
"keyword": "When "
});
formatter.step({
"line": 7,
"name": "user should be navigate to category \"http://tutorialsninja.com/demo/index.php?route\u003dproduct/category\u0026path\u003d57\" successfully",
"matchedColumns": [
1
],
"keyword": "Then "
});
formatter.match({
"location": "MyStepdef.user_is_on_homepage()"
});
formatter.result({
"duration": 2899471791,
"status": "passed"
});
formatter.match({
"arguments": [
{
"val": "Tablets",
"offset": 15
}
],
"location": "MyStepdef.user_click_on_link_on_top_menu(String)"
});
formatter.result({
"duration": 4950603618,
"status": "passed"
});
formatter.match({
"arguments": [
{
"val": "http://tutorialsninja.com/demo/index.php?route\u003dproduct/category\u0026path\u003d57",
"offset": 37
}
],
"location": "MyStepdef.user_should_be_navigate_to_category_successfully(String)"
});
formatter.result({
"duration": 465970925,
"status": "passed"
});
formatter.after({
"duration": 4604847025,
"status": "passed"
});
});<file_sep>/src/main/java/org/example/HomePage.java
package org.example;
import org.openqa.selenium.By;
import org.testng.asserts.SoftAssert;
public class HomePage extends Util {
private String expectedHomePage="http://tutorialsninja.com/demo/";
//private By _PhoneAndPDS=By.xpath("//a[text()="Phones & PDAs"]");
private By _PhoneAndPDS=By.linkText("Phones & PDAs");
SoftAssert softAssert = new SoftAssert();
private String ExpectedUrlHomePage="http://tutorialsninja.com/demo/";
private By _PhoneAndPDAs=By.xpath("//a[text()=\"Phones & PDAs\"]");
public void VerifyuserisonHomePage(){
// String ActualUrlHomePage = driver.getCurrentUrl();
//softAssert.assertEquals((ActualUrlHomePage),ExpectedUrlHomePage, "expected with actual");
// softAssert.assertAll();
}
public void userClickOnCategoryLink(String categoryLink){
clickOnElement(By.linkText(categoryLink));
}
public void clickOnPhoneAndPDAS(){
clickOnElement(_PhoneAndPDS);
}
}
<file_sep>/src/main/java/org/example/Util.java
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable;
public class Util extends BasePage {
public static void waituntilElementIsclickable(By by, int time) {
WebDriverWait wait = new WebDriverWait(driver, time);
wait.until(elementToBeClickable(by));
}
//reusable method to click on elements
public static void clickOnElement(By by) {
driver.findElement(by).click();
}
//reusable method to type text elements
public static void typeText(By by, String text) {
driver.findElement(by).sendKeys(text);
}
//reusable method to get text from elements
public static String getTextFromElement(By by) {
return driver.findElement(by).getText();
}
//Time stamp
public static long timestamp() {
return (System.currentTimeMillis());
}
//reusable method for select from dropdown by visible text
public static void selectFromDropDownByVisibleText(By by, String text) {
Select select = new Select(driver.findElement(by));
select.selectByVisibleText(text);
}
public static String getUrl() {
return driver.getCurrentUrl();
}
} | c81720e25d70c044b10996df73eabde58d4577b1 | [
"JavaScript",
"Java"
] | 3 | JavaScript | Divyakorat/practice1 | 2ba9f57f34817603681ff81ce6dc713655394ec5 | 1207f086779aa34100d163254fda67488a8c1d1e |
refs/heads/master | <file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Dump all replication events from a remote mysql server
#
import datetime
import pika
import json
import os.path
import os
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import (
DeleteRowsEvent,
UpdateRowsEvent,
WriteRowsEvent
)
class DateEncoder(json.JSONEncoder):
"""
自定义类,解决报错:
TypeError: Object of type 'datetime' is not JSON serializable
"""
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, datetime.date):
return obj.strftime("%Y-%m-%d")
else:
return json.JSONEncoder.default(self, obj)
# 数据库连接配置
MYSQL_SETTINGS = {
"host": os.getenv('ENV_BINLOG_HOST'),
"port": int(os.getenv('ENV_BINLOG_PORT')),
"user": os.getenv('ENV_BINLOG_USER'),
"passwd": <PASSWORD>('<PASSWORD>')
}
def main():
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=os.getenv('ENV_MQ_HOST'),
port=int(os.getenv('ENV_MQ_PORT')),
credentials=pika.PlainCredentials(
os.getenv('ENV_MQ_USER'),
os.getenv('ENV_MQ_PASSWD')
),
virtual_host='/'
)
)
channel = connection.channel()
channel.queue_declare(queue='default_queue', durable=True)
file_name = "file_pos.log"
log_file = ''
log_pos = 0
if os.path.isfile(file_name):
fo = open(file_name, "r")
file_pos = fo.read()
fo.close()
if file_pos != '':
fp_list = file_pos.split('|')
log_file = fp_list[0]
log_pos = int(fp_list[1])
# server_id is your slave identifier, it should be unique.
# set blocking to True if you want to block and wait for the next event at
# the end of the stream
stream = BinLogStreamReader(connection_settings=MYSQL_SETTINGS,
server_id=3,
blocking=True,
resume_stream=True,
log_file=log_file,
log_pos=log_pos,
only_events=[DeleteRowsEvent, WriteRowsEvent, UpdateRowsEvent],
only_tables=['system_message'])
for binlogevent in stream:
# binlogevent.dump() # 打印所有信息
for row in binlogevent.rows:
# 打印 库名 和 表名
event = {"schema": binlogevent.schema,
"table": binlogevent.table,
# "log_pos": stream.log_pos,
# "log_file": stream.log_file
}
if isinstance(binlogevent, DeleteRowsEvent):
event["action"] = "delete"
event["data"] = row["values"]
elif isinstance(binlogevent, UpdateRowsEvent):
event["action"] = "update"
event["data"] = row["after_values"] # 注意这里不是values
elif isinstance(binlogevent, WriteRowsEvent):
event["action"] = "insert"
event["data"] = row["values"]
print(json.dumps(event, cls=DateEncoder))
message = {
'class': '\\MZ\\Models\\user\\UserModel',
'method': 'getUserById',
'data': event
}
body = json.dumps(message, cls=DateEncoder)
channel.basic_publish(exchange='default_ex', routing_key='default_route', body=body)
fo = open(file_name, "w")
fo.write(stream.log_file + '|' + str(stream.log_pos))
fo.close()
# sys.stdout.flush()
# stream.close() # 如果使用阻塞模式,这行多余了
if __name__ == "__main__":
main()
<file_sep>#!/usr/bin/env python
import pika
import json
credentials = pika.PlainCredentials("admin", "<PASSWORD>")
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host='qeue.rs.youfa365.com',
port=5672,
credentials=credentials,
virtual_host='/'
)
)
channel = connection.channel()
channel.queue_declare(queue='default_queue', durable=True)
message = {
'class': "\\MZ\Models\\user\\UserModel",
'method': 'getUserById',
'data': 1000
}
body = json.dumps(message)
channel.basic_publish(exchange='default_ex', routing_key='default_route', body=body)
print(" [x] Sent body: "+body)
connection.close()
| 6cdfeb648db62576d4d2017e3b078f14b1e9766b | [
"Python"
] | 2 | Python | mydevc/python-mysql-replication | bd0417ac6a3b406183e9f9404856aef4683b441b | 874f8bd475e7cc5140e5337e23ab95258bcb5554 |
refs/heads/master | <repo_name>danilo4web/ionic<file_sep>/restaurantes/src/pages/carrinho/carrinho.ts
import { Component } from '@angular/core';
import { NavController, NavParams, AlertController } from 'ionic-angular';
import { Http } from '@angular/http';
import { DetalheDoPedidoPage } from '../detalhe-do-pedido/detalhe-do-pedido';
import { CardapiosPage } from '../cardapios/cardapios';
import { LoginPage } from '../login/login';
import { PedidosPage } from '../pedidos/pedidos';
import { Pedido } from '../../domain/pedido/pedido';
import { Cardapio } from '../../domain/cardapio/cardapio';
import { Usuario } from '../../domain/usuario/usuario';
@Component({
selector: 'page-carrinho',
templateUrl: 'carrinho.html'
})
export class CarrinhoPage {
public data;
public http;
public url: string;
public pedido: Pedido;
public cardapio: Cardapio;
constructor(public navCtrl: NavController, public _alertCtrl: AlertController, http: Http, public navParams: NavParams) {
this.pedido = new Pedido(null,null,null,null,null,null,null,null);
this.pedido.usuario = new Usuario(sessionStorage.getItem('usuarioId'), sessionStorage.getItem('usuarioNome'), sessionStorage.getItem('usuarioLogado'), null, sessionStorage.getItem('flagLogado'));
this.pedido.cardapio = this.navParams.get('CardapioSelecionado');
console.log("Carrinho - constructor");
console.log(this.pedido);
console.log(this.pedido.cardapio);
console.log(this.pedido.usuario);
console.log("=====================");
console.log("=====================");
this.data = {};
this.data.response = '';
this.http = http;
this.url = 'http://pedidos.localhost/index.php/page/cadastrar_pedido_ionic';
}
ngOnInit() {
if(sessionStorage.getItem('flagLogado') != 'sim') {
this.goToLogin();
}
}
submit() {
var data = JSON.stringify({
cardapio_id: this.pedido.cardapio.id,
usuario_id: this.pedido.usuario.id,
valor: this.pedido.cardapio.preco,
taxaEntrega: "10.00",
nome: this.pedido.usuario.nome,
email: this.pedido.usuario.email,
observacao: this.pedido.observacao
});
console.log(data);
this.http.post(this.url, data)
.subscribe(data => {
this.data.response = data._body;
this._alertCtrl
.create({
title: 'Sucesso',
buttons: [{ text: 'OK' }],
subTitle: this.data.response
}).present();
this.goToPedidos();
}, error => {
console.log("Oooops!");
this._alertCtrl
.create({
title: 'Falha na conexão',
buttons: [{ text: 'Estou ciente!' }],
subTitle: 'Não foi possível obter a lista de restaurantes. Tente novamente.'
}).present();
});
}
goToLogin() {
this.navCtrl.setRoot(LoginPage);
}
goToPedidos() {
this.navCtrl.setRoot(PedidosPage);
}
}
<file_sep>/restaurantes/src/pages/detalhe-do-pedido/detalhe-do-pedido.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { CardapiosPage } from '../cardapios/cardapios';
import { CarrinhoPage } from '../carrinho/carrinho';
@Component({
selector: 'page-detalhe-do-pedido',
templateUrl: 'detalhe-do-pedido.html'
})
export class DetalheDoPedidoPage {
constructor(public navCtrl: NavController) {
}
goToCardapio(params){
if (!params) params = {};
this.navCtrl.push(CardapiosPage);
}goToCarrinho(params){
if (!params) params = {};
this.navCtrl.push(CarrinhoPage);
}goToDetalheDoPedido(params){
if (!params) params = {};
this.navCtrl.push(DetalheDoPedidoPage);
}
}
<file_sep>/pedidos/docs/arquivos_necessarios/idsgeo5_curso_udemy.sql
-- phpMyAdmin SQL Dump
-- version 4.6.6
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Tempo de geração: 19/10/2017 às 12:01
-- Versão do servidor: 5.6.35-log
-- Versão do PHP: 5.6.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Banco de dados: `idsgeo5_curso_udemy`
--
-- --------------------------------------------------------
--
-- Estrutura para tabela `cardapio`
--
CREATE TABLE `cardapio` (
`id` int(11) NOT NULL,
`restaurante_id` int(11) NOT NULL,
`nome` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`tipo` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`ingredientes` tinytext COLLATE utf8_unicode_ci,
`observacao` text COLLATE utf8_unicode_ci,
`preco` decimal(10,2) NOT NULL,
`img_url` varchar(300) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Estrutura para tabela `cardapios_pedido`
--
CREATE TABLE `cardapios_pedido` (
`pedido_id` int(11) NOT NULL,
`cardapio_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Fazendo dump de dados para tabela `cardapios_pedido`
--
INSERT INTO `cardapios_pedido` (`pedido_id`, `cardapio_id`) VALUES
(42, 1),
(42, 2);
-- --------------------------------------------------------
--
-- Estrutura para tabela `ci_sessions`
--
CREATE TABLE `ci_sessions` (
`id` varchar(40) DEFAULT NULL,
`ip_address` varchar(45) DEFAULT NULL,
`timestamp` int(10) UNSIGNED DEFAULT '0',
`data` blob,
`session_id` varchar(40) DEFAULT NULL,
`user_agent` text,
`last_activity` text,
`user_data` text
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Fazendo dump de dados para tabela `ci_sessions`
--
INSERT INTO `ci_sessions` (`id`, `ip_address`, `timestamp`, `data`, `session_id`, `user_agent`, `last_activity`, `user_data`) VALUES
(NULL, '192.168.3.11', 0, NULL, '482172204130a29146b5badd7dfdbb6b', 'python-requests/2.9.1', '1489555056', 'a:2:{s:9:\"user_data\";s:0:\"\";s:4:\"lang\";s:2:\"en\";}'),
(NULL, '192.168.3.11', 0, NULL, '554b4055f6b742d45020de78a2f2a25b', 'python-requests/2.9.1', '1489727868', 'a:2:{s:9:\"user_data\";s:0:\"\";s:4:\"lang\";s:2:\"en\";}');
-- --------------------------------------------------------
--
-- Estrutura para tabela `empresa`
--
CREATE TABLE `empresa` (
`id` int(11) NOT NULL,
`nome_fantasia` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`razao_social` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`CNPJ` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`inscricao_estadual` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`CPF` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`telefone` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`celular` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`password` text COLLATE utf8_unicode_ci NOT NULL,
`email` tinytext COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Fazendo dump de dados para tabela `empresa`
--
INSERT INTO `empresa` (`id`, `nome_fantasia`, `razao_social`, `CNPJ`, `inscricao_estadual`, `CPF`, `telefone`, `celular`, `password`, `email`) VALUES
(1, '<NAME>', NULL, NULL, NULL, '0000', ' (31) 3634 - 6735', '(31) 99384-8241', '', ''),
(2, 'DESK Coworking', '1', '1', '1', '', '(31) 3236-1400', '', '', ''),
(74, 'Novo Sabor Tele-marmitex', 'Novo Sabor Tele-marmitex', 'Novo Sabor Tele-marmitex', 'Novo Sabor Tele-marmitex', 'Novo Sabor Tele-marm', '(31) 3413-8430', '3130779039', 'marmita12345', 'Novo Sabor Tele-marmitex'),
(73, 'Novo Sabor Tele-marmitex', 'Novo Sabor Tele-marmitex', 'Novo Sabor Tele-marmitex', 'Novo Sabor Tele-marmitex', 'Novo Sabor Tele-marm', '(31) 3413-8430', '3130779039', 'marmita12345', 'Novo Sabor Tele-marmitex'),
(72, 'Tele Marmitex Miura', 'Tele Marmitex Miura', 'Tele Marmitex Miura', 'Tele Marmitex Miura', 'Tele Marmitex Miura', '(31) 3077-9039', '', 'marmita12345', 'Tele Marmitex Miura'),
(68, 'Novo Teste restaurante', 'Novo Teste restaurante', 'Novo Teste restaurante', 'Novo Teste restaurante', 'Novo Teste restauran', '43423', '434', 'marmita12345', 'Novo Teste restaurante'),
(79, 'P<NAME> E TELEMARMITEX', 'P<NAME> LANCHES E TELEMARMITEX', 'P<NAME> LANCHES E TELEMARMITEX', 'PONTO CERTO LANCHES E TELEMARMITEX', '<NAME> ', '3130779039', '3130779039', 'marmita12345', 'PONTO CERTO LANCHES E TELEMARMITEX'),
(78, 'Telemarmitex da Lu', 'Telemarmitex da Lu', 'Telemarmitex da Lu', 'Telemarmitex da Lu', 'Telemarmitex da Lu', '(31) 3283-5247', '', 'marmita12345', 'Telemarmitex da Lu'),
(77, 'Rio Manso Tele-Marmitex', 'Rio Manso Tele-Marmitex', 'Rio Manso Tele-Marmitex', 'Rio Manso Tele-Marmitex', 'Rio Manso Tele-Marmi', '(31) 3287-8529', '3130779039', 'marmita12345', 'Rio Manso Tele-Marmitex'),
(76, 'Novosabor Tele Marmitex', 'Novosabor Tele Marmitex', 'Novosabor Tele Marmitex', 'Novosabor Tele Marmitex', 'Novosabor Tele Marmi', '(31)3568-8808', '(31)98720-7821', 'marmita12345', 'Novosabor Tele Marmitex'),
(75, 'Tele Marmitex', 'Tele Marmitex', 'Tele Marmitex', 'Tele Marmitex', 'Tele Marmitex', '(31) 3072-7769', '', 'marmita12345', 'Tele Marmitex'),
(67, 'Restaurante teste', 'Restaurante teste', 'Restaurante teste', 'Restaurante teste', 'Restaurante teste', '33333', '33333', 'marmita12345', 'Restaurante teste'),
(66, 'Restaurante teste', 'Restaurante teste', 'Restaurante teste', 'Restaurante teste', 'Restaurante teste', '33333', '33333', 'marmita12345', 'Restaurante teste'),
(65, 'Teste Apagar', 'Teste Apagar', 'Teste Apagar', 'Teste Apagar', 'Teste Apagar', '333333', '3333333', 'marmita12345', 'Teste Apagar'),
(63, 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', '(31) 3498-2094', '', 'marmita12345', 'Tele Marmitex Tia Rô'),
(64, 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', '(31) 3498-2094', '', 'marmita12345', 'Tele Marmitex Tia Rô'),
(71, 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', 'Tele Marmitex Tia Rô', '(31) 3498-2094', '', 'marmita12345', 'Tele Marmitex Tia Rô'),
(70, 'Tele Marmitex', 'Tele Marmitex', 'Tele Marmitex', 'Tele Marmitex', 'Tele Marmitex', '(31) 3418-6222', '', 'marmita12345', 'Tele Marmitex'),
(69, 'Naturalíssima', 'Naturalíssima', 'Naturalíssima', 'Naturalíssima', 'Naturalíssima', '(31) 3474-0054', '', 'marmita12345', 'Naturalíssima'),
(57, 'Candeia Restsurante\'s', '', '', '', '<EMAIL>', '3134942256', '', 'aqswdefr', ''),
(55, 'Bar e Restaurante Temperinho da Eva', NULL, NULL, NULL, '1111', '(31) 3457-1400', '', 'q1w2e3r4', ''),
(80, 'Tele Marmitex Sabor e Cia', 'Tele Marmitex Sabor e Cia', 'Tele Marmitex Sabor e Cia', 'Tele Marmitex Sabor e Cia', 'Tele Marmitex Sabor ', '(31) 3437-8895', '3130779039', 'marmita12345', 'Tele Marmitex Sabor e Cia'),
(81, 'Restaurante Sabores Tele Marmitex', 'Restaurante Sabores Tele Marmitex', 'Restaurante Sabores Tele Marmitex', 'Restaurante Sabores Tele Marmitex', 'Restaurante Sabores ', '(31) 2565-2945', '', 'marmita12345', 'Restaurante Sabores Tele Marmitex'),
(82, 'Sagrado Sabor - Tele Marmitex', 'Sagrado Sabor - Tele Marmitex', 'Sagrado Sabor - Tele Marmitex', 'Sagrado Sabor - Tele Marmitex', 'Sagrado Sabor - Tele', '(31) 3468-0449', '', 'marmita12345', 'Sagrado Sabor - Tele Marmitex'),
(83, 'Tele-Marmitex Sabor de Verdade', 'Tele-Marmitex Sabor de Verdade', 'Tele-Marmitex Sabor de Verdade', 'Tele-Marmitex Sabor de Verdade', 'Tele-Marmitex Sabor ', '', '', 'marmita12345', 'Tele-Marmitex Sabor de Verdade'),
(85, 'Dona Alice Refeições', 'Dona Alice Refeições', 'Dona Alice Refeições', 'Dona Alice Refeições', 'Dona Alice Refeições', '03134590146', '031988606042', 'marmita12345', 'Dona Alice Refeições');
-- --------------------------------------------------------
--
-- Estrutura para tabela `endereco`
--
CREATE TABLE `endereco` (
`id` int(11) NOT NULL,
`restaurante_id` int(11) NOT NULL,
`endereco` text COLLATE utf8_unicode_ci NOT NULL,
`numero` varchar(400) COLLATE utf8_unicode_ci NOT NULL,
`complemento` varchar(400) COLLATE utf8_unicode_ci DEFAULT NULL,
`cidade` text COLLATE utf8_unicode_ci NOT NULL,
`estado` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`bairro` text COLLATE utf8_unicode_ci NOT NULL,
`cep` varchar(255) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Fazendo dump de dados para tabela `endereco`
--
INSERT INTO `endereco` (`id`, `restaurante_id`, `endereco`, `numero`, `complemento`, `cidade`, `estado`, `bairro`, `cep`) VALUES
(1, 1, 'Av. Brasília', '1313', 'Lj 04 - Sob Loja', 'Santa Luzia', 'MG', 'São Benedito', ''),
(2, 2, '<NAME>', '125', '', 'Belo Horizonte', 'MG', 'Salgado Filho', ''),
(3, 69, '<NAME>', '351', '', 'Belo Horizonte', 'MG', 'Ouro preto', ''),
(4, 71, 'Teste 333', '445', '555', 'BH', 'MG', 'Santa Lucia', '3333'),
(5, 72, 'Rua 1 bairro 2', '333', '102', 'Belo Horizonte', 'MG', 'Centro', '30360240'),
(6, 73, 'Rua 1 bairro 2', '333', '102', 'Belo Horizonte', 'MG', 'Centro', '30360240'),
(7, 74, '432423', '43242', '432432', 'Belo Horizonte', 'MG', 'Santa Lúcia', '432432'),
(8, 75, 'Av. Abí<NAME>', '1669', '', '<NAME>', 'Minas Gerais', 'Glória', '30830-373'),
(9, 76, '<NAME>', ' 168', '', '<NAME>', 'Minas Gerais', 'Ouro Preto', ''),
(10, 77, '<NAME>', '351', '', '<NAME>', 'Minas Gerais', 'Ouro Preto', '31330-500'),
(11, 78, '<NAME>', '200', '', '<NAME>', 'Minas Gerais', 'Glória', '30880-140'),
(12, 79, 'R. Expedicion<NAME> da Costa', '211', '', '<NAME>', 'Minas Gerais', 'Caiçaras', '30770-300'),
(13, 80, 'R. Expedicionário Hereny da Costa', '211', '', '<NAME>', 'Minas Gerais', 'Caiçaras', '30770-300'),
(14, 81, '<NAME>', '901', '', '<NAME>', 'Minas Gerais', 'Palmares', '31160-290'),
(15, 82, '<NAME>', '56', '', '<NAME>', 'Minas Gerais', '<NAME>', '30820-330'),
(16, 83, '<NAME>', '172', '', '<NAME>', 'Minas Gerais', 'Santa Efigênia', '30240-350'),
(17, 84, '', '', '', '<NAME>', 'Minas Gerais', 'Paraíso', ''),
(18, 85, 'Tv. C-5', '70', '', 'Contagem', 'Minas Gerais', 'Eldorado', '32310-280'),
(19, 86, '<NAME>', '15', '', 'Belo Horizonte', 'Minas Gerais', 'Providência', '31814-130'),
(20, 87, 'Av. <NAME>', '2940', '', 'Contagem', 'Minas Gerais', 'Eldorado', '32310-210'),
(21, 88, '<NAME>', '465', '', 'Belo Horizonte', 'Minas Gerais', 'Sagrada Família', '31030-220'),
(22, 89, '<NAME>', '174', '', 'Belo Horizonte', 'Minas Gerais', 'Santa Monica', '31530-130'),
(23, 90, '<NAME>', '128', '', 'Ribeirão das Neves', 'MG', '<NAME>', '33930-310'),
(24, 91, '<NAME>', '128', '', 'Ribeirão das Neves', 'MG', '<NAME>', '33930310');
-- --------------------------------------------------------
--
-- Estrutura para tabela `login_attempts`
--
CREATE TABLE `login_attempts` (
`id` int(11) NOT NULL,
`ip_address` varchar(40) COLLATE utf8_bin NOT NULL,
`attempts` int(11) NOT NULL,
`login` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`lastLogin` int(11) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Fazendo dump de dados para tabela `login_attempts`
--
INSERT INTO `login_attempts` (`id`, `ip_address`, `attempts`, `login`, `lastLogin`, `time`) VALUES
(11, '172.16.17.32', 2, NULL, 1409855680, '2014-09-05 01:34:40'),
(12, '172.16.58.3', 2, NULL, 1415985711, '2014-11-15 00:21:51'),
(13, '192.168.127.12', 1, NULL, 1424023348, '2015-02-16 01:02:28'),
(14, '172.16.31.10', 1, NULL, 1436908481, '2015-07-15 04:14:41'),
(19, '172.16.17.32', 2, NULL, 1455135889, '2016-02-11 01:24:49'),
(18, '172.16.58.3', 4, NULL, 1447632160, '2015-11-16 05:02:40'),
(20, '172.16.31.10', 2, NULL, 1460122215, '2016-04-08 17:30:15'),
(21, '172.16.58.3', 1, NULL, 1464550526, '2016-05-29 23:35:26'),
(22, '192.168.127.12', 1, NULL, 1466076456, '2016-06-16 15:27:36'),
(23, '172.16.58.3', 2, NULL, 1466366638, '2016-06-20 00:03:58'),
(24, '172.16.17.32', 1, NULL, 1468445253, '2016-07-14 01:27:33'),
(25, '192.168.3.11', 5, NULL, 1471435694, '2016-08-17 16:08:14'),
(26, '192.168.3.11', 1, NULL, 1471899426, '2016-08-23 00:57:06');
-- --------------------------------------------------------
--
-- Estrutura para tabela `pedidos`
--
CREATE TABLE `pedidos` (
`id` int(11) NOT NULL,
`cardapio_id` int(11) NOT NULL,
`usurarios_id` int(11) NOT NULL,
`valor` decimal(10,2) NOT NULL,
`taxa_entrega` decimal(10,2) NOT NULL,
`nome` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`observacao` tinytext COLLATE utf8_unicode_ci
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Fazendo dump de dados para tabela `pedidos`
--
INSERT INTO `pedidos` (`id`, `cardapio_id`, `usurarios_id`, `valor`, `taxa_entrega`, `nome`, `email`, `observacao`) VALUES
(1, 0, 0, '0.00', '0.00', '<NAME>', '<EMAIL>', NULL),
(2, 1, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(3, 1, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(4, 1, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(5, 1, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(6, 3, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(7, 1, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(8, 1, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(9, 1, 104, '15.00', '10.00', 'Bruno', '<EMAIL>', NULL),
(10, 3, 105, '15.00', '10.00', 'Bruno', '<EMAIL>', NULL),
(11, 1, 105, '15.00', '10.00', 'Bruno', '<EMAIL>', NULL),
(12, 3, 104, '15.00', '10.00', 'Bruno', '<EMAIL>', NULL),
(13, 1, 119, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(14, 1, 119, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(15, 1, 119, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(16, 1, 119, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(17, 1, 119, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(18, 2, 119, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(19, 1, 119, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(20, 1, 119, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(21, 1, 119, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(22, 2, 119, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(23, 1, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(24, 1, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(25, 1, 1, '15.00', '10.00', 'brunohauck', '<EMAIL>', NULL),
(26, 3, 1, '15.00', '10.00', 'brunohauck', '<EMAIL>', NULL),
(27, 1, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(28, 1, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(29, 1, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(30, 2, 1, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(31, 1, 173, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(32, 1, 173, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(33, 1, 173, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(34, 1, 173, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(35, 1, 173, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(36, 1, 173, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(37, 1, 173, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(38, 1, 173, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(39, 1, 173, '15.00', '10.00', '<NAME>', '<EMAIL>', NULL),
(40, 1, 1, '30.00', '10.50', NULL, '<EMAIL>', NULL),
(41, 1, 1, '15.00', '10.00', 'brunohauck', '<EMAIL>', NULL),
(42, 1, 1, '30.00', '10.50', NULL, '<EMAIL>', NULL),
(43, 1, 218, '15.00', '10.00', 'test', 'test', NULL),
(44, 3, 218, '15.00', '10.00', 'test', 'test', NULL);
-- --------------------------------------------------------
--
-- Estrutura para tabela `prato`
--
CREATE TABLE `prato` (
`id` int(11) NOT NULL,
`restaurante_id` int(11) NOT NULL,
`nome` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`tipo` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`arroz` varchar(300) COLLATE utf8_unicode_ci DEFAULT NULL,
`feijao` varchar(300) COLLATE utf8_unicode_ci DEFAULT NULL,
`ingredientes` tinytext COLLATE utf8_unicode_ci,
`observacao` text COLLATE utf8_unicode_ci,
`img_url` varchar(300) COLLATE utf8_unicode_ci DEFAULT NULL,
`flag_refeicao_montada` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Fazendo dump de dados para tabela `prato`
--
INSERT INTO `prato` (`id`, `restaurante_id`, `nome`, `tipo`, `arroz`, `feijao`, `ingredientes`, `observacao`, `img_url`, `flag_refeicao_montada`) VALUES
(1, 1, 'Prato do dia 01', 'Marmitex', 'Arroz', 'Feijão Tropeiro', 'Fritas', NULL, 'http://costelanobafo.loja2.com.br/img/6398fdbba7d52cea6ccf8ad74fb4b8f7.jpg', 'Nao'),
(2, 1, 'Prato do dia 02', 'Marmitex', 'Arroz Branco', 'Feijão ', ' Batata Palha Temperada', NULL, 'http://costelanobafo.loja2.com.br/img/6398fdbba7d52cea6ccf8ad74fb4b8f7.jpg', 'Nao'),
(3, 1, 'Prato do dia 03', 'Marmitex', 'Arroz', 'Feijão', 'Creme de Batata c/cheiro Verde, Batata Palha, Espaguete ao Molho Napolitano', 'Escolha Carne e Informe no Campo Alteração do Prato', 'http://costelanobafo.loja2.com.br/img/6398fdbba7d52cea6ccf8ad74fb4b8f7.jpg', 'Nao');
-- --------------------------------------------------------
--
-- Estrutura para tabela `restaurante`
--
CREATE TABLE `restaurante` (
`id` int(11) NOT NULL,
`empresa_id` int(11) NOT NULL,
`nome` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`tipo` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`telefone` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`celular` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`img_url` tinytext COLLATE utf8_unicode_ci,
`pedido_url` varchar(400) COLLATE utf8_unicode_ci DEFAULT NULL,
`endereco` tinytext COLLATE utf8_unicode_ci,
`flag_pedido_cadastrado` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
`latitude` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`longitude` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`data_criacao` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Fazendo dump de dados para tabela `restaurante`
--
INSERT INTO `restaurante` (`id`, `empresa_id`, `nome`, `tipo`, `telefone`, `celular`, `img_url`, `pedido_url`, `endereco`, `flag_pedido_cadastrado`, `latitude`, `longitude`, `data_criacao`) VALUES
(1, 1, 'Escondidim', 'Restaurante e entregas', '(31) 3634 - 6735', '(31) 99384-8241', 'http://dev.escondidim.com.br/images/escondidim_app.png', NULL, 'Av. Brasília, 1313 Lj 04 - Sob Loja\r\nSão Benedito - Santa Luzia', 'Nao', '-19.7925697', '-43.9346231', '2016-07-24 13:43:19'),
(2, 2, 'Marmitex Online BH', 'Tele Marmitex', '(31) 3459-8862', '', 'http://assets.lwsite.com.br/uploads/widget_image/image/307/967/307967/logo_1759846566.png', NULL, 'R. Consuelo, 3 - Jardim dos Comerciários,Belo Horizonte - MG,31650-100', 'Nao', '-19.7922574 ', '-43.9737068', '2016-07-24 13:43:19'),
(61, 3, 'Temperinho da Eva', 'Marmitex', '(31) 3457-1400 / 2520-2509', '', 'http://www.poenoprato.com.br/system/restaurants/photos/000/000/003/thumb/logomarca_temperinho.jpg', 'http://www.poenoprato.com.br/temperinho-da-eva/pedido_online', 'R<NAME>, 440 Loja\r\n31510-420\r\nBelo Horizonte / Minas Gerais ', 'url', '-19.8168257', '-43.9675658', '2016-07-24 13:43:19'),
(62, 0, 'Restaurante Requinte', 'Telemarmitex', '(31) 3637-2020', '(31) 99540-7498', NULL, 'http://www.poenoprato.com.br/restaurante-requinte/pedido_online', 'Rua <NAME>, 31 Cristina A - 2º ANDAR\r\n33105-250', 'url', '-19.7834209', '-43.9258064', '2016-07-24 13:43:19'),
(65, 57, 'Candeia Restsurante\'s', 'Tele Marmitex', '3134942256', '333', NULL, NULL, 'Rua Osório Duque Estrada 156 Planalto', 'Nao', '-19.8332699', '-43.9481284', '2016-07-24 13:43:19'),
(69, 63, 'Tele Marmitex Tia Rô', 'Telemarmitex', '(31) 3498-2094', '', NULL, NULL, NULL, 'Nao', '', '', '2016-09-11 19:24:47'),
(75, 69, 'Naturalíssima', 'Telemarmitex', '(31) 3474-0054', '', NULL, NULL, 'Av. <NAME>', 'Nao', '', '', '2016-10-24 19:36:51'),
(76, 70, 'Tele Marmitex', 'Telemarmitex', '(31) 3418-6222', '', NULL, NULL, '<NAME> e Oito', 'Nao', '', '', '2016-11-29 21:06:21'),
(78, 72, 'Tele <NAME>', 'Telemarmitex', '(31) 3077-9039', '', NULL, NULL, 'R. Iliada', NULL, '', '', '2016-12-01 16:41:02'),
(79, 73, 'Novo Sabor Tele-marmitex', 'Telemarmitex', '(31) 3413-8430', '3130779039', NULL, NULL, 'R. <NAME>', 'Nao', '', '', '2016-12-01 16:42:41'),
(92, 86, '', 'Telemarmitex', '82764652325', '<EMAIL>', NULL, NULL, '<NAME>agra 100mg 4st <a href=http://byuvaigranonile.com>viagra</a> Stendra Without Perscription Internet Overseas ', NULL, '', '', '2017-05-05 18:28:03'),
(91, 85, '<NAME>', 'Telemarmitex', '03134590146', '031988606042', NULL, NULL, 'R. <NAME>', 'Nao', '', '', '2017-01-31 18:41:54'),
(83, 77, '<NAME> Tele-Marmitex', 'Telemarmitex', '(31) 3287-8529', '3130779039', NULL, NULL, 'R. <NAME>', 'Nao', '', '', '2016-12-01 16:47:33'),
(84, 78, 'Telemarmitex da Lu', 'Telemarmitex', '(31) 3283-5247', '', NULL, NULL, '', 'Nao', '', '', '2016-12-01 16:51:26'),
(85, 79, '<NAME>', 'Telemarmitex', '3130779039', '3130779039', NULL, NULL, 'Tv. C-5', 'Nao', '', '', '2016-12-01 16:52:33'),
(86, 80, 'Tele Marmitex Sabor e Cia', 'Telemarmitex', '(31) 3437-8895', '3130779039', NULL, NULL, 'R. Fronteira', 'Nao', '', '', '2016-12-01 16:53:34'),
(87, 81, 'Restaurante Sabores Tele Marmitex', 'Telemarmitex', '(31) 2565-2945', '', NULL, NULL, 'Av. <NAME>', 'Nao', '', '', '2016-12-01 16:54:43'),
(88, 82, 'Sagrado Sabor - Tele Marmitex', 'Telemarmitex', '(31) 3468-0449', '', NULL, NULL, 'R. <NAME>', 'Nao', '', '', '2016-12-01 17:07:11'),
(89, 83, 'Tele-Marmitex Sabor de Verdade', 'Telemarmitex', '', '', NULL, NULL, 'Rua Dos Xetas', 'Nao', '', '', '2016-12-01 17:08:20'),
(93, 87, '', 'Telemarmitex', '89243148336', '<EMAIL>', NULL, NULL, 'Perfect Rx Meds Buy Viagra Usa <a href=http://viacheap.com>viagra online pharmacy</a> Amoxicillin Order From Canada Le Cialis Blog <a href=http://cial40mg.com/buy-cheap-cialis-pills.php>Buy Cheap Cialis Pills</a> Amoxil 500 Mg Viagra Marocaine <a href=', NULL, '', '', '2017-06-21 17:05:34');
-- --------------------------------------------------------
--
-- Estrutura para tabela `restaurante_foto`
--
CREATE TABLE `restaurante_foto` (
`id` int(11) NOT NULL,
`restaurante_id` int(11) NOT NULL,
`nome` varchar(200) NOT NULL,
`img_url` tinytext NOT NULL,
`flag_capa` varchar(3) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Fazendo dump de dados para tabela `restaurante_foto`
--
INSERT INTO `restaurante_foto` (`id`, `restaurante_id`, `nome`, `img_url`, `flag_capa`) VALUES
(1, 1, 'Logo', 'http://dev.escondidim.com.br/images/escondidim_app.png', 'Sim'),
(2, 2, 'teste444', 'http://assets.lwsite.com.br/uploads/widget_image/image/307/967/307967/logo_1759846566.png', 'Sim'),
(6, 62, 'Requinte', 'http://dev.escondidim.com.br/images/requinte.png', 'Sim'),
(5, 61, 'eva', 'http://www.poenoprato.com.br/system/restaurants/photos/000/000/003/thumb/logomarca_temperinho.jpg', 'Sim'),
(7, 65, 'logo', 'http://dev.escondidim.com.br/imagens/candeia_restaurante.png', 'Sim'),
(8, 69, 'Marmitex', 'http://dev.escondidim.com.br/images/marmitex.png', 'Sim'),
(9, 74, '6c119c5dbae3e37a5a150f88d63a101c.jpg', 'http://dev.escondidim.com.br/images/6c119c5dbae3e37a5a150f88d63a101c.jpg', NULL),
(10, 75, '1a6c57c8e305770a23b0a900c6b53793.jpg', 'http://dev.escondidim.com.br/images/1a6c57c8e305770a23b0a900c6b53793.jpg', NULL),
(28, 90, '761b76982a83aab5b3ab9b86d8fa3b7a.png', 'http://dev.escondidim.com.br/images/761b76982a83aab5b3ab9b86d8fa3b7a.png', NULL),
(12, 76, '9aff7a4a43aad86661e8d99a2d7f7988.jpg', 'http://dev.escondidim.com.br/images/9aff7a4a43aad86661e8d99a2d7f7988.jpg', NULL),
(29, 91, 'cdb840b51de2be09d73e7004a59db98d.png', 'http://dev.escondidim.com.br/images/cdb840b51de2be09d73e7004a59db98d.png', NULL),
(14, 77, 'd145059775d9c7d05e89b13efa6fa7a6.jpg', 'http://dev.escondidim.com.br/images/d145059775d9c7d05e89b13efa6fa7a6.jpg', NULL),
(15, 78, '589c00c8a9b7eadef5bc382359243562.jpg', 'http://dev.escondidim.com.br/images/589c00c8a9b7eadef5bc382359243562.jpg', NULL),
(16, 79, '0d4d9d7c8c5c5ab82a6bf1aefc52b097.jpg', 'http://dev.escondidim.com.br/images/0d4d9d7c8c5c5ab82a6bf1aefc52b097.jpg', NULL),
(17, 81, '6f29f25503b666dc84ba2712f2ef5900.jpg', 'http://dev.escondidim.com.br/images/6f29f25503b666dc84ba2712f2ef5900.jpg', NULL),
(19, 82, 'b5e5c49efbbdef66ca71d24e2650e1bd.jpg', 'http://dev.escondidim.com.br/images/b5e5c49efbbdef66ca71d24e2650e1bd.jpg', NULL),
(20, 83, '593179c9a80154fd785bd349eaf7ff14.jpg', 'http://dev.escondidim.com.br/images/593179c9a80154fd785bd349eaf7ff14.jpg', NULL),
(21, 84, '2223b2e5c569aaf27ac1057c35416cc4.jpg', 'http://dev.escondidim.com.br/images/2223b2e5c569aaf27ac1057c35416cc4.jpg', NULL),
(22, 85, 'cd01256d927bfa4b9ebaac3101db25d2.jpg', 'http://dev.escondidim.com.br/images/cd01256d927bfa4b9ebaac3101db25d2.jpg', NULL),
(23, 86, '91d8847988879c07743fdf21e68017aa.jpg', 'http://dev.escondidim.com.br/images/91d8847988879c07743fdf21e68017aa.jpg', NULL),
(24, 87, '8045a668fca9ecc10d1364802cc7be9d.jpg', 'http://dev.escondidim.com.br/images/8045a668fca9ecc10d1364802cc7be9d.jpg', NULL),
(26, 88, '9c3e0578aa3099380557d9480820f722.jpg', 'http://dev.escondidim.com.br/images/9c3e0578aa3099380557d9480820f722.jpg', NULL),
(27, 89, '38f2b174d2f18520b500dbe26dac1863.jpg', 'http://dev.escondidim.com.br/images/38f2b174d2f18520b500dbe26dac1863.jpg', NULL);
-- --------------------------------------------------------
--
-- Estrutura para tabela `usuarios_app`
--
CREATE TABLE `usuarios_app` (
`id` int(11) NOT NULL,
`nome` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(64) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Fazendo dump de dados para tabela `usuarios_app`
--
INSERT INTO `usuarios_app` (`id`, `nome`, `email`, `password`, `created_at`, `updated_at`) VALUES
(1, '<NAME>', '<EMAIL>', '123456', '2017-08-22 16:26:12', NULL),
(2, 'asdf ', 'www@fwe', '<PASSWORD>', '2017-09-07 01:21:18', NULL),
(3, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:41:59', NULL),
(4, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:42:07', NULL),
(5, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:43:08', NULL),
(6, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:09', NULL),
(7, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:10', NULL),
(8, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:10', NULL),
(9, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:10', NULL),
(10, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:10', NULL),
(11, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:10', NULL),
(12, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:10', NULL),
(13, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:10', NULL),
(14, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:11', NULL),
(15, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:11', NULL),
(16, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:11', NULL),
(17, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:11', NULL),
(18, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:44:11', NULL),
(19, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:45:39', NULL),
(20, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:46:05', NULL),
(21, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:47:16', NULL),
(22, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:49:54', NULL),
(23, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:50:54', NULL),
(24, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:50:59', NULL),
(25, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:50:59', NULL),
(26, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:50:59', NULL),
(27, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:50:59', NULL),
(28, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:50:59', NULL),
(29, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:50:59', NULL),
(30, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:50:59', NULL),
(31, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:51:00', NULL),
(32, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:51:00', NULL),
(33, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:53:15', NULL),
(34, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:54:10', NULL),
(35, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:56:11', NULL),
(36, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:56:14', NULL),
(37, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:56:15', NULL),
(38, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:56:15', NULL),
(39, 'Udemy', '<EMAIL>', '123456', '2017-09-10 17:56:16', NULL),
(40, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:02:16', NULL),
(41, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:02:32', NULL),
(42, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:02:32', NULL),
(43, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:02:32', NULL),
(44, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:03:52', NULL),
(45, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:03:55', NULL),
(46, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:03:55', NULL),
(47, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:03:55', NULL),
(48, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:03:55', NULL),
(49, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:04:01', NULL),
(50, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:04:03', NULL),
(51, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:04:04', NULL),
(52, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:04:04', NULL),
(53, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:04:04', NULL),
(54, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:04:04', NULL),
(55, 'Escondidim', '<EMAIL>', '123456', '2017-09-11 02:04:04', NULL),
(56, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:40', NULL),
(57, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:51', NULL),
(58, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:54', NULL),
(59, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:54', NULL),
(60, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:54', NULL),
(61, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:54', NULL),
(62, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:54', NULL),
(63, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:54', NULL),
(64, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:55', NULL),
(65, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:55', NULL),
(66, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:55', NULL),
(67, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:55', NULL),
(68, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:55', NULL),
(69, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:56', NULL),
(70, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:56', NULL),
(71, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:56', NULL),
(72, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:56', NULL),
(73, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:56', NULL),
(74, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:56', NULL),
(75, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:57', NULL),
(76, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:57', NULL),
(77, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:57', NULL),
(78, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:57', NULL),
(79, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:57', NULL),
(80, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:57', NULL),
(81, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:10:58', NULL),
(82, 'udemy', '<EMAIL>', 'q1w2e3r4t5', '2017-09-11 02:11:53', NULL),
(83, 'udemy', '<EMAIL>', '123456', '2017-09-11 02:13:05', NULL),
(84, 'udemy', '<EMAIL>', '123456', '2017-09-11 02:13:36', NULL),
(85, 'udemy', '<EMAIL>', '123456', '2017-09-11 02:15:17', NULL),
(86, 'Teste', '<EMAIL>', '123456', '2017-09-11 20:58:03', NULL),
(87, 'Maico', '<EMAIL>', '123456', '2017-09-11 21:28:04', NULL),
(88, 'Maico', '<EMAIL>', '123456', '2017-09-11 21:28:27', NULL),
(89, 'asdf', 'asdf@asdf', 'asdf', '2017-09-12 14:20:39', NULL),
(90, 'asdf', 'asdf@asdf', 'asdf', '2017-09-12 14:20:44', NULL),
(91, 'asdfasdf', '<EMAIL>', 'asdf', '2017-09-12 14:46:07', NULL),
(92, 'asdfasdf', '<EMAIL>', 'asdf', '2017-09-12 14:46:12', NULL),
(93, 'asdf', '<EMAIL>', 'asdf', '2017-09-12 14:47:15', NULL),
(94, 'junioe', '<EMAIL>', '123456', '2017-09-16 17:10:49', NULL),
(95, 'JUNIOR', '<EMAIL>', '123456', '2017-09-18 12:13:47', NULL),
(96, 'JUNIOR', '<EMAIL>', '123456', '2017-09-18 12:55:18', NULL),
(97, 'testebr', '<EMAIL>', 'testebr', '2017-09-20 14:57:50', NULL),
(98, 'testebr', '<EMAIL>', 'testebr', '2017-09-20 14:57:51', NULL),
(99, 'testebr', '<EMAIL>', 'testebr', '2017-09-20 14:57:52', NULL),
(100, 'testebr', '<EMAIL>', 'testebr', '2017-09-20 14:57:52', NULL),
(101, 'testebr', '<EMAIL>', 'testebr', '2017-09-20 14:58:09', NULL),
(102, 'testbr', '<EMAIL>', 'testbr', '2017-09-20 15:00:26', NULL),
(103, 'emails', '<EMAIL>', 'emails', '2017-09-20 15:02:53', NULL),
(104, 'brteste123', '<EMAIL>', 'brteste123', '2017-09-20 15:09:17', NULL),
(105, 'Br', '<EMAIL>', 'br', '2017-09-20 20:59:45', NULL),
(106, 'asd', 'asda', 'sadas', '2017-09-27 17:00:20', NULL),
(107, 'asd', 'asda', 'sadas', '2017-09-27 17:00:25', NULL),
(108, 'aldoprogramador', '<EMAIL>', '36213304', '2017-09-27 18:06:55', NULL),
(109, 'Udemy', '<EMAIL>', 'olamundo', '2017-09-30 00:15:32', NULL),
(110, 'Udemy', '<EMAIL>', '12345', '2017-09-30 00:16:34', NULL),
(111, 'Udemy', '<EMAIL>', '12345', '2017-09-30 00:16:48', NULL),
(112, 'udem', '<EMAIL>', '123456', '2017-09-30 01:02:10', NULL),
(113, 'udem', '<EMAIL>', '123456', '2017-09-30 01:02:33', NULL),
(114, 'LEO', '<EMAIL>', '123456', '2017-09-30 06:47:09', NULL),
(115, 'Matsinhe', '<EMAIL>', '123456', '2017-09-30 12:21:48', NULL),
(116, 'Leonel', '<EMAIL>', '123456', '2017-09-30 12:22:30', NULL),
(117, 'Leonel', '<EMAIL>', '123456', '2017-09-30 12:22:58', NULL),
(118, 'Leonel', '<EMAIL>', '123456', '2017-09-30 12:24:32', NULL),
(119, 'Jadson', '<EMAIL>', '123', '2017-09-30 20:56:44', NULL),
(120, 'Matsinhe', '<EMAIL>', '123456', '2017-10-02 09:22:34', NULL),
(121, 'Matsinhe', '<EMAIL>', '123456', '2017-10-02 09:22:40', NULL),
(122, 'Udemy', '<EMAIL>', 'q1w2e3r4', '2017-10-04 19:01:08', NULL),
(123, 'Udemy', '<EMAIL>', 'q1w2e3r4', '2017-10-04 19:07:18', NULL),
(124, 'Udemy', '<EMAIL>', 'q1w2e3r4', '2017-10-04 19:53:16', NULL),
(125, 'Lucia', '<EMAIL>', '123456', '2017-10-04 19:53:39', NULL),
(126, 'teste', 'teste', 'teste', '2017-10-05 01:32:01', NULL),
(127, 'teste', 'teste', 'teste', '2017-10-05 01:33:09', NULL),
(128, 'jhemerson', 'jhemerson', 'jhemerson', '2017-10-05 01:51:55', NULL),
(129, 'Udemy', '<EMAIL>', '123456', '2017-10-08 22:51:36', NULL),
(130, 'Udemy', '<EMAIL>', '123456', '2017-10-08 22:52:00', NULL),
(131, 'Udemy', '<EMAIL>', '123456', '2017-10-08 22:52:51', NULL),
(132, 'TESTE', '<EMAIL>', 'teste', '2017-10-08 22:55:59', NULL),
(133, 'Teste', '<EMAIL>', '1212', '2017-10-09 19:54:53', NULL),
(134, 'Teste', '<EMAIL>', '1212', '2017-10-09 19:55:22', NULL),
(135, 'Teste', '<EMAIL>', '1212', '2017-10-09 19:55:22', NULL),
(136, 'Teste', '<EMAIL>', '1212', '2017-10-09 19:55:22', NULL),
(137, 'Teste', '<EMAIL>', '1212', '2017-10-09 19:55:22', NULL),
(138, 'Teste', '<EMAIL>', '1212', '2017-10-09 19:55:22', NULL),
(139, 'Teste', '<EMAIL>', '1212', '2017-10-09 19:55:23', NULL),
(140, 'Ramon', '<EMAIL>', '1212', '2017-10-09 20:19:08', NULL),
(141, 'Ramon', '<EMAIL>', '1212', '2017-10-09 20:19:20', NULL),
(142, 'Ramon', '<EMAIL>', '1212', '2017-10-09 20:19:21', NULL),
(143, 'Ramon', '<EMAIL>', '1212', '2017-10-09 20:19:21', NULL),
(144, 'Ramon', '<EMAIL>', '1212', '2017-10-09 20:19:22', NULL),
(145, 'Ramon', '<EMAIL>', '1212', '2017-10-09 20:19:35', NULL),
(146, 'Teste', '<EMAIL>', '1212', '2017-10-09 20:21:24', NULL),
(147, 'Teste', '<EMAIL>', '1212', '2017-10-09 20:21:30', NULL),
(148, 'Ramon', '<EMAIL>', '1212', '2017-10-09 20:23:00', NULL),
(149, 'Teste', '<EMAIL>', '1212', '2017-10-09 20:24:25', NULL),
(150, 'Ramon', '<EMAIL>', '1212', '2017-10-09 20:32:22', NULL),
(151, 'Ramon', '<EMAIL>', '1212', '2017-10-09 20:35:05', NULL),
(152, 'Rita', '<EMAIL>', '1212', '2017-10-09 20:38:00', NULL),
(153, 'Ramon', '<EMAIL>', '1212', '2017-10-09 20:43:56', NULL),
(154, 'wesley', '<EMAIL>', '123456', '2017-10-10 20:07:29', NULL),
(155, 'wesley', '<EMAIL>', '123456', '2017-10-10 20:07:34', NULL),
(156, 'wesley', '<EMAIL>', '123456', '2017-10-10 20:11:33', NULL),
(157, 'wesley', '<EMAIL>', '123456', '2017-10-10 20:11:35', NULL),
(158, 'wesley', '<EMAIL>', '123456', '2017-10-10 21:29:32', NULL),
(159, 'wesley', '<EMAIL>', '123456', '2017-10-10 21:29:34', NULL),
(160, 'wesley', '<EMAIL>', '123456', '2017-10-10 21:30:16', NULL),
(161, 'Wesley', '<EMAIL>', '123456', '2017-10-11 13:39:43', NULL),
(162, 'Wesley', '<EMAIL>', '123456', '2017-10-11 13:39:46', NULL),
(163, 'Matsinhe', '<EMAIL>', 'MarciA2002', '2017-10-14 11:38:42', NULL),
(164, 'Almeida', '<EMAIL>', '123456', '2017-10-14 11:56:58', NULL),
(165, 'Almeida', '<EMAIL>', '123456', '2017-10-14 11:57:17', NULL),
(166, 'ALmeida12', '<EMAIL>', '123456', '2017-10-14 11:58:56', NULL),
(167, 'Habyb', '<EMAIL>', 'q1w2e3r4t5', '2017-10-15 19:35:22', NULL),
(168, 'Habyb', '<EMAIL>', 'q1w2e3r4t5', '2017-10-15 19:35:57', NULL),
(169, 'Habyb', '<EMAIL>', 'q1w2e3r4t5', '2017-10-15 19:35:59', NULL),
(170, 'Habyb', '<EMAIL>', 'q1w2e3r4t5', '2017-10-15 19:52:49', NULL),
(171, 'Habyb', '<EMAIL>', 'q1w2e3r4t5', '2017-10-15 19:53:33', NULL),
(172, 'Habyb', '<EMAIL>', 'q1w2e3r4t5', '2017-10-15 19:54:12', NULL),
(173, 'Habyb', '<EMAIL>', 'q1w2e3r4t5', '2017-10-15 19:54:27', NULL),
(174, 'teste', '<EMAIL>', 'teste', '2017-10-16 17:04:51', NULL),
(175, 'teste', '<EMAIL>', 'teste', '2017-10-16 17:04:55', NULL),
(176, 'teste', '<EMAIL>', 'q1w2e3r4', '2017-10-16 17:05:02', NULL),
(177, 'teste', '<EMAIL>', 'q1w2e3r4', '2017-10-16 17:05:04', NULL),
(178, 'teste', '<EMAIL>', 'q1w2e3r4', '2017-10-16 17:05:05', NULL),
(179, 'teste', '<EMAIL>', 'q1w2e3r4', '2017-10-16 17:05:06', NULL),
(180, 'teste', '<EMAIL>', 'q1w2e3r4', '2017-10-16 17:05:07', NULL),
(181, 'teste', '<EMAIL>', 'q1w2e3r4', '2017-10-16 17:05:08', NULL),
(182, 'teste', '<EMAIL>', 'q1w2e3r4', '2017-10-16 17:05:09', NULL),
(183, 'teste', '<EMAIL>', 'q1w2e3r4', '2017-10-16 17:05:09', NULL),
(184, 'teste', '<EMAIL>', 'q1w2e3r4', '2017-10-16 17:05:09', NULL),
(185, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:50', NULL),
(186, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:51', NULL),
(187, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:53', NULL),
(188, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:53', NULL),
(189, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:53', NULL),
(190, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:54', NULL),
(191, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:54', NULL),
(192, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:54', NULL),
(193, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:54', NULL),
(194, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:54', NULL),
(195, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:55', NULL),
(196, 'teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:05:55', NULL),
(197, 'Teste', '<EMAIL>', 'q1w2e3r4t5', '2017-10-16 17:14:17', NULL),
(198, 'shandryll', '<EMAIL>', 'shandryll', '2017-10-16 17:41:47', NULL),
(199, 'abc', '<EMAIL>', 'abc123', '2017-10-16 17:49:10', NULL),
(200, 'test', 'test', 'test', '2017-10-17 18:31:10', NULL),
(201, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:16', NULL),
(202, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:21', NULL),
(203, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:22', NULL),
(204, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:22', NULL),
(205, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:23', NULL),
(206, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:23', NULL),
(207, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:23', NULL),
(208, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:23', NULL),
(209, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:23', NULL),
(210, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:23', NULL),
(211, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:24', NULL),
(212, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:24', NULL),
(213, 'udemyantonio', '<EMAIL>', 'toni3032', '2017-10-17 18:55:24', NULL),
(214, 'shandryll', 'shandryll', 'shandryll', '2017-10-17 19:22:01', NULL),
(215, 'shandryll', 'shandryll', 'shandryll', '2017-10-17 19:22:06', NULL),
(216, 'antonioudemy', '<EMAIL>', 'toni3032', '2017-10-17 19:33:18', NULL),
(217, 'udemytoni', '<EMAIL>', 'toni3032', '2017-10-17 19:39:23', NULL),
(218, 'test', 'test', 'test', '2017-10-17 19:52:44', NULL),
(219, 'test', '<EMAIL>', 'test', '2017-10-17 19:52:52', NULL),
(220, 'udemyteste3', '<EMAIL>', 'toni3032', '2017-10-18 02:29:29', NULL),
(221, 'udemytestetoni', '<EMAIL>', 'toni3032', '2017-10-18 02:32:59', NULL),
(222, 'fgfg', 'ffff', '', '2017-10-18 23:34:54', NULL),
(223, 'ass', 'ass', 'ssss', '2017-10-19 00:19:18', NULL),
(224, 'escondidim', '<EMAIL>', '123', '2017-10-19 00:26:55', NULL),
(225, 'escondidim', '<EMAIL>', '123', '2017-10-19 00:31:32', NULL);
--
-- Índices de tabelas apagadas
--
--
-- Índices de tabela `cardapio`
--
ALTER TABLE `cardapio`
ADD PRIMARY KEY (`id`);
--
-- Índices de tabela `ci_sessions`
--
ALTER TABLE `ci_sessions`
ADD KEY `ci_sessions_timestamp` (`timestamp`);
--
-- Índices de tabela `empresa`
--
ALTER TABLE `empresa`
ADD PRIMARY KEY (`id`);
--
-- Índices de tabela `endereco`
--
ALTER TABLE `endereco`
ADD PRIMARY KEY (`id`);
--
-- Índices de tabela `login_attempts`
--
ALTER TABLE `login_attempts`
ADD PRIMARY KEY (`id`);
--
-- Índices de tabela `pedidos`
--
ALTER TABLE `pedidos`
ADD PRIMARY KEY (`id`);
--
-- Índices de tabela `prato`
--
ALTER TABLE `prato`
ADD PRIMARY KEY (`id`);
--
-- Índices de tabela `restaurante`
--
ALTER TABLE `restaurante`
ADD PRIMARY KEY (`id`);
--
-- Índices de tabela `restaurante_foto`
--
ALTER TABLE `restaurante_foto`
ADD PRIMARY KEY (`id`);
--
-- Índices de tabela `usuarios_app`
--
ALTER TABLE `usuarios_app`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de tabelas apagadas
--
--
-- AUTO_INCREMENT de tabela `cardapio`
--
ALTER TABLE `cardapio`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de tabela `empresa`
--
ALTER TABLE `empresa`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=86;
--
-- AUTO_INCREMENT de tabela `endereco`
--
ALTER TABLE `endereco`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25;
--
-- AUTO_INCREMENT de tabela `login_attempts`
--
ALTER TABLE `login_attempts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27;
--
-- AUTO_INCREMENT de tabela `pedidos`
--
ALTER TABLE `pedidos`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=45;
--
-- AUTO_INCREMENT de tabela `prato`
--
ALTER TABLE `prato`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT de tabela `restaurante`
--
ALTER TABLE `restaurante`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=94;
--
-- AUTO_INCREMENT de tabela `restaurante_foto`
--
ALTER TABLE `restaurante_foto`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30;
--
-- AUTO_INCREMENT de tabela `usuarios_app`
--
ALTER TABLE `usuarios_app`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=226;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/restaurantes/src/pages/cadastro/cadastro.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '@angular/http';
import { RestaurantesPage } from '../restaurantes/restaurantes';
import { Usuario } from '../../domain/usuario/usuario';
import { Cardapio } from '../../domain/cardapio/cardapio';
@Component({
selector: 'page-cadastro',
templateUrl: 'cadastro.html'
})
export class CadastroPage {
public data;
public http;
public usuario: Usuario;
constructor(public navCtrl: NavController, http: Http ) {
this.data = {};
this.data.response = '';
this.http = http;
this.usuario = new Usuario(null, null, null, null, null);
}
ngOnInit() {
if(sessionStorage.getItem('flagLogado') == 'sim') {
this.goToRestaurante();
}
}
goToRestaurante() {
this.navCtrl.setRoot(RestaurantesPage);
}
submit(){
var link = 'http://pedidos.localhost/index.php/page/cadastrar_usuario_ionic';
var data = JSON.stringify({
nome: this.usuario.nome,
email: this.usuario.email,
password: <PASSWORD>
});
// iniciando a conexao http para cadastro via JSON
this.http.post(link, data)
.subscribe(data => {
this.data.response = data._body;
var res = this.data.response.split("|");
if(res[1] == "sucesso"){
sessionStorage.setItem('usuarioId', res[0]);
sessionStorage.setItem('usuarioLogado', this.usuario.email);
sessionStorage.setItem('usuarioNome', this.usuario.nome);
sessionStorage.setItem('flagLogado', 'sim');
this.navCtrl.push(RestaurantesPage)
} else if(this.data.response == 'invalido') {
console.log('Invalido!!!');
}
}, error => {
console.log('ocorreu algum erro!');
});
}
}<file_sep>/recursos_nativos/src/pages/home/home.ts
import { Component } from '@angular/core';
import { NavController, ActionSheetController, ToastController, Platform, LoadingController, Loading } from 'ionic-angular';
import { File } from '@ionic-native/file';
import { Transfer, TransferObject } from '@ionic-native/transfer';
import { FilePath } from '@ionic-native/file-path';
import { Camera } from '@ionic-native/camera';
declare var cordova: any;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
lastImage: string = null;
loading: Loading;
constructor(
public navCtrl: NavController,
private camera: Camera,
private transfer: Transfer,
private file: File,
private filePath: FilePath,
private actionSheetCtrl: ActionSheetController,
private toastCtrl: ToastController,
private platform: Platform,
private loadingCtrl: LoadingController
) {
}
public presentActionSheet() {
console.log("entrou no present");
let actionSheet = this.actionSheetCtrl.create({
title: 'Selecione uma opção',
buttons: [
{
text: 'Carregar da memória do telefone',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Tirar uma foto',
handler: () => {
this.takePicture(this.camera.PictureSourceType.CAMERA);
}
},
{
text: 'cancel',
role: 'cancel'
}
]
});
actionSheet.present();
}
public takePicture(sourceType) {
// cria as opcoes
var options = {
quality: 100,
sourceType: sourceType,
savetoPhotoAlbum: false,
correctOrientation: true
};
this.camera.getPicture(options).then((imagePath) => {
// Se for Android e for para pegar o arquivo da biblioteca de imagens
if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
this.filePath.resolveNativePath(imagePath)
.then(filePath => {
let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
let correctName = imagePath.substr(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
});
} else {
var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
}
}, (err) => {
this.presentToast('Error while selectiong image.');
});
}
private createFileName() {
var d = new Date();
var n = d.getTime();
var newFileName = n + ".jpg";
return newFileName;
}
private copyFileToLocalDir(namePath, currentName, newFileName) {
this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName)
.then(sucess => {
this.lastImage = newFileName;
},error => {
this.presentToast('Ocorreu algum erro');
});
}
private presentToast(text) {
let toast = this.toastCtrl.create({
message: text,
duration: 3000,
position: 'top'
});
toast.present();
}
private uploadImage() {
}
private pathForImage(img) {
}
} | bbb30033802b7ce6945ebbb93d3c84cae6ff1e49 | [
"SQL",
"TypeScript"
] | 5 | TypeScript | danilo4web/ionic | e08f316b3454ce147b0f7f5422db40acfd59d11f | 84c780809a7b1fa8350f4a02404d99385322351d |
refs/heads/master | <repo_name>SBarreto/Proyecto-Final-Analisis-Numerico<file_sep>/README.md
# Proyecto Final: Calculadora de Integrales
En el siguiente documento se describe el contenido del repositorio
## Documento: Proyecto final analisis numerico
documento que describe los diferentes componentes del proyecto, incluyendo marco teorico, objetivos, desarrollo y muestra de funcionamiento
## Carpeta AnalisisNum2
En esta carpeta se encuentra el codigo de implementacion del proyecto y sus librerias, desarrollado en Java.
## Carpeta MaquinaIntegradora
En esta carpeta se encuentra el codigo de implementacion del proyecto y sus librerias, con varios ajustes y correcciones.
## Maquina_Integradora.zip
Archivo comprimido con ejecutable para correr aplicacion sin necesidad de un IDE, descomprimirlo y leer instrucciones en README.TXT
## Integrantes:
* <NAME>
* <NAME>
* <NAME>
* <NAME>
<file_sep>/AnalisisNum2/src/analisisnum/AnalisisNum.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package analisisnum;
import static analisisnum.GUI_Analisis.distancia;
import java.math.*;
import java.lang.Math;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import java.util.Stack;
/**
*
* @author alejandro
*/
public class AnalisisNum {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
List<Float> listX = new ArrayList<>();
List<Float> listY = new ArrayList<>();
Scanner reader = new Scanner(System.in); // Reading from System.in
float cantidadPuntos = 0;
float a = 0;
float b = 0;
System.out.println("Ingrese el intervalo a para sin(x): ");
a = Integer.parseInt(reader.next());
System.out.println("Ingrese el intervalo b para sin(x): ");
b = Integer.parseInt(reader.next());
System.out.println("Ingrese la cantidad de puntos para sin(x): ");
cantidadPuntos = Integer.parseInt(reader.next()); // Scans the next token of the input as an int.
System.out.println("ingreso a: " + a + ", b: " + b + ", Cantidad de puntos: " + cantidadPuntos );
listX = puntos(a, b,cantidadPuntos);
listY = puntosY(listX);
System.out.println("-------------------------------------------------------------- ");
//System.out.println("Area rectangular: " + areaRectangular(a, b, listX, listY));
System.out.println("-------------------------------------------------------------- ");
System.out.println("Area trapezoidal: " + areaTrapezoidal(a, b, listX, listY));
System.out.println("-------------------------------------------------------------- ");
System.out.println("Area semicircular: " + areaSemicircular(a, b, listX, listY));
reader.close();
}
public static float distancia( float a, float b){
return Math.abs(b - a);
}
public static List<Float> puntos( float a, float b, float cantidadPuntos){
List<Float> listA = new ArrayList<>();
float n = distancia(a ,b);
float n2 = n / cantidadPuntos;
float n3 = n2;
listA.add(a);
for(int i = 0; i < cantidadPuntos; i++){
listA.add(a + n2);
n2 = n3 + n2;
}
return listA;
}
public static List<Float> puntosY(List<Float> x){
List<Float> listY = new ArrayList<>();
for(Float f : x){
//System.out.println("x: y:");
//System.out.println(f + " " + (float)Math.sin(f));
listY.add((float)Math.sin(f));
}
return listY;
}
public static float areaRectangular(float a, float b, List<Float> x, List<Float> y){
int i = 0;
float area = 0;
for(Float f : x){
if(i == 0){
area += y.get(i) * (distancia(a, f));
i++;
}else{
area += y.get(i) * (distancia(x.get(i - 1), f));
//System.out.println( "abs " + y.get(i) * Math.abs(distancia(x.get(i - 1), f)));
i++;
}
}
return area;
}
public static float areaTrapezoidal(float a, float b, List<Float> x, List<Float> y){
int i = 0;
float area = 0;
for(Float f : x){
if(( i + 1) < x.size()){
area += y.get(i) * distancia(x.get(i), x.get(i + 1));
area += ((y.get(i + 1) - y.get(i)) * (distancia(x.get(i), x.get(i + 1)))) / 2;
i++;
}
}
System.out.println("error de truncamiento: "+ errorTruncamientoTrap( a, b, x, y));
return area;
}
public static float areaSemicircular(float a, float b, List<Float> x, List<Float> y){
int i = 0;
float area = 0;
float pi = (float)3.1415926;
int signo = 1;
for(Float f : x){
if(i == 0){
area += y.get(i) * distancia(a, f);
if(y.get(i) >= 0)
signo = 1;
else signo = -1;
area += signo * (pi * Math.pow(distancia(a, f), 2));
i++;
}else{
if(y.get(i) >= 0)
signo = 1;
else signo = -1;
area += y.get(i) * distancia(x.get(i - 1), f);
area += signo * (pi * Math.abs(Math.pow(distancia(x.get(i - 1), f), 2)));
i++;
}
}
return area;
}
public static List<Float> particionSin(List<Float> x){
List<Float> listY = new ArrayList<>();
List<Float> listY2 = new ArrayList<>();
for(Float f : x){
listY.add((float)Math.sin(f));
}
for(int i = 0; i < x.size(); i++){
listY2.add(listY.get(i) * x.get(i));
}
return listY2;
}
public static List<Float> xMasUno(List<Float> x){
List<Float> listY = new ArrayList<>();
List<Float> listY2 = new ArrayList<>();
for(Float f : x){
listY.add(f + 1);
}
for(int i = 0; i < x.size(); i++){
listY2.add(listY.get(i) * x.get(i));
}
return listY2;
}
public static List<Float> xALa2(List<Float> x){
List<Float> listY = new ArrayList<>();
List<Float> listY2 = new ArrayList<>();
for(Float f : x){
listY.add((float)Math.pow(f,2));
}
for(int i = 0; i < x.size(); i++){
listY2.add(listY.get(i) * x.get(i));
}
return listY2;
}
public static float derivada1(float a, float b, List<Float> x, List<Float> y){
int i = 0;
float derivada = 0;
List<Float> listIzq = puntosY(puntosIzq(x));
List<Float> listDer = puntosY(puntosDer(x));
for(Float f : x){
if(( i + 1) < x.size()){
if(( i -1 ) >= 0){
derivada += (listDer.get(i) - listIzq.get(i)) / (2 * distancia(x.get(i), x.get(i + 1)));
}
i++;
}
}
return derivada;
}
public static List<Float> puntosDer( List<Float> x){
List<Float> listY = new ArrayList<>();
int i = 0;
for(Float f : x){
if(( i + 1) < x.size()){
listY.add(f + distancia(x.get(i),x.get(i+1)));
i++;
}
}
return listY;
}
public static List<Float> puntosIzq( List<Float> x){
List<Float> listY = new ArrayList<>();
int i = 0;
for(Float f : x){
if(( i + 1) < x.size()){
listY.add(f - distancia(x.get(i),x.get(i+1)));
i++;
}
}
return listY;
}
public static float derivada2(float a, float b, List<Float> x, List<Float> y){
int i = 0;
float derivada2 = 0;
List<Float> listIzq = puntosY(puntosIzq(x));
List<Float> listDer = puntosY(puntosDer(x));
System.out.println("der: " + listDer.size() + "izq: " + listDer.size() + "x: " + x.size() + "y: " + y.size());
for(Float f : x){
if(( i + 1) < x.size()){
derivada2 += (listDer.get(i) + listIzq.get(i) - (2 * y.get(i))) / ( Math.pow(distancia(x.get(i), x.get(i + 1)),2));
i++;
}
}
return derivada2;
}
public static float errorTruncamientoTrap(float a, float b, List<Float> x, List<Float> y){
int i = 0;
float errorTruncamientoTrap = 0;
float derivada2 = 0;
List<Float> listIzq = puntosY(puntosIzq(x));
List<Float> listDer = puntosY(puntosDer(x));
System.out.println("der: " + listDer.size() + "izq: " + listDer.size() + "x: " + x.size() + "y: " + y.size());
for(Float f : x){
if(( i + 1) < x.size()){
if(( i -1 ) >= 0){
derivada2 += (listDer.get(i) + listIzq.get(i) - (2 * y.get(i))) / ( Math.pow(distancia(x.get(i), x.get(i + 1)),2));
errorTruncamientoTrap += (( Math.pow(distancia(x.get(i), x.get(i + 1)),3))/12) * derivada2 * (-1);
}
i++;
}
}
return errorTruncamientoTrap;
}
}
| daf28eb6f8dcb8f28a53c29b53cee4d36433fab2 | [
"Markdown",
"Java"
] | 2 | Markdown | SBarreto/Proyecto-Final-Analisis-Numerico | 984880701052033a67a173598a99deb861763574 | f0ac69687eac0edd529b127a7d6979d708fc8052 |
refs/heads/master | <repo_name>yung-chu/GemStockpiles<file_sep>/vue/src/libs/sweetAlert.js
import sweetalert from 'sweetalert';
import {resolve} from 'path';
export default {
text(message) {
swal(message);
},
message(title, message) {
swal(title, message);
},
success(title, message) {
swal(title, message, "success");
},
error(title, message) {
swal(title, message, "error");
},
warning(title, message) {
swal(title, message, "warning");
},
info(title, message) {
swal(title, message, "info");
},
confirm(title, message) {
var p = new Promise((resolve, reject) =>
{
swal({
title: title,
text: message,
icon: "warning",
buttons: ['取消','确定'],
dangerMode: true
}).then(istrue => {
if (istrue) {
resolve();
}
});
});
return p;
},
alert(title, message) {
var p = new Promise((resolve, reject) =>
{
swal({
title: title,
text: message,
icon: "warning",
buttons:'确定',
closeOnClickOutside: false,
closeOnEsc: false,
dangerMode: true
}).then(istrue => {
if (istrue) {
resolve();
}
});
});
return p;
}
}<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Roles/IRoleAppService.cs
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Roles.Dto;
using JFJT.GemStockpiles.Commons.Dto;
namespace JFJT.GemStockpiles.Roles
{
public interface IRoleAppService : IAsyncCrudAppService<RoleDto, int, PagedResultRequestExtendDto, CreateRoleDto, RoleDto>
{
/// <summary>
/// 根据ID获取编辑角色信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
Task<RoleDto> GetRoleForEdit(int id);
/// <summary>
/// 获取权限列表数据
/// </summary>
/// <returns></returns>
Task<ListResultDto<PermissionDto>> GetAllPermissions();
/// <summary>
/// 获取权限树形结构数据
/// </summary>
/// <returns></returns>
Task<ListResultDto<PermissionTreeDto>> GetTreePermissions();
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Web.Core/Controllers/GemStockpilesControllerBase.cs
using Microsoft.AspNetCore.Identity;
using Abp.IdentityFramework;
using Abp.AspNetCore.Mvc.Controllers;
namespace JFJT.GemStockpiles.Controllers
{
public abstract class GemStockpilesControllerBase : AbpController
{
protected GemStockpilesControllerBase()
{
LocalizationSourceName = GemStockpilesConsts.LocalizationSourceName;
}
protected void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Enums/OrderStateEnum.cs
using System;
namespace JFJT.GemStockpiles.Enums
{
/// <summary>
/// 订单状态
/// </summary>
public enum OrderStateEnum
{
/// <summary>
/// 待付款
/// </summary>
Paying = 10,
/// <summary>
/// 待确认
/// </summary>
Confirming = 20,
/// <summary>
/// 待发货
/// </summary>
Sending = 30,
/// <summary>
/// 待收货
/// </summary>
Receiving = 40,
/// <summary>
/// 待评价
/// </summary>
Appraising = 50,
/// <summary>
/// 已完成
/// </summary>
Completed = 60,
/// <summary>
/// 已关闭
/// </summary>
Closed = 70
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Points/PointRule.cs
using System;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Points
{
/// <summary>
/// 积分规则
/// </summary>
public class PointRule : FullAudited<Guid>
{
/// <summary>
/// 名称
/// </summary>
public PointActionEnum Name { get; set; } = PointActionEnum.Upload;
/// <summary>
/// 奖励分值
/// </summary>
public int Point { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
/// <summary>
/// 是否活动兑换
/// </summary>
public bool IsActivity { get; set; } = false;
/// <summary>
/// 是否兑换商品
/// </summary>
public bool IsCommodity { get; set; } = false;
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.EntityFrameworkCore/Migrations/20180613062354_InitialCreate.cs
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace JFJT.GemStockpiles.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AbpAuditLogs",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
BrowserInfo = table.Column<string>(maxLength: 512, nullable: true),
ClientIpAddress = table.Column<string>(maxLength: 64, nullable: true),
ClientName = table.Column<string>(maxLength: 128, nullable: true),
CustomData = table.Column<string>(maxLength: 2000, nullable: true),
Exception = table.Column<string>(maxLength: 2000, nullable: true),
ExecutionDuration = table.Column<int>(nullable: false),
ExecutionTime = table.Column<DateTime>(nullable: false),
ImpersonatorTenantId = table.Column<int>(nullable: true),
ImpersonatorUserId = table.Column<long>(nullable: true),
MethodName = table.Column<string>(maxLength: 256, nullable: true),
Parameters = table.Column<string>(maxLength: 1024, nullable: true),
ServiceName = table.Column<string>(maxLength: 256, nullable: true),
TenantId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpAuditLogs", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpBackgroundJobs",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
IsAbandoned = table.Column<bool>(nullable: false),
JobArgs = table.Column<string>(maxLength: 1048576, nullable: false),
JobType = table.Column<string>(maxLength: 512, nullable: false),
LastTryTime = table.Column<DateTime>(nullable: true),
NextTryTime = table.Column<DateTime>(nullable: false),
Priority = table.Column<byte>(nullable: false),
TryCount = table.Column<short>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpBackgroundJobs", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpEditions",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
DisplayName = table.Column<string>(maxLength: 64, nullable: false),
IsDeleted = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Name = table.Column<string>(maxLength: 32, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpEditions", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpEntityChangeSets",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
BrowserInfo = table.Column<string>(maxLength: 512, nullable: true),
ClientIpAddress = table.Column<string>(maxLength: 64, nullable: true),
ClientName = table.Column<string>(maxLength: 128, nullable: true),
CreationTime = table.Column<DateTime>(nullable: false),
ExtensionData = table.Column<string>(nullable: true),
ImpersonatorTenantId = table.Column<int>(nullable: true),
ImpersonatorUserId = table.Column<long>(nullable: true),
Reason = table.Column<string>(maxLength: 256, nullable: true),
TenantId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpEntityChangeSets", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpLanguages",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
DisplayName = table.Column<string>(maxLength: 64, nullable: false),
Icon = table.Column<string>(maxLength: 128, nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
IsDisabled = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Name = table.Column<string>(maxLength: 10, nullable: false),
TenantId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpLanguages", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpLanguageTexts",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
Key = table.Column<string>(maxLength: 256, nullable: false),
LanguageName = table.Column<string>(maxLength: 10, nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Source = table.Column<string>(maxLength: 128, nullable: false),
TenantId = table.Column<int>(nullable: true),
Value = table.Column<string>(maxLength: 67108864, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpLanguageTexts", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpNotifications",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
Data = table.Column<string>(maxLength: 1048576, nullable: true),
DataTypeName = table.Column<string>(maxLength: 512, nullable: true),
EntityId = table.Column<string>(maxLength: 96, nullable: true),
EntityTypeAssemblyQualifiedName = table.Column<string>(maxLength: 512, nullable: true),
EntityTypeName = table.Column<string>(maxLength: 250, nullable: true),
ExcludedUserIds = table.Column<string>(maxLength: 131072, nullable: true),
NotificationName = table.Column<string>(maxLength: 96, nullable: false),
Severity = table.Column<byte>(nullable: false),
TenantIds = table.Column<string>(maxLength: 131072, nullable: true),
UserIds = table.Column<string>(maxLength: 131072, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpNotifications", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpNotificationSubscriptions",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
EntityId = table.Column<string>(maxLength: 96, nullable: true),
EntityTypeAssemblyQualifiedName = table.Column<string>(maxLength: 512, nullable: true),
EntityTypeName = table.Column<string>(maxLength: 250, nullable: true),
NotificationName = table.Column<string>(maxLength: 96, nullable: true),
TenantId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpNotificationSubscriptions", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpOrganizationUnits",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Code = table.Column<string>(maxLength: 95, nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
DisplayName = table.Column<string>(maxLength: 128, nullable: false),
IsDeleted = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
ParentId = table.Column<long>(nullable: true),
TenantId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpOrganizationUnits", x => x.Id);
table.ForeignKey(
name: "FK_AbpOrganizationUnits_AbpOrganizationUnits_ParentId",
column: x => x.ParentId,
principalTable: "AbpOrganizationUnits",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "AbpTenantNotifications",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
Data = table.Column<string>(maxLength: 1048576, nullable: true),
DataTypeName = table.Column<string>(maxLength: 512, nullable: true),
EntityId = table.Column<string>(maxLength: 96, nullable: true),
EntityTypeAssemblyQualifiedName = table.Column<string>(maxLength: 512, nullable: true),
EntityTypeName = table.Column<string>(maxLength: 250, nullable: true),
NotificationName = table.Column<string>(maxLength: 96, nullable: false),
Severity = table.Column<byte>(nullable: false),
TenantId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpTenantNotifications", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpUserAccounts",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
EmailAddress = table.Column<string>(maxLength: 256, nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
LastLoginTime = table.Column<DateTime>(nullable: true),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
TenantId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: false),
UserLinkId = table.Column<long>(nullable: true),
UserName = table.Column<string>(maxLength: 32, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpUserAccounts", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpUserLoginAttempts",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
BrowserInfo = table.Column<string>(maxLength: 512, nullable: true),
ClientIpAddress = table.Column<string>(maxLength: 64, nullable: true),
ClientName = table.Column<string>(maxLength: 128, nullable: true),
CreationTime = table.Column<DateTime>(nullable: false),
Result = table.Column<byte>(nullable: false),
TenancyName = table.Column<string>(maxLength: 64, nullable: true),
TenantId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: true),
UserNameOrEmailAddress = table.Column<string>(maxLength: 255, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpUserLoginAttempts", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpUserNotifications",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
State = table.Column<int>(nullable: false),
TenantId = table.Column<int>(nullable: true),
TenantNotificationId = table.Column<Guid>(nullable: false),
UserId = table.Column<long>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpUserNotifications", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpUserOrganizationUnits",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
OrganizationUnitId = table.Column<long>(nullable: false),
TenantId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpUserOrganizationUnits", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpUsers",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
AccessFailedCount = table.Column<int>(nullable: false),
AuthenticationSource = table.Column<string>(maxLength: 64, nullable: true),
ConcurrencyStamp = table.Column<string>(maxLength: 128, nullable: true),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
EmailAddress = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmationCode = table.Column<string>(maxLength: 328, nullable: true),
IsActive = table.Column<bool>(nullable: false),
IsDeleted = table.Column<bool>(nullable: false),
IsEmailConfirmed = table.Column<bool>(nullable: false),
IsLockoutEnabled = table.Column<bool>(nullable: false),
IsPhoneNumberConfirmed = table.Column<bool>(nullable: false),
IsTwoFactorEnabled = table.Column<bool>(nullable: false),
LastLoginTime = table.Column<DateTime>(nullable: true),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
LockoutEndDateUtc = table.Column<DateTime>(nullable: true),
Name = table.Column<string>(maxLength: 32, nullable: false),
NormalizedEmailAddress = table.Column<string>(maxLength: 256, nullable: false),
NormalizedUserName = table.Column<string>(maxLength: 32, nullable: false),
Password = table.Column<string>(maxLength: 128, nullable: false),
PasswordResetCode = table.Column<string>(maxLength: 328, nullable: true),
PhoneNumber = table.Column<string>(maxLength: 32, nullable: true),
SecurityStamp = table.Column<string>(maxLength: 128, nullable: true),
Surname = table.Column<string>(maxLength: 32, nullable: true),
TenantId = table.Column<int>(nullable: true),
UserName = table.Column<string>(maxLength: 32, nullable: false),
UserType = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpUsers", x => x.Id);
table.ForeignKey(
name: "FK_AbpUsers_AbpUsers_CreatorUserId",
column: x => x.CreatorUserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_AbpUsers_AbpUsers_DeleterUserId",
column: x => x.DeleterUserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_AbpUsers_AbpUsers_LastModifierUserId",
column: x => x.LastModifierUserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Category",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Name = table.Column<string>(nullable: true),
ParentId = table.Column<Guid>(nullable: true),
Remark = table.Column<string>(nullable: true),
Sort = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Category", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Customer",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
AuditedAccount = table.Column<string>(nullable: true),
AuditedTime = table.Column<DateTime>(nullable: true),
Contact = table.Column<string>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
LastVisitIP = table.Column<string>(nullable: true),
LastVisitTime = table.Column<DateTime>(nullable: true),
Mobile = table.Column<string>(nullable: true),
NickName = table.Column<string>(nullable: true),
Password = table.Column<string>(nullable: true),
RegisterIP = table.Column<string>(nullable: true),
RegisterTime = table.Column<DateTime>(nullable: true),
RejectedRemark = table.Column<string>(nullable: true),
RoleType = table.Column<int>(nullable: false),
State = table.Column<int>(nullable: false),
UserName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Customer", x => x.Id);
});
migrationBuilder.CreateTable(
name: "CustomerCompany",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Address = table.Column<string>(nullable: true),
CompanyName = table.Column<string>(nullable: true),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
RegisterTime = table.Column<DateTime>(nullable: true),
UserId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CustomerCompany", x => x.Id);
});
migrationBuilder.CreateTable(
name: "CustomerCompanyLicense",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CompanyId = table.Column<Guid>(nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
ImageUrl = table.Column<string>(nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Sort = table.Column<int>(nullable: false),
Type = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CustomerCompanyLicense", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PointLog",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
ActionDesc = table.Column<string>(nullable: true),
ActionTime = table.Column<DateTime>(nullable: false),
ActionType = table.Column<int>(nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
MemberId = table.Column<int>(nullable: false),
Points = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PointLog", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PointRank",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Avatar = table.Column<string>(nullable: true),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
MinPoint = table.Column<int>(nullable: false),
Name = table.Column<string>(nullable: true),
Remark = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_PointRank", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PointRule",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
IsActivity = table.Column<bool>(nullable: false),
IsCommodity = table.Column<bool>(nullable: false),
IsDeleted = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Name = table.Column<int>(nullable: false),
Point = table.Column<int>(nullable: false),
Remark = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_PointRule", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Product",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
AuditState = table.Column<int>(nullable: false),
AuditedAccount = table.Column<string>(nullable: true),
AuditedTime = table.Column<DateTime>(nullable: true),
CategoryId = table.Column<Guid>(nullable: false),
CertNo = table.Column<string>(nullable: true),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
CustomerId = table.Column<int>(nullable: false),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
IsRecommend = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Name = table.Column<string>(nullable: true),
Number = table.Column<int>(nullable: false),
Price = table.Column<int>(nullable: false),
RejectedRemark = table.Column<string>(nullable: true),
Remark = table.Column<string>(nullable: true),
SaleState = table.Column<int>(nullable: false),
Sn = table.Column<string>(nullable: true),
Weight = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Product", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpFeatures",
columns: table => new
{
EditionId = table.Column<int>(nullable: true),
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
Discriminator = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 128, nullable: false),
TenantId = table.Column<int>(nullable: true),
Value = table.Column<string>(maxLength: 2000, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpFeatures", x => x.Id);
table.ForeignKey(
name: "FK_AbpFeatures_AbpEditions_EditionId",
column: x => x.EditionId,
principalTable: "AbpEditions",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AbpEntityChanges",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ChangeTime = table.Column<DateTime>(nullable: false),
ChangeType = table.Column<byte>(nullable: false),
EntityChangeSetId = table.Column<long>(nullable: false),
EntityId = table.Column<string>(maxLength: 48, nullable: true),
EntityTypeFullName = table.Column<string>(maxLength: 192, nullable: true),
TenantId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpEntityChanges", x => x.Id);
table.ForeignKey(
name: "FK_AbpEntityChanges_AbpEntityChangeSets_EntityChangeSetId",
column: x => x.EntityChangeSetId,
principalTable: "AbpEntityChangeSets",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AbpRoles",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ConcurrencyStamp = table.Column<string>(maxLength: 128, nullable: true),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
Description = table.Column<string>(maxLength: 5000, nullable: true),
DisplayName = table.Column<string>(maxLength: 64, nullable: false),
IsDefault = table.Column<bool>(nullable: false),
IsDeleted = table.Column<bool>(nullable: false),
IsStatic = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Name = table.Column<string>(maxLength: 32, nullable: false),
NormalizedName = table.Column<string>(maxLength: 32, nullable: false),
TenantId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpRoles", x => x.Id);
table.ForeignKey(
name: "FK_AbpRoles_AbpUsers_CreatorUserId",
column: x => x.CreatorUserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_AbpRoles_AbpUsers_DeleterUserId",
column: x => x.DeleterUserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_AbpRoles_AbpUsers_LastModifierUserId",
column: x => x.LastModifierUserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "AbpSettings",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Name = table.Column<string>(maxLength: 256, nullable: false),
TenantId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: true),
Value = table.Column<string>(maxLength: 2000, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpSettings", x => x.Id);
table.ForeignKey(
name: "FK_AbpSettings_AbpUsers_UserId",
column: x => x.UserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "AbpTenants",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ConnectionString = table.Column<string>(maxLength: 1024, nullable: true),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
EditionId = table.Column<int>(nullable: true),
IsActive = table.Column<bool>(nullable: false),
IsDeleted = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Name = table.Column<string>(maxLength: 128, nullable: false),
TenancyName = table.Column<string>(maxLength: 64, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpTenants", x => x.Id);
table.ForeignKey(
name: "FK_AbpTenants_AbpUsers_CreatorUserId",
column: x => x.CreatorUserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_AbpTenants_AbpUsers_DeleterUserId",
column: x => x.DeleterUserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_AbpTenants_AbpEditions_EditionId",
column: x => x.EditionId,
principalTable: "AbpEditions",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_AbpTenants_AbpUsers_LastModifierUserId",
column: x => x.LastModifierUserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "AbpUserClaims",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(maxLength: 256, nullable: true),
ClaimValue = table.Column<string>(nullable: true),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
TenantId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AbpUserClaims_AbpUsers_UserId",
column: x => x.UserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AbpUserLogins",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
ProviderKey = table.Column<string>(maxLength: 256, nullable: false),
TenantId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpUserLogins", x => x.Id);
table.ForeignKey(
name: "FK_AbpUserLogins_AbpUsers_UserId",
column: x => x.UserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AbpUserRoles",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
RoleId = table.Column<int>(nullable: false),
TenantId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpUserRoles", x => x.Id);
table.ForeignKey(
name: "FK_AbpUserRoles_AbpUsers_UserId",
column: x => x.UserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AbpUserTokens",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
LoginProvider = table.Column<string>(maxLength: 64, nullable: true),
Name = table.Column<string>(maxLength: 128, nullable: true),
TenantId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: false),
Value = table.Column<string>(maxLength: 512, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpUserTokens", x => x.Id);
table.ForeignKey(
name: "FK_AbpUserTokens_AbpUsers_UserId",
column: x => x.UserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "CategoryAttribute",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CategoryId = table.Column<Guid>(nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Name = table.Column<string>(nullable: true),
Required = table.Column<bool>(nullable: false),
Sort = table.Column<int>(nullable: false),
Type = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CategoryAttribute", x => x.Id);
table.ForeignKey(
name: "FK_CategoryAttribute_Category_CategoryId",
column: x => x.CategoryId,
principalTable: "Category",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ProductAttributeValue",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
AttributeName = table.Column<int>(nullable: false),
AttributeValue = table.Column<string>(nullable: true),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
ProductId = table.Column<Guid>(nullable: false),
Sort = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ProductAttributeValue", x => x.Id);
table.ForeignKey(
name: "FK_ProductAttributeValue_Product_ProductId",
column: x => x.ProductId,
principalTable: "Product",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ProductMedia",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
ProductId = table.Column<Guid>(nullable: false),
Sort = table.Column<int>(nullable: false),
Type = table.Column<int>(nullable: false),
Url = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ProductMedia", x => x.Id);
table.ForeignKey(
name: "FK_ProductMedia_Product_ProductId",
column: x => x.ProductId,
principalTable: "Product",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AbpEntityPropertyChanges",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
EntityChangeId = table.Column<long>(nullable: false),
NewValue = table.Column<string>(maxLength: 512, nullable: true),
OriginalValue = table.Column<string>(maxLength: 512, nullable: true),
PropertyName = table.Column<string>(maxLength: 96, nullable: true),
PropertyTypeFullName = table.Column<string>(maxLength: 192, nullable: true),
TenantId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpEntityPropertyChanges", x => x.Id);
table.ForeignKey(
name: "FK_AbpEntityPropertyChanges_AbpEntityChanges_EntityChangeId",
column: x => x.EntityChangeId,
principalTable: "AbpEntityChanges",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AbpPermissions",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
Discriminator = table.Column<string>(nullable: false),
IsGranted = table.Column<bool>(nullable: false),
Name = table.Column<string>(maxLength: 128, nullable: false),
TenantId = table.Column<int>(nullable: true),
RoleId = table.Column<int>(nullable: true),
UserId = table.Column<long>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpPermissions", x => x.Id);
table.ForeignKey(
name: "FK_AbpPermissions_AbpRoles_RoleId",
column: x => x.RoleId,
principalTable: "AbpRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AbpPermissions_AbpUsers_UserId",
column: x => x.UserId,
principalTable: "AbpUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AbpRoleClaims",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(maxLength: 256, nullable: true),
ClaimValue = table.Column<string>(nullable: true),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
RoleId = table.Column<int>(nullable: false),
TenantId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AbpRoleClaims_AbpRoles_RoleId",
column: x => x.RoleId,
principalTable: "AbpRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "CategoryAttributeItem",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CategoryAttributeId = table.Column<Guid>(nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
CreatorUserId = table.Column<long>(nullable: true),
DeleterUserId = table.Column<long>(nullable: true),
DeletionTime = table.Column<DateTime>(nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
LastModificationTime = table.Column<DateTime>(nullable: true),
LastModifierUserId = table.Column<long>(nullable: true),
Sort = table.Column<int>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_CategoryAttributeItem", x => x.Id);
table.ForeignKey(
name: "FK_CategoryAttributeItem_CategoryAttribute_CategoryAttributeId",
column: x => x.CategoryAttributeId,
principalTable: "CategoryAttribute",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AbpAuditLogs_TenantId_ExecutionDuration",
table: "AbpAuditLogs",
columns: new[] { "TenantId", "ExecutionDuration" });
migrationBuilder.CreateIndex(
name: "IX_AbpAuditLogs_TenantId_ExecutionTime",
table: "AbpAuditLogs",
columns: new[] { "TenantId", "ExecutionTime" });
migrationBuilder.CreateIndex(
name: "IX_AbpAuditLogs_TenantId_UserId",
table: "AbpAuditLogs",
columns: new[] { "TenantId", "UserId" });
migrationBuilder.CreateIndex(
name: "IX_AbpBackgroundJobs_IsAbandoned_NextTryTime",
table: "AbpBackgroundJobs",
columns: new[] { "IsAbandoned", "NextTryTime" });
migrationBuilder.CreateIndex(
name: "IX_AbpEntityChanges_EntityChangeSetId",
table: "AbpEntityChanges",
column: "EntityChangeSetId");
migrationBuilder.CreateIndex(
name: "IX_AbpEntityChanges_EntityTypeFullName_EntityId",
table: "AbpEntityChanges",
columns: new[] { "EntityTypeFullName", "EntityId" });
migrationBuilder.CreateIndex(
name: "IX_AbpEntityChangeSets_TenantId_CreationTime",
table: "AbpEntityChangeSets",
columns: new[] { "TenantId", "CreationTime" });
migrationBuilder.CreateIndex(
name: "IX_AbpEntityChangeSets_TenantId_Reason",
table: "AbpEntityChangeSets",
columns: new[] { "TenantId", "Reason" });
migrationBuilder.CreateIndex(
name: "IX_AbpEntityChangeSets_TenantId_UserId",
table: "AbpEntityChangeSets",
columns: new[] { "TenantId", "UserId" });
migrationBuilder.CreateIndex(
name: "IX_AbpEntityPropertyChanges_EntityChangeId",
table: "AbpEntityPropertyChanges",
column: "EntityChangeId");
migrationBuilder.CreateIndex(
name: "IX_AbpFeatures_EditionId_Name",
table: "AbpFeatures",
columns: new[] { "EditionId", "Name" });
migrationBuilder.CreateIndex(
name: "IX_AbpFeatures_TenantId_Name",
table: "AbpFeatures",
columns: new[] { "TenantId", "Name" });
migrationBuilder.CreateIndex(
name: "IX_AbpLanguages_TenantId_Name",
table: "AbpLanguages",
columns: new[] { "TenantId", "Name" });
migrationBuilder.CreateIndex(
name: "IX_AbpLanguageTexts_TenantId_Source_LanguageName_Key",
table: "AbpLanguageTexts",
columns: new[] { "TenantId", "Source", "LanguageName", "Key" });
migrationBuilder.CreateIndex(
name: "IX_AbpNotificationSubscriptions_NotificationName_EntityTypeName_EntityId_UserId",
table: "AbpNotificationSubscriptions",
columns: new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" });
migrationBuilder.CreateIndex(
name: "IX_AbpNotificationSubscriptions_TenantId_NotificationName_EntityTypeName_EntityId_UserId",
table: "AbpNotificationSubscriptions",
columns: new[] { "TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId" });
migrationBuilder.CreateIndex(
name: "IX_AbpOrganizationUnits_ParentId",
table: "AbpOrganizationUnits",
column: "ParentId");
migrationBuilder.CreateIndex(
name: "IX_AbpOrganizationUnits_TenantId_Code",
table: "AbpOrganizationUnits",
columns: new[] { "TenantId", "Code" });
migrationBuilder.CreateIndex(
name: "IX_AbpPermissions_TenantId_Name",
table: "AbpPermissions",
columns: new[] { "TenantId", "Name" });
migrationBuilder.CreateIndex(
name: "IX_AbpPermissions_RoleId",
table: "AbpPermissions",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AbpPermissions_UserId",
table: "AbpPermissions",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AbpRoleClaims_RoleId",
table: "AbpRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AbpRoleClaims_TenantId_ClaimType",
table: "AbpRoleClaims",
columns: new[] { "TenantId", "ClaimType" });
migrationBuilder.CreateIndex(
name: "IX_AbpRoles_CreatorUserId",
table: "AbpRoles",
column: "CreatorUserId");
migrationBuilder.CreateIndex(
name: "IX_AbpRoles_DeleterUserId",
table: "AbpRoles",
column: "DeleterUserId");
migrationBuilder.CreateIndex(
name: "IX_AbpRoles_LastModifierUserId",
table: "AbpRoles",
column: "LastModifierUserId");
migrationBuilder.CreateIndex(
name: "IX_AbpRoles_TenantId_NormalizedName",
table: "AbpRoles",
columns: new[] { "TenantId", "NormalizedName" });
migrationBuilder.CreateIndex(
name: "IX_AbpSettings_UserId",
table: "AbpSettings",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AbpSettings_TenantId_Name",
table: "AbpSettings",
columns: new[] { "TenantId", "Name" });
migrationBuilder.CreateIndex(
name: "IX_AbpTenantNotifications_TenantId",
table: "AbpTenantNotifications",
column: "TenantId");
migrationBuilder.CreateIndex(
name: "IX_AbpTenants_CreatorUserId",
table: "AbpTenants",
column: "CreatorUserId");
migrationBuilder.CreateIndex(
name: "IX_AbpTenants_DeleterUserId",
table: "AbpTenants",
column: "DeleterUserId");
migrationBuilder.CreateIndex(
name: "IX_AbpTenants_EditionId",
table: "AbpTenants",
column: "EditionId");
migrationBuilder.CreateIndex(
name: "IX_AbpTenants_LastModifierUserId",
table: "AbpTenants",
column: "LastModifierUserId");
migrationBuilder.CreateIndex(
name: "IX_AbpTenants_TenancyName",
table: "AbpTenants",
column: "TenancyName");
migrationBuilder.CreateIndex(
name: "IX_AbpUserAccounts_EmailAddress",
table: "AbpUserAccounts",
column: "EmailAddress");
migrationBuilder.CreateIndex(
name: "IX_AbpUserAccounts_UserName",
table: "AbpUserAccounts",
column: "UserName");
migrationBuilder.CreateIndex(
name: "IX_AbpUserAccounts_TenantId_EmailAddress",
table: "AbpUserAccounts",
columns: new[] { "TenantId", "EmailAddress" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserAccounts_TenantId_UserId",
table: "AbpUserAccounts",
columns: new[] { "TenantId", "UserId" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserAccounts_TenantId_UserName",
table: "AbpUserAccounts",
columns: new[] { "TenantId", "UserName" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserClaims_UserId",
table: "AbpUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AbpUserClaims_TenantId_ClaimType",
table: "AbpUserClaims",
columns: new[] { "TenantId", "ClaimType" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserLoginAttempts_UserId_TenantId",
table: "AbpUserLoginAttempts",
columns: new[] { "UserId", "TenantId" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserLoginAttempts_TenancyName_UserNameOrEmailAddress_Result",
table: "AbpUserLoginAttempts",
columns: new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserLogins_UserId",
table: "AbpUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AbpUserLogins_TenantId_UserId",
table: "AbpUserLogins",
columns: new[] { "TenantId", "UserId" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserLogins_TenantId_LoginProvider_ProviderKey",
table: "AbpUserLogins",
columns: new[] { "TenantId", "LoginProvider", "ProviderKey" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserNotifications_UserId_State_CreationTime",
table: "AbpUserNotifications",
columns: new[] { "UserId", "State", "CreationTime" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserOrganizationUnits_TenantId_OrganizationUnitId",
table: "AbpUserOrganizationUnits",
columns: new[] { "TenantId", "OrganizationUnitId" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserOrganizationUnits_TenantId_UserId",
table: "AbpUserOrganizationUnits",
columns: new[] { "TenantId", "UserId" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserRoles_UserId",
table: "AbpUserRoles",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AbpUserRoles_TenantId_RoleId",
table: "AbpUserRoles",
columns: new[] { "TenantId", "RoleId" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserRoles_TenantId_UserId",
table: "AbpUserRoles",
columns: new[] { "TenantId", "UserId" });
migrationBuilder.CreateIndex(
name: "IX_AbpUsers_CreatorUserId",
table: "AbpUsers",
column: "CreatorUserId");
migrationBuilder.CreateIndex(
name: "IX_AbpUsers_DeleterUserId",
table: "AbpUsers",
column: "DeleterUserId");
migrationBuilder.CreateIndex(
name: "IX_AbpUsers_LastModifierUserId",
table: "AbpUsers",
column: "LastModifierUserId");
migrationBuilder.CreateIndex(
name: "IX_AbpUsers_TenantId_NormalizedEmailAddress",
table: "AbpUsers",
columns: new[] { "TenantId", "NormalizedEmailAddress" });
migrationBuilder.CreateIndex(
name: "IX_AbpUsers_TenantId_NormalizedUserName",
table: "AbpUsers",
columns: new[] { "TenantId", "NormalizedUserName" });
migrationBuilder.CreateIndex(
name: "IX_AbpUserTokens_UserId",
table: "AbpUserTokens",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AbpUserTokens_TenantId_UserId",
table: "AbpUserTokens",
columns: new[] { "TenantId", "UserId" });
migrationBuilder.CreateIndex(
name: "IX_CategoryAttribute_CategoryId",
table: "CategoryAttribute",
column: "CategoryId");
migrationBuilder.CreateIndex(
name: "IX_CategoryAttributeItem_CategoryAttributeId",
table: "CategoryAttributeItem",
column: "CategoryAttributeId");
migrationBuilder.CreateIndex(
name: "IX_ProductAttributeValue_ProductId",
table: "ProductAttributeValue",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_ProductMedia_ProductId",
table: "ProductMedia",
column: "ProductId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AbpAuditLogs");
migrationBuilder.DropTable(
name: "AbpBackgroundJobs");
migrationBuilder.DropTable(
name: "AbpEntityPropertyChanges");
migrationBuilder.DropTable(
name: "AbpFeatures");
migrationBuilder.DropTable(
name: "AbpLanguages");
migrationBuilder.DropTable(
name: "AbpLanguageTexts");
migrationBuilder.DropTable(
name: "AbpNotifications");
migrationBuilder.DropTable(
name: "AbpNotificationSubscriptions");
migrationBuilder.DropTable(
name: "AbpOrganizationUnits");
migrationBuilder.DropTable(
name: "AbpPermissions");
migrationBuilder.DropTable(
name: "AbpRoleClaims");
migrationBuilder.DropTable(
name: "AbpSettings");
migrationBuilder.DropTable(
name: "AbpTenantNotifications");
migrationBuilder.DropTable(
name: "AbpTenants");
migrationBuilder.DropTable(
name: "AbpUserAccounts");
migrationBuilder.DropTable(
name: "AbpUserClaims");
migrationBuilder.DropTable(
name: "AbpUserLoginAttempts");
migrationBuilder.DropTable(
name: "AbpUserLogins");
migrationBuilder.DropTable(
name: "AbpUserNotifications");
migrationBuilder.DropTable(
name: "AbpUserOrganizationUnits");
migrationBuilder.DropTable(
name: "AbpUserRoles");
migrationBuilder.DropTable(
name: "AbpUserTokens");
migrationBuilder.DropTable(
name: "CategoryAttributeItem");
migrationBuilder.DropTable(
name: "Customer");
migrationBuilder.DropTable(
name: "CustomerCompany");
migrationBuilder.DropTable(
name: "CustomerCompanyLicense");
migrationBuilder.DropTable(
name: "PointLog");
migrationBuilder.DropTable(
name: "PointRank");
migrationBuilder.DropTable(
name: "PointRule");
migrationBuilder.DropTable(
name: "ProductAttributeValue");
migrationBuilder.DropTable(
name: "ProductMedia");
migrationBuilder.DropTable(
name: "AbpEntityChanges");
migrationBuilder.DropTable(
name: "AbpRoles");
migrationBuilder.DropTable(
name: "AbpEditions");
migrationBuilder.DropTable(
name: "CategoryAttribute");
migrationBuilder.DropTable(
name: "Product");
migrationBuilder.DropTable(
name: "AbpEntityChangeSets");
migrationBuilder.DropTable(
name: "AbpUsers");
migrationBuilder.DropTable(
name: "Category");
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Products/CategoryAttribute.cs
using System;
using System.Collections.Generic;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Products
{
/// <summary>
/// 产品分类属性表
/// </summary>
public class CategoryAttribute : FullAudited<Guid>
{
/// <summary>
/// 分类ID
/// </summary>
public Guid CategoryId { get; set; }
/// <summary>
/// 属性名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 分类属性类型
/// </summary>
public CategoryAttributeTypeEnum Type { get; set; } = CategoryAttributeTypeEnum.TextBox;
/// <summary>
/// 是否必须
/// </summary>
public bool Required { get; set; } = false;
/// <summary>
/// 排序
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 属性可选值列表
/// </summary>
public virtual List<CategoryAttributeItem> Items { get; set; } = new List<CategoryAttributeItem>();
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Products/CategoryAttributeItem.cs
using System;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Products
{
/// <summary>
/// 分类属性可选值表
/// </summary>
public class CategoryAttributeItem : FullAudited<Guid>
{
/// <summary>
/// 属性ID
/// </summary>
public Guid CategoryAttributeId { get; set; }
/// <summary>
/// 属性值
/// </summary>
public string Value { get; set; }
/// <summary>
/// 排序
/// </summary>
public int Sort { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Users/IUserAppService.cs
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Roles.Dto;
using JFJT.GemStockpiles.Users.Dto;
using JFJT.GemStockpiles.Commons.Dto;
namespace JFJT.GemStockpiles.Users
{
public interface IUserAppService : IAsyncCrudAppService<UserDto, long, PagedResultRequestExtendDto, CreateUserDto, UserDto>
{
/// <summary>
/// 获取系统角色数据
/// </summary>
/// <returns></returns>
Task<ListResultDto<RoleDto>> GetRoles();
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Entities/CreateModifyAudited.cs
using System;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
namespace JFJT.GemStockpiles.Entities
{
public class CreateModifyAudited : CreateModifyAudited<int>
{
}
public class CreateModifyAudited<TPrimaryKey> : Entity<TPrimaryKey>, ICreationAudited, IModificationAudited
{
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Users/Dto/UserDto.cs
using System;
using System.ComponentModel.DataAnnotations;
using Abp.Auditing;
using Abp.AutoMapper;
using Abp.Authorization.Users;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Authorization.Users;
namespace JFJT.GemStockpiles.Users.Dto
{
[AutoMapFrom(typeof(User))]
public class UserDto : EntityDto<long>
{
[Required]
[StringLength(AbpUserBase.MaxUserNameLength)]
public string UserName { get; set; }
[Required]
[StringLength(AbpUserBase.MaxNameLength)]
public string Name { get; set; }
[StringLength(AbpUserBase.MaxSurnameLength)]
public string Surname { get; set; }
[StringLength(AbpUserBase.MaxEmailAddressLength)]
public string EmailAddress { get; set; }
[Required]
[DisableAuditing]
public string Password { get; set; }
public bool IsActive { get; set; }
public string FullName { get; set; }
public DateTime? LastLoginTime { get; set; }
public DateTime CreationTime { get; set; }
public string[] RoleNames { get; set; }
[Required]
public virtual UserTypeEnum UserType { get; set; } = UserTypeEnum.Administrator;
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Authorization/PermissionNames.cs
namespace JFJT.GemStockpiles.Authorization
{
/// <summary>
/// Defines string constants for application's permission names.
/// </summary>
public static class PermissionNames
{
// 根节点
public const string Pages = "Pages";
#region 系统管理
public const string Pages_SystemManagement = "Pages.SystemManagement";
//角色
public const string Pages_SystemManagement_Roles = "Pages.SystemManagement.Roles";
public const string Pages_SystemManagement_Roles_View = "Pages.SystemManagement.Roles.View";
public const string Pages_SystemManagement_Roles_Create = "Pages.SystemManagement.Roles.Create";
public const string Pages_SystemManagement_Roles_Edit = "Pages.SystemManagement.Roles.Edit";
public const string Pages_SystemManagement_Roles_Delete = "Pages.SystemManagement.Roles.Delete";
//用户
public const string Pages_SystemManagement_Users = "Pages.SystemManagement.Users";
public const string Pages_SystemManagement_Users_View = "Pages.SystemManagement.Users.View";
public const string Pages_SystemManagement_Users_Create = "Pages.SystemManagement.Users.Create";
public const string Pages_SystemManagement_Users_Edit = "Pages.SystemManagement.Users.Edit";
public const string Pages_SystemManagement_Users_Delete = "Pages.SystemManagement.Users.Delete";
//租户
public const string Pages_SystemManagement_Tenants = "Pages.SystemManagement.Tenants";
public const string Pages_SystemManagement_Tenants_View = "Pages.SystemManagement.Tenants.View";
public const string Pages_SystemManagement_Tenants_Create = "Pages.SystemManagement.Tenants.Create";
public const string Pages_SystemManagement_Tenants_Edit = "Pages.SystemManagement.Tenants.Edit";
public const string Pages_SystemManagement_Tenants_Delete = "Pages.SystemManagement.Tenants.Delete";
#endregion
#region 积分管理
public const string Pages_PointManagement = "Pages.PointManagement";
public const string Pages_PointManagement_PointRules = "Pages.PointManagement.PointRules";
public const string Pages_PointManagement_PointRules_View = "Pages.PointManagement.PointRules.View";
public const string Pages_PointManagement_PointRules_Create = "Pages.PointManagement.PointRules.Create";
public const string Pages_PointManagement_PointRules_Edit = "Pages.PointManagement.PointRules.Edit";
public const string Pages_PointManagement_PointRules_Delete = "Pages.PointManagement.PointRules.Delete";
public const string Pages_PointManagement_PointRanks = "Pages.PointManagement.PointRanks";
public const string Pages_PointManagement_PointRanks_View = "Pages.PointManagement.PointRanks.View";
public const string Pages_PointManagement_PointRanks_Create = "Pages.PointManagement.PointRanks.Create";
public const string Pages_PointManagement_PointRanks_Edit = "Pages.PointManagement.PointRanks.Edit";
public const string Pages_PointManagement_PointRanks_Delete = "Pages.PointManagement.PointRanks.Delete";
#endregion
#region 商品管理
public const string Pages_ProductManagement = "Pages.ProductManagement";
//商品列表
public const string Pages_ProductManagement_Products = "Pages.ProductManagement.Products";
public const string Pages_ProductManagement_Products_View = "Pages.ProductManagement.Products.View";
public const string Pages_ProductManagement_Products_Create = "Pages.ProductManagement.Products.Create ";
public const string Pages_ProductManagement_Products_Edit = "Pages.ProductManagement.Products.Edit";
public const string Pages_ProductManagement_Products_Delete = "Pages.ProductManagement.Products.Delete";
//分类管理
public const string Pages_ProductManagement_Categorys = "Pages.ProductManagement.Categorys";
public const string Pages_ProductManagement_Categorys_View = "Pages.ProductManagement.Categorys.View";
public const string Pages_ProductManagement_Categorys_Create = "Pages.ProductManagement.Categorys.Create";
public const string Pages_ProductManagement_Categorys_Edit = "Pages.ProductManagement.Categorys.Edit";
public const string Pages_ProductManagement_Categorys_Delete = "Pages.ProductManagement.Categorys.Delete";
//分类属性
public const string Pages_ProductManagement_CategoryAttributes = "Pages.ProductManagement.CategoryAttributes";
public const string Pages_ProductManagement_CategoryAttributes_View = "Pages.ProductManagement.CategoryAttributes.View";
public const string Pages_ProductManagement_CategoryAttributes_Create = "Pages.ProductManagement.CategoryAttributes.Create";
public const string Pages_ProductManagement_CategoryAttributes_Edit = "Pages.ProductManagement.CategoryAttributes.Edit";
public const string Pages_ProductManagement_CategoryAttributes_Delete = "Pages.ProductManagement.CategoryAttributes.Delete";
#endregion
#region 订单管理
public const string Pages_OrderManagement = "Pages.OrderManagement";
//订单列表
public const string Pages_OrderManagement_Orders = "Pages.OrderManagement.Orders";
public const string Pages_OrderManagement_Orders_View = "Pages.OrderManagement.Orders.View";
public const string Pages_OrderManagement_Orders_Create = "Pages.OrderManagement.Orders.Create ";
public const string Pages_OrderManagement_Orders_Edit = "Pages.OrderManagement.Orders.Edit";
public const string Pages_OrderManagement_Orders_Delete = "Pages.OrderManagement.Orders.Delete";
//订单评论
public const string Pages_OrderManagement_Comments = "Pages.OrderManagement.Comments";
public const string Pages_OrderManagement_Comments_View = "Pages.OrderManagement.Comments.View";
public const string Pages_OrderManagement_Comments_Create = "Pages.OrderManagement.Comments.Create ";
public const string Pages_OrderManagement_Comments_Edit = "Pages.OrderManagement.Comments.Edit";
public const string Pages_OrderManagement_Comments_Delete = "Pages.OrderManagement.Comments.Delete";
#endregion
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Enums/UserTypeEnum.cs
using System;
namespace JFJT.GemStockpiles.Enums
{
public enum UserTypeEnum
{
/// <summary>
/// 后台管理员
/// </summary>
Administrator = 1,
/// <summary>
/// 个人
/// </summary>
Personal = 2,
/// <summary>
/// 商家
/// </summary>
Merchant = 3
}
}
<file_sep>/vue/src/store/modules/product/attributeItem.js
import Ajax from '@/libs/ajax';
const attributeItem = {
namespaced: true,
state: {
list: [],
loading: false,
currentAttributeId: 0,
editAttributeItemId: 0
},
mutations: {
edit(state, id) {
state.editAttributeItemId = id;
},
clearList(state) {
state.list = [];
}
},
actions: {
async get(context, payload) {
return await Ajax.get('/api/services/app/CategoryAttributeItem/Get?Id=' + payload.id);
},
async create(context, payload) {
return await Ajax.post('/api/services/app/CategoryAttributeItem/Create', payload.data);
},
async update(context, payload) {
return await Ajax.put('/api/services/app/CategoryAttributeItem/Update', payload.data);
},
async delete(context, payload) {
return await Ajax.delete('/api/services/app/CategoryAttributeItem/Delete?Id=' + payload.data.id);
},
async getCategoryAttributeItems(context, payload) {
//记录当前查询的属性ID
context.state.currentAttributeId = payload.data.id;
context.state.loading = true;
let response = await Ajax.get('/api/services/app/CategoryAttributeItem/GetCategoryAttributeItems?AttributeId=' + payload.data.id);
context.state.loading = false;
context.state.list = response.data.result.items;
}
}
}
export default attributeItem;<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Orders/Order.cs
using System;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Orders
{
/// <summary>
/// 订单信息
/// </summary>
public class Order : FullAudited<Guid>
{
/// <summary>
/// 订单编号
/// </summary>
public string OrderSn { get; set; }
/// <summary>
/// 订单重量
/// </summary>
public int OrderWeight { get; set; }
/// <summary>
/// 订单金额
/// </summary>
public int OrderAmount { get; set; }
/// <summary>
/// 订单状态
/// </summary>
public OrderStateEnum OrderState { get; set; } = OrderStateEnum.Paying;
/// <summary>
/// 订单时间
/// </summary>
private DateTime OrderTime { get; set; } = DateTime.Now;
#region 买家信息
/// <summary>
/// 买家Id
/// </summary>
public string BuyerId { get; set; }
/// <summary>
/// 买家用户名
/// </summary>
public string BuyerUserName { get; set; }
/// <summary>
/// 收货人
/// </summary>
public string Consignee { get; set; }
/// <summary>
/// 联系电话
/// </summary>
public string Mobile { get; set; }
/// <summary>
/// 收货地区ID
/// </summary>
public int RegionId { get; set; }
/// <summary>
/// 收货详细地址
/// </summary>
public string Address { get; set; }
/// <summary>
/// 买家备注
/// </summary>
public string BuyerRemark { get; set; }
#endregion
#region 卖家信息
/// <summary>
/// 卖家Id
/// </summary>
public string SellerId { get; set; }
/// <summary>
/// 卖家用户名
/// </summary>
public string SellerUserName { get; set; }
/// <summary>
/// 供应商名称
/// </summary>
public string Supplier { get; set; }
#endregion
#region 支付信息
/// <summary>
/// 支付方式
/// </summary>
public PayModeEnum PayMode { get; set; } = PayModeEnum.OfflinePay;
/// <summary>
/// 支付流水号
/// </summary>
public string PaySn { get; set; }
/// <summary>
/// 支付时间
/// </summary>
public DateTime PayTime { get; set; }
#endregion
#region 配送信息
/// <summary>
/// 配送单号
/// </summary>
public string ShipSn { get; set; }
/// <summary>
/// 配送公司
/// </summary>
public string ShipCompany { get; set; }
/// <summary>
/// 配送时间
/// </summary>
public DateTime ShipTime { get; set; }
#endregion
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/Categorys/ICategoryAppService.cs
using System;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Products.Categorys.Dto;
namespace JFJT.GemStockpiles.Products.Categorys
{
public interface ICategoryAppService : IAsyncCrudAppService<CategoryDto, Guid, PagedResultRequestDto, CategoryDto, CategoryDto>
{
Task<ListResultDto<CategoryDto>> GetParent();
Task<ListResultDto<CategoryTreeDto>> GetTreeCategory();
Task<ListResultDto<CategoryCascaderDto>> GetCascaderCategory();
}
}<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Points/PointRanks/IPointRankAppService.cs
using System;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Points.PointRanks.Dto;
namespace JFJT.GemStockpiles.Points.PointRanks
{
public interface IPointRankAppService : IAsyncCrudAppService<PointRankDto, Guid, PagedResultRequestDto, PointRankDto, PointRankDto>
{
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Enums/CompanyLicenseTypeEnum.cs
using System;
namespace JFJT.GemStockpiles.Enums
{
/// <summary>
/// 公司证书类型
/// </summary>
public enum CompanyLicenseTypeEnum
{
/// <summary>
/// 营业执照
/// </summary>
BusinessLicense = 10,
/// <summary>
/// 税务登记证
/// </summary>
TaxRegisterLicense = 20,
/// <summary>
/// 组织机构代码证
/// </summary>
OrganizationCodeLicense = 30
}
}
<file_sep>/vue/src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import app from './modules/common/app';
import common from './modules/common/common';
import session from './modules/common/session';
import user from './modules/admin/user';
import role from './modules/admin/role';
import pointRank from './modules/point/pointRank';
import pointRule from './modules/point/pointRule';
import category from './modules/product/category';
import attribute from './modules/product/attribute';
import attributeItem from './modules/product/attributeItem';
import product from './modules/product/product';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
//
},
mutations: {
//
},
actions: {
//
},
modules: {
app,
common,
session,
user,
role,
pointRank,
pointRule,
category,
attribute,
attributeItem,
product,
}
});
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Points/PointRanks/PointRankAppService.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Identity;
using Abp.UI;
using Abp.Authorization;
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using Abp.IdentityFramework;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Helpers;
using JFJT.GemStockpiles.Sessions.Dto;
using JFJT.GemStockpiles.Authorization;
using JFJT.GemStockpiles.Models.Points;
using JFJT.GemStockpiles.Models.Configs;
using JFJT.GemStockpiles.Points.PointRanks.Dto;
namespace JFJT.GemStockpiles.Points.PointRanks
{
[AbpAuthorize(PermissionNames.Pages_PointManagement_PointRanks)]
public class PointRankAppService : AsyncCrudAppService<PointRank, PointRankDto, Guid, PagedResultRequestDto, PointRankDto, PointRankDto>, IPointRankAppService
{
private readonly IRepository<PointRank, Guid> _pointRankRepository;
private readonly IOptions<AppSettings> _appSettings;
private readonly UploadHelper uploadHelper;
public PointRankAppService(IRepository<PointRank, Guid> pointRankRepository, IOptions<AppSettings> appSettings)
: base(pointRankRepository)
{
_pointRankRepository = pointRankRepository;
_appSettings = appSettings;
uploadHelper = new UploadHelper(appSettings);
}
/// <summary>
/// 新增积分等级
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_PointManagement_PointRanks_Create)]
public override async Task<PointRankDto> Create(PointRankDto input)
{
CheckCreatePermission();
CheckErrors(await CheckNameOrMinPointAsync(input.Id, input.Name, input.MinPoint));
var entity = ObjectMapper.Map<PointRank>(input);
entity = await _pointRankRepository.InsertAsync(entity);
//移动文件
if (!string.IsNullOrWhiteSpace(entity.Avatar))
{
uploadHelper.MoveFile(entity.Avatar, UploadType.PointAvatar, FileType.Image, AbpSession.UserId);
}
return MapToEntityDto(entity);
}
/// <summary>
/// 修改积分等级
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_PointManagement_PointRanks_Edit)]
public override async Task<PointRankDto> Update(PointRankDto input)
{
CheckUpdatePermission();
var entity = await _pointRankRepository.GetAsync(input.Id);
if (entity == null)
throw new EntityNotFoundException(typeof(PointRank), input.Id);
var oldAvatar = entity.Avatar;
CheckErrors(await CheckNameOrMinPointAsync(input.Id, input.Name, input.MinPoint));
MapToEntity(input, entity);
entity = await _pointRankRepository.UpdateAsync(entity);
//头像文件处理
if (oldAvatar != entity.Avatar)
{
uploadHelper.MoveFile(entity.Avatar, UploadType.PointAvatar, FileType.Image, AbpSession.UserId);
uploadHelper.DeleteFile(oldAvatar, UploadType.PointAvatar, FileType.Image);
}
return MapToEntityDto(entity);
}
/// <summary>
/// 删除积分等级
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_PointManagement_PointRanks_Delete)]
public override async Task Delete(EntityDto<Guid> input)
{
CheckDeletePermission();
var entity = await _pointRankRepository.GetAsync(input.Id);
if (entity == null)
throw new EntityNotFoundException(typeof(PointRank), input.Id);
await _pointRankRepository.DeleteAsync(entity);
//删除头像文件
if (!string.IsNullOrWhiteSpace(entity.Avatar))
{
uploadHelper.DeleteFile(entity.Avatar, UploadType.PointAvatar, FileType.Image);
}
}
/// <summary>
/// Dto模型映射
/// </summary>
/// <param name="input"></param>
/// <param name="pointRank"></param>
protected override void MapToEntity(PointRankDto input, PointRank pointRank)
{
ObjectMapper.Map(input, pointRank);
}
/// <summary>
/// 根据ID获取Entity模型
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
protected override async Task<PointRank> GetEntityByIdAsync(Guid id)
{
var entity = await Repository.FirstOrDefaultAsync(x => x.Id == id);
if (entity == null)
{
throw new EntityNotFoundException(typeof(PointRank), id);
}
return entity;
}
/// <summary>
/// GetAll查询排序条件
/// </summary>
/// <param name="query"></param>
/// <param name="input"></param>
/// <returns></returns>
protected override IQueryable<PointRank> ApplySorting(IQueryable<PointRank> query, PagedResultRequestDto input)
{
return query.OrderBy(r => r.MinPoint);
}
/// <summary>
/// 检测积分等级名称或最小积分值是否已存在
/// </summary>
/// <param name="expectedId"></param>
/// <param name="name"></param>
/// <param name="minPoint"></param>
/// <returns></returns>
protected async Task<IdentityResult> CheckNameOrMinPointAsync(Guid? expectedId, string name, int minPoint)
{
var entity = await _pointRankRepository.FirstOrDefaultAsync(b => b.Name == name);
if (entity != null && entity.Id != expectedId)
{
throw new UserFriendlyException(name + " 等级名称已存在");
}
entity = await _pointRankRepository.FirstOrDefaultAsync(b => b.MinPoint == minPoint);
if (entity != null && entity.Id != expectedId)
{
throw new UserFriendlyException(minPoint + " 最小积分已存在");
}
return IdentityResult.Success;
}
/// <summary>
/// 异常描述本地化转换函数
/// </summary>
/// <param name="identityResult"></param>
protected virtual void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Configs/UploadConfig.cs
using System;
namespace JFJT.GemStockpiles.Models.Configs
{
/// <summary>
/// 文件上传配置
/// </summary>
public class UploadConfig
{
/// <summary>
/// 公共上传文件配置
/// </summary>
public Common Common { get; set; }
/// <summary>
/// 积分头像文件上传配置
/// </summary>
public PointAvatar PointAvatar { get; set; }
}
/// <summary>
/// 公共配置
/// </summary>
public class Common
{
/// <summary>
/// 文件上传根目录
/// </summary>
public string BasePath { get; set; }
/// <summary>
/// 文件上传临时目录
/// </summary>
public string TempFolderName { get; set; }
}
/// <summary>
/// 积分头像
/// </summary>
public class PointAvatar
{
/// <summary>
/// 文件目录
/// </summary>
public string FolderName { get; set; }
/// <summary>
/// 文件大小
/// </summary>
public string FileSize { get; set; }
/// <summary>
/// 文件扩展类型
/// </summary>
public string FileExtension { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/CategoryAttributes/ICategoryAttributeAppService.cs
using System;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Commons.Dto;
using JFJT.GemStockpiles.Products.Categorys.Dto;
using JFJT.GemStockpiles.Products.CategoryAttributes.Dto;
namespace JFJT.GemStockpiles.Products.CategoryAttributes
{
public interface ICategoryAttributeAppService : IAsyncCrudAppService<CategoryAttributeDto, Guid, PagedResultRequestExtendDto, CategoryAttributeDto, CategoryAttributeDto>
{
/// <summary>
/// 获取属性类型列表
/// </summary>
/// <returns></returns>
Task<ListResultDto<IdAndNameDto>> GetAllAttributeTypes();
/// <summary>
/// 获取分类树形结构数据
/// </summary>
/// <returns></returns>
Task<ListResultDto<CategoryCascaderDto>> GetAllAttr();
/// <summary>
/// 根据分类ID获取属性列表
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
Task<ListResultDto<CategoryAttributeDto>> GetAttr(Guid Id);
/// <summary>
/// 根据ID获取编辑属性信息
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
Task<CategoryAttributeDto> GetAttributeForEdit(Guid Id);
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Customers/Customer.cs
using System;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Customers
{
/// <summary>
/// 客户表
/// </summary>
public class Customer : ModifyDeleteAudited
{
/// <summary>
/// 登录账号
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 登录密码
/// </summary>
public string Password { get; set; }
/// <summary>
/// 用户昵称
/// </summary>
public string NickName { get; set; }
/// <summary>
/// 注册手机号码
/// </summary>
public string Mobile { get; set; }
/// <summary>
/// 联系方式
/// </summary>
public string Contact { get; set; }
/// <summary>
/// 角色类型
/// </summary>
public UserRoleTypeEnum RoleType { get; set; } = UserRoleTypeEnum.Person;
/// <summary>
/// 账号状态
/// </summary>
public UserStateEnum State { get; set; } = UserStateEnum.Submited;
/// <summary>
/// 审核人登录帐号
/// </summary>
public string AuditedAccount { get; set; }
/// <summary>
/// 审核时间
/// </summary>
public DateTime? AuditedTime { get; set; }
/// <summary>
/// 驳回原因
/// </summary>
public string RejectedRemark { get; set; }
/// <summary>
/// 注册IP
/// </summary>
public string RegisterIP { get; set; }
/// <summary>
/// 注册时间
/// </summary>
public DateTime? RegisterTime { get; set; } = DateTime.Now;
/// <summary>
/// 最后访问IP
/// </summary>
public string LastVisitIP { get; set; }
/// <summary>
/// 最后访问时间
/// </summary>
public DateTime? LastVisitTime { get; set; } = DateTime.Now;
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Configs/AppSettings.cs
using System;
namespace JFJT.GemStockpiles.Models.Configs
{
public class AppSettings
{
/// <summary>
/// 文件上传配置
/// </summary>
public UploadConfig UploadConfig { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/Products/ProductAppService.cs
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using JFJT.GemStockpiles.Authorization;
using JFJT.GemStockpiles.Models.Products;
using JFJT.GemStockpiles.Products.Products.Dto;
namespace JFJT.GemStockpiles.Products.Products
{
[AbpAuthorize(PermissionNames.Pages_ProductManagement_Products)]
public class ProductAppService : AsyncCrudAppService<Product, ProductDto, Guid, PagedResultRequestDto, ProductDto, ProductDto>, IProductAppService
{
private readonly IRepository<Product, Guid> _productRepository;
public ProductAppService(IRepository<Product, Guid> productRepository)
: base(productRepository)
{
_productRepository = productRepository;
}
}
}<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Orders/OrderAppeal.cs
using System;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Orders
{
/// <summary>
/// 申诉订单
/// </summary>
public class OrderAppeal : FullAudited<Guid>
{
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Points/PointRules/IPointRuleAppService.cs
using System;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Commons.Dto;
using JFJT.GemStockpiles.Points.PointRules.Dto;
namespace JFJT.GemStockpiles.Points.PointRules
{
public interface IPointRuleAppService : IAsyncCrudAppService<PointRuleDto, Guid, PagedResultRequestDto, PointRuleDto, PointRuleDto>
{
/// <summary>
/// 获取积分动作列表
/// </summary>
/// <returns></returns>
Task<ListResultDto<IdAndNameDto>> GetAllPointActions();
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Helpers/UploadHelper.cs
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using JFJT.GemStockpiles.Models.Configs;
namespace JFJT.GemStockpiles.Helpers
{
public class UploadHelper
{
private readonly IOptions<AppSettings> _appSettings;
public UploadHelper(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings;
}
#region 获取配置项
/// <summary>
/// 上传文件根目录
/// </summary>
private string BasePath
{
get
{
return _appSettings.Value.UploadConfig.Common.BasePath;
}
}
/// <summary>
/// 文件上传临时目录
/// </summary>
private string TempFolderName
{
get
{
return _appSettings.Value.UploadConfig.Common.TempFolderName;
}
}
/// <summary>
/// 上传文件类型对应的文件目录
/// </summary>
/// <param name="uploadType"></param>
/// <param name="filetype"></param>
/// <returns></returns>
private string GetFilePath(UploadType uploadType, FileType filetype)
{
switch (uploadType)
{
case UploadType.PointAvatar:
return _appSettings.Value.UploadConfig.PointAvatar.FolderName;
default:
return "";
}
}
/// <summary>
/// 上传文件大小
/// </summary>
/// <param name="uploadType"></param>
/// <param name="filetype"></param>
/// <returns></returns>
private string GetFileSize(UploadType uploadType, FileType filetype)
{
switch (uploadType)
{
case UploadType.PointAvatar:
return _appSettings.Value.UploadConfig.PointAvatar.FileSize;
default:
return "";
}
}
/// <summary>
/// 上传文件扩展类型
/// </summary>
/// <param name="uploadType"></param>
/// <param name="filetype"></param>
/// <returns></returns>
private string GetFileExtension(UploadType uploadType, FileType filetype)
{
switch (uploadType)
{
case UploadType.PointAvatar:
return _appSettings.Value.UploadConfig.PointAvatar.FileExtension;
default:
return "";
}
}
#endregion
#region 文件验证
/// <summary>
/// 上传文件验证
/// </summary>
/// <param name="file">文件对象</param>
/// <param name="uploadType">上传类型</param>
/// <param name="filetype">文件类型</param>
/// <param name="Error">错误消息</param>
/// <returns></returns>
public bool Validate(IFormFile file, UploadType uploadType, FileType filetype, out string Error)
{
string extensValue = GetFileExtension(uploadType, filetype);
long size = Convert.ToInt32(GetFileSize(uploadType, filetype)) * 1024;
Error = "";
if (!ValidateExtension(extensValue, file.FileName))
{
Error = "文件类型错误";
return false;
}
if (!ValidateSize(size, file.Length))
{
Error = "文件大小不可超过" + size / 1024 + "KB";
return false;
}
return true;
}
/// <summary>
/// 验证文件类型
/// </summary>
/// <param name="ExtensionValue"></param>
/// <param name="fileName"></param>
/// <returns></returns>
private bool ValidateExtension(string ExtensionValue, string fileName)
{
string ext = GetExtensionName(fileName).ToLower();
return ExtensionValue.ToLower().Contains(ext);
}
/// <summary>
/// 验证文件大小
/// </summary>
/// <param name="Size"></param>
/// <param name="fileSize"></param>
/// <returns></returns>
private bool ValidateSize(long Size, long fileSize)
{
return fileSize <= Size;
}
#endregion
#region 功能函数
/// <summary>
/// 返回文件扩展名
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public string GetExtensionName(string fileName)
{
return Path.GetExtension(fileName);
}
/// <summary>
/// 获取文件保存信息
/// </summary>
/// <param name="fileName">文件名称</param>
/// <param name="loginUserId">当前登录用户ID</param>
/// <returns></returns>
public async Task<SaveFileResult> SaveFile(IFormFile file, long? loginUserId)
{
//登录用户文件夹
string loginUserFolder = "user" + loginUserId?.ToString();
//临时存储的相对路径
string relativePath = $"{BasePath}/{TempFolderName}/{loginUserFolder}";
//获取服务器根目录
string rootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
//临时存储的绝对路径
string filePath = $"{rootPath}/{relativePath}";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
//存储的文件名称
string fileName = Guid.NewGuid() + GetExtensionName(file.FileName);
//保存文件
filePath = Path.Combine(filePath, fileName);
using (FileStream fs = File.Create(filePath))
{
await file.CopyToAsync(fs);
fs.Flush();
}
//返回存储结果
SaveFileResult result = new SaveFileResult()
{
FileName = fileName,
FilePath = filePath,
RelativePath = $"{relativePath}/{fileName}"
};
return result;
}
/// <summary>
/// 移动文件
/// </summary>
/// <param name="fileName">文件名称</param>
/// <param name="fileType">文件类型</param>
/// <param name="uploadType">上传类型</param>
/// <param name="currentUserFolder">当前登录用户临时目录文件名</param>
/// <returns></returns>
public void MoveFile(string fileName, UploadType uploadType, FileType fileType, long? loginUserId)
{
//登录用户文件夹
string loginUserFolder = "user" + loginUserId?.ToString();
//临时相对路径
string tempRelativePath = $"{BasePath}/{TempFolderName}/{loginUserFolder}";
//存储相对路径
string saveRelativePath = $"{BasePath}/{GetFilePath(uploadType, fileType)}";
//获取服务器目录
string rootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
//判断文件是否存在
string fileTempPath = $"{rootPath}/{tempRelativePath}/{fileName}";
if (!File.Exists(fileTempPath))
{
return;
}
//文件保存路径
string fileDestPath = $"{rootPath}/{saveRelativePath}";
if (!Directory.Exists(fileDestPath))
{
Directory.CreateDirectory(fileDestPath);
}
fileDestPath = $"{fileDestPath}/{fileName}";
//确认目标文件不存在
if (File.Exists(fileDestPath))
{
File.Delete(fileDestPath);
}
//移动文件
File.Move(fileTempPath, fileDestPath);
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName">文件名称</param>
/// <param name="fileType">文件类型</param>
/// <param name="uploadType">上传类型</param>
public void DeleteFile(string fileName, UploadType uploadType, FileType fileType)
{
//文件相对路径
string fileRelativePath = $"{BasePath}/{GetFilePath(uploadType, fileType)}";
//获取服务器目录
string rootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
//判断文件是否存在
string filePath = $"{rootPath}/{fileRelativePath}/{fileName}";
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
/// <summary>
/// 删除登录用户临时目录
/// </summary>
/// <param name="loginUserId"></param>
public void ClearTempDirectory(long? loginUserId)
{
//登录用户文件夹
string loginUserFolder = "user" + loginUserId?.ToString();
//临时相对路径
string tempRelativePath = $"{BasePath}/{TempFolderName}/{loginUserFolder}";
//获取服务器目录
string rootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
//删除目录及子文件
string tempDirectory = $"{rootPath}/{tempRelativePath}";
if (Directory.Exists(tempDirectory))
{
Directory.Delete(tempDirectory, true);
}
}
#endregion
}
/// <summary>
/// 上传类型
/// </summary>
public enum UploadType
{
/// <summary>
/// 积分头像
/// </summary>
PointAvatar = 10
}
/// <summary>
/// 文件类型
/// </summary>
public enum FileType
{
/// <summary>
///图片
/// </summary>
Image = 10,
/// <summary>
/// 视频
/// </summary>
Video = 20
}
/// <summary>
/// 文件存储结果
/// </summary>
public class SaveFileResult
{
//保存文件名称
public string FileName { get; set; }
//绝对路径
public string FilePath { get; set; }
//相对路径
public string RelativePath { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Localization/GemStockpilesLocalizationConfigurer.cs
using Abp.Configuration.Startup;
using Abp.Localization.Dictionaries;
using Abp.Localization.Dictionaries.Xml;
using Abp.Reflection.Extensions;
namespace JFJT.GemStockpiles.Localization
{
public static class GemStockpilesLocalizationConfigurer
{
public static void Configure(ILocalizationConfiguration localizationConfiguration)
{
localizationConfiguration.Sources.Add(
new DictionaryBasedLocalizationSource(GemStockpilesConsts.LocalizationSourceName,
new XmlEmbeddedFileLocalizationDictionaryProvider(
typeof(GemStockpilesLocalizationConfigurer).GetAssembly(),
"JFJT.GemStockpiles.Localization.SourceFiles"
)
)
);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Enums/UserRoleTypeEnum.cs
using System;
namespace JFJT.GemStockpiles.Enums
{
/// <summary>
/// 注册用户角色类型
/// </summary>
public enum UserRoleTypeEnum
{
/// <summary>
/// 个人
/// </summary>
Person = 10,
/// <summary>
/// 商人
/// </summary>
Merchant = 20
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Commons/Dto/PagedResultRequestExtendDto.cs
using System;
using Abp.Application.Services.Dto;
namespace JFJT.GemStockpiles.Commons.Dto
{
/// <summary>
/// 分页结果请求扩展Dto
/// </summary>
public class PagedResultRequestExtendDto : PagedResultRequestDto
{
/// <summary>
/// 关键字
/// </summary>
public virtual string KeyWord { get; set; } = "";
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Enums/CategoryAttributeTypeEnum.cs
using System;
using System.ComponentModel;
namespace JFJT.GemStockpiles.Enums
{
/// <summary>
/// 产品属性类型
/// </summary>
public enum CategoryAttributeTypeEnum
{
/// <summary>
/// 文本框
/// </summary>
[Description("文本框")]
TextBox =10,
/// <summary>
/// 下拉框
/// </summary>
[Description("下拉框")]
DropDownList = 20,
/// <summary>
/// 单选框
/// </summary>
[Description("单选框")]
RadioButton = 30,
/// <summary>
/// 多选框
/// </summary>
[Description("多选框")]
CheckBox = 40,
/// <summary>
/// 文本域
/// </summary>
[Description("文本域")]
TextArea = 50
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.EntityFrameworkCore/EntityFrameworkCore/GemStockpilesDbContextFactory.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using JFJT.GemStockpiles.Configuration;
using JFJT.GemStockpiles.Web;
namespace JFJT.GemStockpiles.EntityFrameworkCore
{
/* This class is needed to run "dotnet ef ..." commands from command line on development. Not used anywhere else */
public class GemStockpilesDbContextFactory : IDesignTimeDbContextFactory<GemStockpilesDbContext>
{
public GemStockpilesDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<GemStockpilesDbContext>();
var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
GemStockpilesDbContextConfigurer.Configure(builder, configuration.GetConnectionString(GemStockpilesConsts.ConnectionStringName));
return new GemStockpilesDbContext(builder.Options);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Entities/CreateAudited.cs
using System;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
namespace JFJT.GemStockpiles.Entities
{
public class CreateAudited : CreateAudited<int>
{
}
public class CreateAudited<TPrimaryKey> : Entity<TPrimaryKey>, ICreationAudited
{
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Points/PointLogs/PointLogAppService.cs
using System;
using Abp.Domain.Repositories;
using AutoMapper;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Helpers;
using JFJT.GemStockpiles.Models.Points;
using JFJT.GemStockpiles.Points.PointLogs.Dto;
namespace JFJT.GemStockpiles.Points.PointLogs
{
public class PointLogAppService : GemStockpilesAppServiceBase
{
private readonly IRepository<PointLog, Guid> _pointLogRepository;
private readonly IRepository<PointRule, Guid> _pointRuleRepository;
public PointLogAppService(IRepository<PointLog, Guid> pointLogRepository, IRepository<PointRule, Guid> pointRuleRepository)
{
_pointLogRepository = pointLogRepository;
_pointRuleRepository = pointRuleRepository;
}
/// <summary>
/// 发放积分
/// </summary>
public async void SendPoints(PointLogDto input)
{
//获取积分规则
var pointRule = await _pointRuleRepository.FirstOrDefaultAsync(b => b.Name == input.ActionType);
if (pointRule == null)
{
return;
}
//获取规则默认描述
string defaultDesc = EnumHelper.GetEnumDescription(typeof(PointActionEnum), (int)pointRule.Name);
//对象映射
var pointLog = ObjectMapper.Map<PointLog>(input);
//默认值处理
pointLog.Points = pointRule.Point;
if (string.IsNullOrEmpty(pointLog.ActionDesc))
{
pointLog.ActionDesc = defaultDesc;
}
await _pointLogRepository.InsertAsync(pointLog);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/Categorys/Dto/CategoryCascaderDto.cs
using System;
using System.Collections.Generic;
namespace JFJT.GemStockpiles.Products.Categorys.Dto
{
public class CategoryCascaderDto
{
public Guid value { get; set; }
public string label { get; set; }
public List<CategoryCascaderDto> children { get; set; } = new List<CategoryCascaderDto>();
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Enums/ProductMediaTypeEnum.cs
using System;
namespace JFJT.GemStockpiles.Enums
{
/// <summary>
/// 媒体类型
/// </summary>
public enum MediaTypeEnum
{
/// <summary>
/// 图片
/// </summary>
Picture = 10,
/// <summary>
/// 视频
/// </summary>
Video = 20
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.EntityFrameworkCore/EntityFrameworkCore/GemStockpilesDbContext.cs
using Microsoft.EntityFrameworkCore;
using Abp.Zero.EntityFrameworkCore;
using JFJT.GemStockpiles.Authorization.Roles;
using JFJT.GemStockpiles.Authorization.Users;
using JFJT.GemStockpiles.MultiTenancy;
using JFJT.GemStockpiles.Models.Points;
using JFJT.GemStockpiles.Models.Products;
using JFJT.GemStockpiles.Models.Customers;
namespace JFJT.GemStockpiles.EntityFrameworkCore
{
public class GemStockpilesDbContext : AbpZeroDbContext<Tenant, Role, User, GemStockpilesDbContext>
{
public GemStockpilesDbContext(DbContextOptions<GemStockpilesDbContext> options)
: base(options)
{
}
/* Define a DbSet for each entity of the application */
public DbSet<Customer> Customer { get; set; }
public DbSet<CustomerCompany> CustomerCompany { get; set; }
public DbSet<CustomerCompanyLicense> CustomerCompanyLicense { get; set; }
public DbSet<PointRule> PointRule { get; set; }
public DbSet<PointRank> PointRank { get; set; }
public DbSet<PointLog> PointLog { get; set; }
public DbSet<Category> Category { get; set; }
public DbSet<CategoryAttribute> CategoryAttribute { get; set; }
public DbSet<CategoryAttributeItem> CategoryAttributeItem { get; set; }
public DbSet<Product> Product { get; set; }
public DbSet<ProductMedia> ProductMedia { get; set; }
public DbSet<ProductAttributeValue> ProductAttributeValue { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//设置该字段非必输项
modelBuilder.Entity<User>().Property(a => a.Surname).IsRequired(false);
modelBuilder.Entity<User>().Property(a => a.EmailAddress).IsRequired(false);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Roles/RoleAppService.cs
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Linq.Extensions;
using Abp.IdentityFramework;
using Abp.Domain.Repositories;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Roles.Dto;
using JFJT.GemStockpiles.Commons.Dto;
using JFJT.GemStockpiles.Authorization;
using JFJT.GemStockpiles.Authorization.Roles;
using JFJT.GemStockpiles.Authorization.Users;
namespace JFJT.GemStockpiles.Roles
{
[AbpAuthorize(PermissionNames.Pages_SystemManagement_Roles)]
public class RoleAppService : AsyncCrudAppService<Role, RoleDto, int, PagedResultRequestExtendDto, CreateRoleDto, RoleDto>, IRoleAppService
{
private readonly RoleManager _roleManager;
private readonly UserManager _userManager;
public RoleAppService(IRepository<Role> repository, RoleManager roleManager, UserManager userManager)
: base(repository)
{
_roleManager = roleManager;
_userManager = userManager;
}
/// <summary>
/// 添加角色
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_SystemManagement_Roles_Create)]
public override async Task<RoleDto> Create(CreateRoleDto input)
{
CheckCreatePermission();
var role = ObjectMapper.Map<Role>(input);
role.SetNormalizedName();
CheckErrors(await _roleManager.CreateAsync(role));
var grantedPermissions = PermissionManager
.GetAllPermissions()
.Where(p => input.Permissions.Contains(p.Name))
.ToList();
await _roleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
return MapToEntityDto(role);
}
/// <summary>
/// 修改角色
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_SystemManagement_Roles_Edit)]
public override async Task<RoleDto> Update(RoleDto input)
{
CheckUpdatePermission();
var role = await _roleManager.GetRoleByIdAsync(input.Id);
ObjectMapper.Map(input, role);
CheckErrors(await _roleManager.UpdateAsync(role));
var grantedPermissions = PermissionManager
.GetAllPermissions()
.Where(p => input.Permissions.Contains(p.Name))
.ToList();
await _roleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
return MapToEntityDto(role);
}
/// <summary>
/// 删除角色
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_SystemManagement_Roles_Delete)]
public override async Task Delete(EntityDto<int> input)
{
CheckDeletePermission();
var role = await _roleManager.FindByIdAsync(input.Id.ToString());
var users = await _userManager.GetUsersInRoleAsync(role.NormalizedName);
foreach (var user in users)
{
CheckErrors(await _userManager.RemoveFromRoleAsync(user, role.NormalizedName));
}
CheckErrors(await _roleManager.DeleteAsync(role));
}
/// <summary>
/// 根据ID获取编辑角色信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<RoleDto> GetRoleForEdit(int id)
{
var role = await _roleManager.GetRoleByIdAsync(id);
//获取有效权限项
var grantedPermissions = (await _roleManager.GetGrantedPermissionsAsync(role)).ToArray();
RoleDto editRoleDto = ObjectMapper.Map<RoleDto>(role);
//更新实体权限
editRoleDto.Permissions = grantedPermissions.Select(t => t.Name).ToList();
return editRoleDto;
}
/// <summary>
/// 获取权限列表数据
/// </summary>
/// <returns></returns>
public Task<ListResultDto<PermissionDto>> GetAllPermissions()
{
var permissions = PermissionManager.GetAllPermissions();
return Task.FromResult(new ListResultDto<PermissionDto>(
ObjectMapper.Map<List<PermissionDto>>(permissions)
));
}
/// <summary>
/// 获取权限树形结构数据
/// </summary>
/// <returns></returns>
public Task<ListResultDto<PermissionTreeDto>> GetTreePermissions()
{
List<PermissionTreeDto> treeList = new List<PermissionTreeDto>();
var permissions = PermissionManager.GetAllPermissions();
//
var treeData = new ListResultDto<FlatPermissionDto>(ObjectMapper.Map<List<FlatPermissionDto>>(permissions));
if (treeData != null)
{
treeList = GetPermissionTreeStruct(treeData, null, 0);
}
return Task.FromResult(new ListResultDto<PermissionTreeDto>(ObjectMapper.Map<List<PermissionTreeDto>>(treeList)));
}
/// <summary>
/// 递归生成权限树形结构数据
/// </summary>
/// <param name="permissionData"></param>
/// <param name="parentName"></param>
/// <param name="parentLevel"></param>
/// <returns></returns>
protected List<PermissionTreeDto> GetPermissionTreeStruct(ListResultDto<FlatPermissionDto> permissionData, string parentName, int parentLevel)
{
List<PermissionTreeDto> treeList = new List<PermissionTreeDto>();
var level = parentLevel + 1;
var treeData = permissionData.Items.Where(b => b.ParentName == parentName).ToList();
foreach (var item in treeData)
{
var children = GetPermissionTreeStruct(permissionData, item.Name, level);
var model = new PermissionTreeDto() { title = item.DisplayName, name = item.Name, level = level };
model.children = children.Count <= 0 ? null : children;
model.expand = level <= 2 ? true : false;
treeList.Add(model);
}
return treeList;
}
/// <summary>
/// 根据ID获取Entity模型
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
protected override async Task<Role> GetEntityByIdAsync(int id)
{
return await Repository.GetAllIncluding(x => x.Permissions).FirstOrDefaultAsync(x => x.Id == id);
}
/// <summary>
/// GetAll查询过滤条件
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
protected override IQueryable<Role> CreateFilteredQuery(PagedResultRequestExtendDto input)
{
return Repository.GetAllIncluding(x => x.Permissions).WhereIf(!input.KeyWord.IsNullOrWhiteSpace(), x => x.Name.Contains(input.KeyWord) || x.DisplayName.Contains(input.KeyWord));
}
/// <summary>
/// GetAll查询排序条件
/// </summary>
/// <param name="query"></param>
/// <param name="input"></param>
/// <returns></returns>
protected override IQueryable<Role> ApplySorting(IQueryable<Role> query, PagedResultRequestExtendDto input)
{
return query.OrderBy(r => r.DisplayName);
}
/// <summary>
/// 异常描述本地化转换函数
/// </summary>
/// <param name="identityResult"></param>
protected virtual void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/CategoryAttributes/Dto/CategoryAttributeDto.cs
using System;
using System.Collections.Generic;
using Abp.AutoMapper;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Models.Products;
namespace JFJT.GemStockpiles.Products.CategoryAttributes.Dto
{
[AutoMap(typeof(CategoryAttribute))]
public class CategoryAttributeDto : EntityDto<Guid>
{
/// <summary>
/// 类型名称
/// </summary>
public string CategoryName { get; set; }
/// <summary>
/// 类型名称层级路径
/// </summary>
public List<string> CategoryNamePath { get; set; } = new List<string>();
/// <summary>
/// 类型ID
/// </summary>
public Guid CategoryId { get; set; }
/// <summary>
/// 类型ID层级路径
/// </summary>
public List<string> CategoryIdPath { get; set; } = new List<string>();
/// <summary>
/// 属性名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 分类属性类型
/// </summary>
public CategoryAttributeTypeEnum Type { get; set; } = CategoryAttributeTypeEnum.TextBox;
/// <summary>
/// 是否必须
/// </summary>
public bool Required { get; set; } = false;
/// <summary>
/// 排序
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 属性可选值列表
/// </summary>
public virtual List<CategoryAttributeItem> Items { get; set; } = new List<CategoryAttributeItem>();
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Points/PointRules/Dto/PointRuleDto.cs
using System;
using Abp.AutoMapper;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Models.Points;
namespace JFJT.GemStockpiles.Points.PointRules.Dto
{
/// <summary>
/// 积分规则DTO
/// </summary>
[AutoMap(typeof(PointRule))]
public class PointRuleDto : EntityDto<Guid>
{
/// <summary>
/// 名称
/// </summary>
public PointActionEnum Name { get; set; } = PointActionEnum.Upload;
/// <summary>
/// 奖励分值
/// </summary>
public int Point { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
/// <summary>
/// 是否活动兑换
/// </summary>
public bool IsActivity { get; set; } = false;
/// <summary>
/// 是否兑换商品
/// </summary>
public bool IsCommodity { get; set; } = false;
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Products/ProductAttributeValue.cs
using System;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Products
{
/// <summary>
/// 产品属性值表
/// </summary>
public class ProductAttributeValue : CreateAudited
{
/// <summary>
/// 产品ID
/// </summary>
public Guid ProductId { get; set; }
/// <summary>
/// 属性名称
/// </summary>
public int AttributeName { get; set; }
/// <summary>
/// 属性值
/// </summary>
public string AttributeValue { get; set; }
/// <summary>
/// 排序
/// </summary>
public int Sort { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Products/Category.cs
using System;
using System.Collections.Generic;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Products
{
/// <summary>
/// 产品分类表
/// </summary>
public class Category : FullAudited<Guid>
{
/// <summary>
/// 分类名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 父级ID
/// </summary>
public Guid? ParentId { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
/// <summary>
/// 排序
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 分类属性列表
/// </summary>
public virtual List<CategoryAttribute> Items { get; set; } = new List<CategoryAttribute>();
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/CategoryAttributeItems/Dto/CategoryAttributeItemDto.cs
using System;
using System.ComponentModel.DataAnnotations;
using Abp.AutoMapper;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Models.Products;
namespace JFJT.GemStockpiles.Products.CategoryAttributeItems.Dto
{
[AutoMap(typeof(CategoryAttributeItem))]
public class CategoryAttributeItemDto : EntityDto<Guid>
{
/// <summary>
/// 属性ID
/// </summary>
[Required]
public Guid CategoryAttributeId { get; set; }
/// <summary>
/// 属性值
/// </summary>
[Required]
public string Value { get; set; }
/// <summary>
/// 排序
/// </summary>
[Required]
public int Sort { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Enums/PointActionEnum.cs
using System;
using System.ComponentModel;
namespace JFJT.GemStockpiles.Enums
{
/// <summary>
/// 积分动作
/// </summary>
public enum PointActionEnum
{
/// <summary>
/// 上传商品
/// </summary>
[Description("上传商品")]
Upload = 10,
/// <summary>
/// 购买商品
/// </summary>
[Description("购买商品")]
Buy = 20,
/// <summary>
/// 注册
/// </summary>
[Description("注册")]
Register = 30,
/// <summary>
/// 推荐
/// </summary>
[Description("推荐")]
Recommend = 40
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.EntityFrameworkCore/EntityFrameworkCore/GemStockpilesDbContextConfigurer.cs
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
namespace JFJT.GemStockpiles.EntityFrameworkCore
{
public static class GemStockpilesDbContextConfigurer
{
public static void Configure(DbContextOptionsBuilder<GemStockpilesDbContext> builder, string connectionString)
{
builder.UseSqlServer(connectionString);
}
public static void Configure(DbContextOptionsBuilder<GemStockpilesDbContext> builder, DbConnection connection)
{
builder.UseSqlServer(connection);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/Categorys/Dto/CategoryDto.cs
using System;
using System.Collections.Generic;
using Abp.AutoMapper;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Models.Products;
namespace JFJT.GemStockpiles.Products.Categorys.Dto
{
[AutoMap(typeof(Category))]
public class CategoryDto : EntityDto<Guid>
{
/// <summary>
/// 分类名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 父级ID
/// </summary>
public Guid? ParentId { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
/// <summary>
/// 排序
/// </summary>
public int Sort { get; set; }
}
}
<file_sep>/vue/src/store/modules/admin/user.js
import Ajax from '@/libs/ajax';
const user = {
namespaced: true,
state: {
totalCount: 0,
currentPage: 1,
pageSize: 10,
list: [],
loading: false,
editUserId: 0,
roles: []
},
mutations: {
setCurrentPage(state, page) {
state.currentPage = page;
},
setPageSize(state, pageSize) {
state.pageSize = pageSize;
},
edit(state, id) {
state.editUserId = id;
}
},
actions: {
async getAll(context, payload) {
context.state.loading = true;
let response = await Ajax.get('/api/services/app/User/GetAll', {params: payload.data});
context.state.loading = false;
let page = response.data.result;
context.state.totalCount = page.totalCount;
context.state.list = page.items;
},
async getRoles(context) {
let response = await Ajax.get('/api/services/app/User/GetRoles');
context.state.roles = response.data.result.items;
},
async get(context, payload) {
return await Ajax.get('/api/services/app/User/Get?Id=' + payload.id);
},
async create(context, payload) {
return await Ajax.post('/api/services/app/User/Create', payload.data);
},
async update(context, payload) {
return await Ajax.put('/api/services/app/User/Update', payload.data);
},
async delete(context, payload) {
return await Ajax.delete('/api/services/app/User/Delete?Id=' + payload.data.id);
},
async changeLanguage(context, payload) {
return await Ajax.post('/api/services/app/User/ChangeLanguage', payload.data);
}
}
};
export default user;
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Points/PointRules/PointRuleAppService.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
using Abp.UI;
using Abp.Authorization;
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using Abp.IdentityFramework;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Helpers;
using JFJT.GemStockpiles.Authorization;
using JFJT.GemStockpiles.Models.Points;
using JFJT.GemStockpiles.Commons.Dto;
using JFJT.GemStockpiles.Points.PointRules.Dto;
namespace JFJT.GemStockpiles.Points.PointRules
{
[AbpAuthorize(PermissionNames.Pages_PointManagement_PointRules)]
public class PointRuleAppService : AsyncCrudAppService<PointRule, PointRuleDto, Guid, PagedResultRequestDto, PointRuleDto, PointRuleDto>, IPointRuleAppService
{
private readonly IRepository<PointRule, Guid> _pointRuleRepository;
public PointRuleAppService(IRepository<PointRule, Guid> pointRuleRepository)
: base(pointRuleRepository)
{
_pointRuleRepository = pointRuleRepository;
}
/// <summary>
/// 添加积分方案
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_PointManagement_PointRules_Create)]
public override async Task<PointRuleDto> Create(PointRuleDto input)
{
CheckCreatePermission();
CheckErrors(await CheckActionNameAsync(input.Id, input.Name));
var entity = ObjectMapper.Map<PointRule>(input);
entity = await _pointRuleRepository.InsertAsync(entity);
return MapToEntityDto(entity);
}
/// <summary>
/// 修改积分方案
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_PointManagement_PointRules_Edit)]
public override async Task<PointRuleDto> Update(PointRuleDto input)
{
CheckUpdatePermission();
var entity = await _pointRuleRepository.GetAsync(input.Id);
if (entity == null)
throw new EntityNotFoundException(typeof(PointRule), input.Id);
CheckErrors(await CheckActionNameAsync(input.Id, input.Name));
MapToEntity(input, entity);
entity = await _pointRuleRepository.UpdateAsync(entity);
return MapToEntityDto(entity);
}
/// <summary>
/// 删除积分方案
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_PointManagement_PointRules_Delete)]
public override async Task Delete(EntityDto<Guid> input)
{
CheckDeletePermission();
var entity = await _pointRuleRepository.GetAsync(input.Id);
if (entity == null)
throw new EntityNotFoundException(typeof(PointRank), input.Id);
await _pointRuleRepository.DeleteAsync(entity);
}
/// <summary>
/// 获取积分动作列表
/// </summary>
/// <returns></returns>
public Task<ListResultDto<IdAndNameDto>> GetAllPointActions()
{
List<IdAndNameDto> actions = new List<IdAndNameDto>();
foreach (PointActionEnum item in Enum.GetValues(typeof(PointActionEnum)))
{
string desc = EnumHelper.GetEnumDescription(typeof(PointActionEnum), (int)item);
actions.Add(new IdAndNameDto() { Id = (int)item, Name = desc });
}
return Task.FromResult(new ListResultDto<IdAndNameDto>(
ObjectMapper.Map<List<IdAndNameDto>>(actions)
));
}
/// <summary>
/// Dto模型映射
/// </summary>
/// <param name="input"></param>
/// <param name="pointRule"></param>
protected override void MapToEntity(PointRuleDto input, PointRule pointRule)
{
ObjectMapper.Map(input, pointRule);
}
/// <summary>
/// 根据ID获取Entity模型
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
protected override async Task<PointRule> GetEntityByIdAsync(Guid id)
{
var entity = await Repository.FirstOrDefaultAsync(x => x.Id == id);
if (entity == null)
{
throw new EntityNotFoundException(typeof(PointRank), id);
}
return entity;
}
/// <summary>
/// GetAll查询排序条件
/// </summary>
/// <param name="query"></param>
/// <param name="input"></param>
/// <returns></returns>
protected override IQueryable<PointRule> ApplySorting(IQueryable<PointRule> query, PagedResultRequestDto input)
{
return query.OrderBy(r => r.Name);
}
/// <summary>
/// 检测积分方案名称是否已存在
/// </summary>
/// <param name="expectedId"></param>
/// <param name="name"></param>
/// <returns></returns>
protected async Task<IdentityResult> CheckActionNameAsync(Guid? expectedId, PointActionEnum name)
{
var entity = await _pointRuleRepository.FirstOrDefaultAsync(b => b.Name == name);
if (entity != null && entity.Id != expectedId)
{
throw new UserFriendlyException("积分方案已存在");
}
return IdentityResult.Success;
}
/// <summary>
/// 异常描述本地化转换函数
/// </summary>
/// <param name="identityResult"></param>
protected virtual void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Enums/ProductAuditStateEnum.cs
using System;
namespace JFJT.GemStockpiles.Enums
{
/// <summary>
/// 产品审核状态
/// </summary>
public enum ProductAuditStateEnum
{
/// <summary>
/// 编辑待提交
/// </summary>
Editing = 10,
/// <summary>
/// 审核中
/// </summary>
Submitted = 20,
/// <summary>
/// 审核不通过
/// </summary>
Rejected = 30,
/// <summary>
/// 审核通过
/// </summary>
Approved = 40
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Helpers/EnumHelper.cs
using System;
using System.Reflection;
using System.ComponentModel;
namespace JFJT.GemStockpiles.Helpers
{
public static class EnumHelper
{
/// <summary>
/// 获取枚举变量的描述信息
/// </summary>
/// <param name="e"></param>
/// <param name="value"></param>
/// <returns></returns>
public static string GetEnumDescription(this Type e, int? value)
{
FieldInfo[] fields = e.GetFields();
for (int i = 1, count = fields.Length; i < count; i++)
{
if ((int)System.Enum.Parse(e, fields[i].Name) == value)
{
DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])fields[i].
GetCustomAttributes(typeof(DescriptionAttribute), false);
if (EnumAttributes.Length > 0)
{
return EnumAttributes[0].Description;
}
}
}
return "没有描述信息";
}
}
}<file_sep>/vue/src/main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import iView from 'iview';
import App from './app';
import {router} from './router/index';
import {appRouter} from './router/router';
import store from './store/index';
import VueWechatTitle from 'vue-wechat-title';
import Ajax from '@/libs/ajax';
import Util from '@/libs/util';
import appConfig from '@/libs/appConfig';
import 'iview/dist/styles/iview.css';
Vue.use(iView);
Vue.use(VueWechatTitle);
// 将Ajax挂载到prototype上,在组件中可以直接使用this.$Ajax访问
Vue.prototype.$Ajax = Ajax;
// 增加全局语言国际化函数
Vue.prototype.L = function (value,source,...argus) {
if(source) {
return window.abp.localization.localize(value,source,argus);
}
else {
return window.abp.localization.localize(value,appConfig.localization.defaultLocalizationSourceName,argus);
}
}
Vue.config.productionTip = false;
/* eslint-disable no-new */
Ajax.get('/AbpUserConfiguration/GetAll').then(data=>{
Util.abp = Util.extend(true, Util.abp, data.data.result);
new Vue({
router,
store,
render: h => h(App),
mounted () {
this.currentPageName = this.$route.name;
this.$store.dispatch({
type: 'session/init'
});
this.$store.commit('app/setOpenedList');
this.$store.commit('app/initCachepage');
this.$store.commit('app/updateMenulist');
},
created () {
let tagsList = [];
appRouter.map((item) => {
if (item.children.length <= 1) {
tagsList.push(item.children[0]);
}
else {
tagsList.push(...item.children);
}
});
this.$store.commit('app/setTagsList', tagsList);
}
}).$mount('#app');
});
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Users/Dto/ChangePasswordDto.cs
using System.ComponentModel.DataAnnotations;
using Abp.AutoMapper;
using Abp.Authorization.Users;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Authorization.Users;
namespace JFJT.GemStockpiles.Users.Dto
{
[AutoMapFrom(typeof(User))]
public class ChangePasswordDto : EntityDto<long>
{
[Required]
[StringLength(AbpUserBase.MaxPlainPasswordLength)]
public string OldPassword { get; set; }
[Required]
[StringLength(AbpUserBase.MaxPlainPasswordLength)]
public string NewPassword { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Entities/FullAudited.cs
using System;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
namespace JFJT.GemStockpiles.Entities
{
#region ABP基类说明
/*
IAudited : ICreationAudited, IModificationAudited 自动记录创建修改人时间信息 可直接继承 IAudited
IDeletionAudited : ISoftDelete 逻辑删除,继承IDeletionAudited ABP自动会过滤删除掉的数据
IFullAudited : IAudited, IDeletionAudited 继承 IFullAudited 可包含修改创建 删除
*/
#endregion
public class FullAudited : FullAudited<int>
{
}
public class FullAudited<TPrimaryKey> : Entity<TPrimaryKey>, ICreationAudited, IModificationAudited, IDeletionAudited
{
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
public bool IsDeleted { get; set; }
public long? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Points/PointRanks/Dto/PointRankDto.cs
using System;
using System.ComponentModel.DataAnnotations;
using Abp.AutoMapper;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Models.Points;
namespace JFJT.GemStockpiles.Points.PointRanks.Dto
{
/// <summary>
/// 积分等级DTO
/// </summary>
[AutoMap(typeof(PointRank))]
public class PointRankDto : EntityDto<Guid>
{
/// <summary>
/// 等级名称
/// </summary>
[Required]
[MaxLength(16, ErrorMessage = "最多输入16个字符")]
public string Name { get; set; }
/// <summary>
/// 等级头像
/// </summary>
public string Avatar { get; set; }
/// <summary>
/// 该等级的最小积分
/// </summary>
[Required]
[Range(1, 99999999, ErrorMessage = "最小积分必须是1~99999999之间的整数")]
public int MinPoint { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/GemStockpilesConsts.cs
namespace JFJT.GemStockpiles
{
public class GemStockpilesConsts
{
public const string LocalizationSourceName = "GemStockpiles";
public const string ConnectionStringName = "Default";
public const bool MultiTenancyEnabled = true;
}
}
<file_sep>/vue/src/router/index.js
import Vue from 'vue';
import iView from 'iview';
import VueRouter from 'vue-router';
import store from '../store/index';
import {routers,appRouter,otherRouter} from './router';
import Util from '../libs/util';
Vue.use(VueRouter);
// 路由配置
const RouterConfig = {
mode: 'history',
routes: routers
};
export const router = new VueRouter(RouterConfig);
router.beforeEach((to, from, next) => {
iView.LoadingBar.start();
if (!Util.abp.session.userId && to.name !== 'login') {
next({
name: 'login'
});
}
else if (!!Util.abp.session.userId && to.name === 'login') {
next({
name: 'home'
});
}
else {
const curRouterObj = Util.getRouterObjByName([otherRouter, ...appRouter], to.name);
if (curRouterObj && curRouterObj.permission) {
if (window.abp.auth.hasPermission(curRouterObj.permission)) {
Util.toDefaultPage([otherRouter, ...appRouter], to.name, router, next);
}
else {
next({
replace: true,
name: 'error-403'
});
}
}
else {
Util.toDefaultPage([...routers], to.name, router, next);
}
}
});
router.afterEach((to) => {
Util.openNewPage(router.app, to.name, to.params, to.query);
iView.LoadingBar.finish();
window.scrollTo(0, 0);
});<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Entities/ModifyDeleteAudited.cs
using System;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
namespace JFJT.GemStockpiles.Entities
{
public class ModifyDeleteAudited : ModifyDeleteAudited<int>
{
}
public class ModifyDeleteAudited<TPrimaryKey> : Entity<TPrimaryKey>, IModificationAudited, IDeletionAudited
{
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
public bool IsDeleted { get; set; }
public long? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/CategoryAttributes/CategoryAttributeAppService.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
using Abp.UI;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Linq.Extensions;
using Abp.IdentityFramework;
using Abp.Domain.Repositories;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Helpers;
using JFJT.GemStockpiles.Commons.Dto;
using JFJT.GemStockpiles.Authorization;
using JFJT.GemStockpiles.Models.Products;
using JFJT.GemStockpiles.Products.Categorys.Dto;
using JFJT.GemStockpiles.Products.CategoryAttributes.Dto;
using Microsoft.EntityFrameworkCore;
using Abp.Domain.Entities;
namespace JFJT.GemStockpiles.Products.CategoryAttributes
{
[AbpAuthorize(PermissionNames.Pages_ProductManagement_CategoryAttributes)]
public class CategoryAttributeAppService : AsyncCrudAppService<CategoryAttribute, CategoryAttributeDto, Guid, PagedResultRequestExtendDto, CategoryAttributeDto, CategoryAttributeDto>, ICategoryAttributeAppService
{
private readonly IRepository<Category, Guid> _categoryRepository;
private readonly IRepository<CategoryAttribute, Guid> _categoryAttributRepository;
private readonly IRepository<CategoryAttributeItem, Guid> _categoryAttributeItemRepository;
public CategoryAttributeAppService(
IRepository<CategoryAttribute, Guid> categoryAttributRepository,
IRepository<Category, Guid> categoryRepository,
IRepository<CategoryAttributeItem, Guid> categoryAttributeItemRepository)
: base(categoryAttributRepository)
{
_categoryAttributRepository = categoryAttributRepository;
_categoryRepository = categoryRepository;
_categoryAttributeItemRepository = categoryAttributeItemRepository;
}
/// <summary>
/// 添加分类属性
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_ProductManagement_CategoryAttributes_Create)]
public override async Task<CategoryAttributeDto> Create(CategoryAttributeDto input)
{
CheckCreatePermission();
CheckErrors(await CheckNameOrSortAsync(input.Id, input.CategoryId, input.Name, input.Sort));
var entity = ObjectMapper.Map<CategoryAttribute>(input);
entity = await _categoryAttributRepository.InsertAsync(entity);
return MapToEntityDto(entity);
}
/// <summary>
/// 修改分类属性
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_ProductManagement_CategoryAttributes_Edit)]
public override async Task<CategoryAttributeDto> Update(CategoryAttributeDto input)
{
CheckUpdatePermission();
var entity = await _categoryAttributRepository.GetAsync(input.Id);
if (entity == null)
throw new EntityNotFoundException(typeof(CategoryAttribute), input.Id);
CheckErrors(await CheckNameOrSortAsync(input.Id, input.CategoryId, input.Name, input.Sort));
MapToEntity(input, entity);
entity = await _categoryAttributRepository.UpdateAsync(entity);
return MapToEntityDto(entity);
}
/// <summary>
/// 删除分类属性
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_ProductManagement_CategoryAttributes_Delete)]
public override async Task Delete(EntityDto<Guid> input)
{
CheckDeletePermission();
var entity = await _categoryAttributRepository.GetAsync(input.Id);
if (entity == null)
throw new EntityNotFoundException(typeof(CategoryAttribute), input.Id);
await _categoryAttributRepository.DeleteAsync(entity);
//删除属性值
await _categoryAttributeItemRepository.DeleteAsync(t => t.CategoryAttributeId == input.Id);
}
/// <summary>
/// 根据ID获取编辑属性信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<CategoryAttributeDto> GetAttributeForEdit(Guid id)
{
var entity = await _categoryAttributRepository.FirstOrDefaultAsync(id);
if (entity == null)
throw new EntityNotFoundException(typeof(CategoryAttribute), id);
CategoryAttributeDto editAttributeDto = ObjectMapper.Map<CategoryAttributeDto>(entity);
//获取分类数据
var categoryData = _categoryRepository.GetAll().ToList();
//设置属性分类信息
var model = HandleCategoryInfo(categoryData, new CategoryAttributeDto() { CategoryId = entity.CategoryId });
editAttributeDto.CategoryName = categoryData.Find(t => t.Id == entity.CategoryId)?.Name;
editAttributeDto.CategoryNamePath = model.CategoryNamePath;
editAttributeDto.CategoryIdPath = model.CategoryIdPath;
return editAttributeDto;
}
/// <summary>
/// 获取属性类型列表
/// </summary>
/// <returns></returns>
public Task<ListResultDto<IdAndNameDto>> GetAllAttributeTypes()
{
List<IdAndNameDto> attributeTypes = new List<IdAndNameDto>();
foreach (CategoryAttributeTypeEnum item in Enum.GetValues(typeof(CategoryAttributeTypeEnum)))
{
string desc = EnumHelper.GetEnumDescription(typeof(CategoryAttributeTypeEnum), (int)item);
attributeTypes.Add(new IdAndNameDto() { Id = (int)item, Name = desc });
}
return Task.FromResult(new ListResultDto<IdAndNameDto>(
ObjectMapper.Map<List<IdAndNameDto>>(attributeTypes)
));
}
/// <summary>
/// 获取分类树形结构数据
/// </summary>
/// <returns></returns>
public Task<ListResultDto<CategoryCascaderDto>> GetAllAttr()
{
List<CategoryCascaderDto> listData = new List<CategoryCascaderDto>();
var entity = _categoryAttributRepository.GetAllList();
if (entity != null && entity.Count > 0)
{
foreach (var item in entity)
{
var model = new CategoryCascaderDto() { label = item.Name, value = item.Id };
listData.Add(model);
}
}
return Task.FromResult(new ListResultDto<CategoryCascaderDto>(
ObjectMapper.Map<List<CategoryCascaderDto>>(listData)
));
}
/// <summary>
/// 根据分类ID获取属性列表
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public Task<ListResultDto<CategoryAttributeDto>> GetAttr(Guid Id)
{
var entity = _categoryAttributRepository.GetAllList().Where(a => a.CategoryId == Id);
return Task.FromResult(new ListResultDto<CategoryAttributeDto>(
ObjectMapper.Map<List<CategoryAttributeDto>>(entity)
));
}
/// <summary>
/// 重写基类的GetAll方法, 以处理属性分类名称、层级信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public override async Task<PagedResultDto<CategoryAttributeDto>> GetAll(PagedResultRequestExtendDto input)
{
PagedResultDto<CategoryAttributeDto> query = await base.GetAll(input);
var categoryData = _categoryRepository.GetAll().ToList();
//分类名称、层级信息处理
if (query.TotalCount > 0)
{
query.Items.ToList().ForEach(x =>
{
var model = HandleCategoryInfo(categoryData, new CategoryAttributeDto() { CategoryId = x.CategoryId });
x.CategoryName = categoryData.Find(t => t.Id == x.CategoryId)?.Name;
x.CategoryNamePath = model.CategoryNamePath;
x.CategoryIdPath = model.CategoryIdPath;
});
}
return query;
}
/// <summary>
/// 处理属性分类层级信息
/// </summary>
/// <param name="categoryData"></param>
/// <param name="model"></param>
/// <returns></returns>
protected CategoryAttributeDto HandleCategoryInfo(List<Category> categoryData, CategoryAttributeDto model)
{
var category = categoryData.Find(t => t.Id == model.CategoryId);
if (category != null)
{
if (category.ParentId != null)
{
model.CategoryId = (Guid)category.ParentId;
HandleCategoryInfo(categoryData, model);
}
model.CategoryIdPath.Add(category.Id.ToString());
model.CategoryNamePath.Add(category.Name);
}
return model;
}
/// <summary>
/// Dto模型映射
/// </summary>
/// <param name="input"></param>
/// <param name="pointRank"></param>
protected override void MapToEntity(CategoryAttributeDto input, CategoryAttribute categoryAttribute)
{
ObjectMapper.Map(input, categoryAttribute);
}
/// <summary>
/// GetAll查询过滤条件
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
protected override IQueryable<CategoryAttribute> CreateFilteredQuery(PagedResultRequestExtendDto input)
{
return Repository.GetAll().WhereIf(!input.KeyWord.IsNullOrWhiteSpace(), x => x.CategoryId.Equals(Guid.Parse(input.KeyWord)));
}
/// <summary>
/// GetAll查询排序条件
/// </summary>
/// <param name="query"></param>
/// <param name="input"></param>
/// <returns></returns>
protected override IQueryable<CategoryAttribute> ApplySorting(IQueryable<CategoryAttribute> query, PagedResultRequestExtendDto input)
{
return query.OrderBy(r => r.CategoryId).ThenBy(r => r.Sort);
}
/// <summary>
/// 检测分类属性名称或属性排序值是否已存在
/// </summary>
/// <param name="expectedId"></param>
/// <param name="categoryId"></param>
/// <param name="name"></param>
/// <param name="sort"></param>
/// <returns></returns>
protected async Task<IdentityResult> CheckNameOrSortAsync(Guid? expectedId, Guid categoryId, string name, int sort)
{
var entity = await _categoryAttributRepository.FirstOrDefaultAsync(b => b.CategoryId == categoryId && b.Name == name);
if (entity != null && entity.Id != expectedId)
{
throw new UserFriendlyException("属性名称已存在");
}
entity = await _categoryAttributRepository.FirstOrDefaultAsync(b => b.CategoryId == categoryId && b.Sort == sort);
if (entity != null && entity.Id != expectedId)
{
throw new UserFriendlyException("排序值已存在");
}
return IdentityResult.Success;
}
/// <summary>
/// 异常描述本地化转换函数
/// </summary>
/// <param name="identityResult"></param>
protected virtual void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Commons/CommonAppService.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Abp.UI;
using Abp.Localization;
using Abp.Authorization;
using Abp.Runtime.Session;
using JFJT.GemStockpiles.Helpers;
using JFJT.GemStockpiles.Users.Dto;
using JFJT.GemStockpiles.Commons.Dto;
using JFJT.GemStockpiles.Models.Configs;
using JFJT.GemStockpiles.Authorization.Users;
namespace JFJT.GemStockpiles.Commons
{
/// <summary>
/// 存放公共的API接口(登录后调用)
/// </summary>
[AbpAuthorize]
public class CommonAppService : GemStockpilesAppServiceBase, ICommonAppService
{
private readonly IOptions<AppSettings> _appSettings;
private readonly UploadHelper uploadHelper;
public CommonAppService(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings;
uploadHelper = new UploadHelper(appSettings);
}
/// <summary>
/// 系统用户语言切换
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task ChangeLanguage(ChangeUserLanguageDto input)
{
await SettingManager.ChangeSettingForUserAsync(
AbpSession.ToUserIdentifier(),
LocalizationSettingNames.DefaultLanguage,
input.LanguageName
);
}
/// <summary>
/// 系统用户密码修改
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task ChangePassword(ChangePasswordDto input)
{
var user = await UserManager.GetUserByIdAsync(input.Id);
CheckErrors(await UserManager.ChangePasswordAsync(user, input.OldPassword, input.NewPassword));
}
/// <summary>
/// 系统用户个人信息修改
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<UserDto> UpdateUserInfo(ChangeUserInfoDto input)
{
var user = await UserManager.GetUserByIdAsync(input.Id);
user.Name = input.Name;
CheckErrors(await UserManager.UpdateAsync(user));
return ObjectMapper.Map<UserDto>(user);
}
/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
public async Task<UploadFileResultDto> UploadFile(IFormFile file, int uploadType, int fileType)
{
//枚举值转换
UploadType eUploadType = (UploadType)Enum.ToObject(typeof(UploadType), uploadType);
FileType eFileType = (FileType)Enum.ToObject(typeof(FileType), fileType);
var validate = uploadHelper.Validate(file, eUploadType, eFileType, out string error);
if (!validate)
{
throw new UserFriendlyException("上传失败", error);
}
//获取文件保存信息
var saveResult = await uploadHelper.SaveFile(file, AbpSession.UserId);
return new UploadFileResultDto { FileName = saveResult.FileName, FilePath = saveResult.RelativePath };
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Commons/Dto/UploadFileResultDto.cs
using System;
namespace JFJT.GemStockpiles.Commons.Dto
{
public class UploadFileResultDto
{
public string FileName { get; set; }
public string FilePath { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Points/PointRank.cs
using System;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Points
{
/// <summary>
/// 积分等级
/// </summary>
public class PointRank : CreateModifyAudited<Guid>
{
/// <summary>
/// 等级名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 等级头像
/// </summary>
public string Avatar { get; set; }
/// <summary>
/// 该等级的最小积分
/// </summary>
public int MinPoint { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
}
}
<file_sep>/vue/src/libs/ajax.js
import Vue from 'vue';
import axios from 'axios';
import appConfig from './appConfig';
import sweetAlert from "./sweetAlert";
// 创建axios实例
const ajax = axios.create({
baseURL: appConfig.remoteServiceBaseUrl,
timeout: 15000
});
// 请求拦截器
ajax.interceptors.request.use(function (config) {
if(!!window.abp.auth.getToken()) {
config.headers.common["Authorization"] = "Bearer " + window.abp.auth.getToken();
}
config.headers.common[".AspNetCore.Culture"] = window.abp.utils.getCookieValue("Abp.Localization.CultureName");
config.headers.common["Abp.TenantId"] = window.abp.multiTenancy.getTenantIdCookie();
return config;
},function (error) {
return Promise.reject(error);
});
let vm = new Vue({});
// 添加一个响应拦截器
ajax.interceptors.response.use((response)=>{
return response;
},(error)=>{
if(error.response&&error.response.status==404) {
sweetAlert.error('404-Not found', '您请求的资源不存在!');
}
else if(error.response&&error.response.status==403) {
sweetAlert.error('403-Forbidden', '您没有权限进行此操作!');
}
else if(!!error.response&&!!error.response.data.error&&!!error.response.data.error.message&&error.response.data.error.details) {
sweetAlert.error(error.response.data.error.message, error.response.data.error.details);
}
else if(!!error.response&&!!error.response.data.error&&!!error.response.data.error.message) {
sweetAlert.error('', error.response.data.error.message);
}
else if(!error.response) {
sweetAlert.error('', 'UnknownError');
}
// 关闭消息框
setTimeout(()=>{vm.$Message.destroy();}, 1000);
return Promise.reject(error);
});
export default ajax;<file_sep>/vue/src/store/modules/product/product.js
import Ajax from '@/libs/ajax';
const product={
namespaced: true,
state: {
totalCount: 0,
currentPage: 1,
pageSize: 10,
list: [],
loading: false,
editUser: null,
roles: []
},
mutations: {
setCurrentPage(state, page) {
state.currentPage = page;
},
setPageSize(state, pageSize) {
state.pageSize = pageSize;
},
edit(state, user) {
state.editUser = user;
}
},
actions: {
async getAll(context, payload) {
context.state.loading = true;
let response = await Ajax.get('/api/services/app/Product/GetAll', {params: payload.data});
context.state.loading = false;
let page = response.data.result;
context.state.totalCount = page.totalCount;
context.state.list = page.items;
},
async get(context, payload) {
let response = await Ajax.get('/api/services/app/Product/Get?Id=' + payload.id);
return response.data.result;
},
async create(context, payload) {
return await Ajax.post('/api/services/app/Product/Create', payload.data);
},
async update(context, payload) {
return await Ajax.put('/api/services/app/Product/Update', payload.data);
},
async delete(context, payload) {
return await Ajax.delete('/api/services/app/Product/Delete?Id=' + payload.data.id);
}
}
}
export default product;<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Authorization/Users/UserManager.cs
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Abp.UI;
using Abp.Zero;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.Localization;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Organizations;
using Abp.Runtime.Caching;
using JFJT.GemStockpiles.Authorization.Roles;
using System.Linq;
namespace JFJT.GemStockpiles.Authorization.Users
{
public class UserManager : AbpUserManager<Role, User>
{
private readonly IUnitOfWorkManager _unitOfWorkManager;
public UserManager(
RoleManager roleManager,
UserStore store,
IOptions<IdentityOptions> optionsAccessor,
IPasswordHasher<User> passwordHasher,
IEnumerable<IUserValidator<User>> userValidators,
IEnumerable<IPasswordValidator<User>> passwordValidators,
ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors,
IServiceProvider services,
ILogger<UserManager<User>> logger,
IPermissionManager permissionManager,
IUnitOfWorkManager unitOfWorkManager,
ICacheManager cacheManager,
IRepository<OrganizationUnit, long> organizationUnitRepository,
IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
IOrganizationUnitSettings organizationUnitSettings,
ISettingManager settingManager)
: base(
roleManager,
store,
optionsAccessor,
passwordHasher,
userValidators,
passwordValidators,
keyNormalizer,
errors,
services,
logger,
permissionManager,
unitOfWorkManager,
cacheManager,
organizationUnitRepository,
userOrganizationUnitRepository,
organizationUnitSettings,
settingManager)
{
_unitOfWorkManager = unitOfWorkManager;
}
public override async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress)
{
var user = (await FindByNameAsync(userName));
if (user != null && user.Id != expectedUserId)
{
throw new UserFriendlyException(string.Format(L("Identity.DuplicateUserName"), userName));
}
return IdentityResult.Success;
}
private string L(string name)
{
return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name);
}
public override async Task<IdentityResult> CreateAsync(User user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
user.Surname = string.Empty;
user.EmailAddress = string.Empty;
var tenantId = GetCurrentTenantId();
if (tenantId.HasValue && !user.TenantId.HasValue)
{
user.TenantId = tenantId.Value;
}
return await base.CreateAsync(user);
}
public override async Task<IdentityResult> UpdateAsync(User user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
//Admin user's username can not be changed!
if (user.UserName != AbpUserBase.AdminUserName)
{
if ((await GetOldUserNameAsync(user.Id)) == AbpUserBase.AdminUserName)
{
throw new UserFriendlyException(string.Format(L("CanNotRenameAdminUser"), AbpUserBase.AdminUserName));
}
}
return await base.UpdateAsync(user);
}
public override async Task<IdentityResult> ChangePasswordAsync(User user, string currentPassword, string newPassword)
{
if (currentPassword.IsNullOrEmpty() || newPassword.IsNullOrEmpty())
{
throw new UserFriendlyException("修改失败", "参数错误!");
}
if (PasswordHasher.VerifyHashedPassword(user, user.Password, currentPassword) == PasswordVerificationResult.Failed)
{
throw new UserFriendlyException("修改失败", "原密码错误!");
}
await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(user, newPassword));
return IdentityResult.Success;
}
private int? GetCurrentTenantId()
{
if (_unitOfWorkManager.Current != null)
{
return _unitOfWorkManager.Current.GetTenantId();
}
return AbpSession.TenantId;
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/GemStockpilesAppServiceBase.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Abp.Runtime.Session;
using Abp.IdentityFramework;
using Abp.Application.Services;
using JFJT.GemStockpiles.MultiTenancy;
using JFJT.GemStockpiles.Authorization.Users;
namespace JFJT.GemStockpiles
{
/// <summary>
/// Derive your application services from this class.
/// </summary>
public abstract class GemStockpilesAppServiceBase : ApplicationService
{
public TenantManager TenantManager { get; set; }
public UserManager UserManager { get; set; }
protected GemStockpilesAppServiceBase()
{
LocalizationSourceName = GemStockpilesConsts.LocalizationSourceName;
}
protected virtual Task<User> GetCurrentUserAsync()
{
var user = UserManager.FindByIdAsync(AbpSession.GetUserId().ToString());
if (user == null)
{
throw new Exception("There is no current user!");
}
return user;
}
protected virtual Task<Tenant> GetCurrentTenantAsync()
{
return TenantManager.GetByIdAsync(AbpSession.GetTenantId());
}
protected virtual void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}
<file_sep>/vue/src/store/modules/point/pointRule.js
import Ajax from '@/libs/ajax';
const pointRule = {
namespaced: true,
state: {
totalCount: 0,
currentPage: 1,
pageSize: 10,
list: [],
loading: false,
editRuleId: 0,
pointActions: []
},
mutations: {
setCurrentPage(state, page) {
state.currentPage = page;
},
setPageSize(state, pageSize) {
state.pageSize = pageSize;
},
edit(state, id) {
state.editRuleId = id;
}
},
actions: {
async getAll(context, payload) {
context.state.loading = true;
// 初始化积分动作列表
if(context.state.pointActions.length <= 0) {
await context.dispatch('getAllPointActions');
}
let response = await Ajax.get('/api/services/app/PointRule/GetAll', {params: payload.data});
context.state.loading = false;
let page = response.data.result;
context.state.totalCount = page.totalCount;
context.state.list = page.items;
},
async getAllPointActions(context) {
let response = await Ajax.get('/api/services/app/PointRule/GetAllPointActions');
context.state.pointActions = response.data.result.items;
},
async get(context, payload) {
return await Ajax.get('/api/services/app/PointRule/Get?Id=' + payload.id);
},
async create(context, payload) {
return await Ajax.post('/api/services/app/PointRule/Create', payload.data);
},
async update(context, payload) {
return await Ajax.put('/api/services/app/PointRule/Update', payload.data);
},
async delete(context, payload) {
return await Ajax.delete('/api/services/app/PointRule/Delete?Id=' + payload.data.id);
}
}
};
export default pointRule;
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Web.Host/Controllers/AntiForgeryController.cs
using Microsoft.AspNetCore.Antiforgery;
using JFJT.GemStockpiles.Controllers;
namespace JFJT.GemStockpiles.Web.Host.Controllers
{
public class AntiForgeryController : GemStockpilesControllerBase
{
private readonly IAntiforgery _antiforgery;
public AntiForgeryController(IAntiforgery antiforgery)
{
_antiforgery = antiforgery;
}
public void GetToken()
{
_antiforgery.SetCookieTokenAndHeader(HttpContext);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Customers/CustomerCompanyLicense.cs
using System;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Customers
{
/// <summary>
/// 公司三证信息表
/// </summary>
public class CustomerCompanyLicense : FullAudited<Guid>
{
/// <summary>
/// 公司Id
/// </summary>
public Guid CompanyId { get; set; }
/// <summary>
/// 证书类型
/// </summary>
public CompanyLicenseTypeEnum Type { get; set; } = CompanyLicenseTypeEnum.BusinessLicense;
/// <summary>
/// 排序
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 图片地址
/// </summary>
public string ImageUrl { get; set; }
}
}
<file_sep>/vue/src/libs/util.js
import jQuery from 'jquery';
let util = {
};
util.abp = window.abp;
util.inOf = function (arr, targetArr) {
let res = true;
arr.forEach(item => {
if (targetArr.indexOf(item) < 0) {
res = false;
}
});
return res;
};
util.oneOf = function (ele, targetArr) {
if (targetArr.indexOf(ele) >= 0) {
return true;
} else {
return false;
}
};
util.showThisRoute = function (itAccess, currentAccess) {
if (typeof itAccess === 'object' && Array.isArray(itAccess)) {
return util.oneOf(currentAccess, itAccess);
} else {
return itAccess === currentAccess;
}
};
util.getRouterObjByName = function (routers, name) {
if (!name || !routers || !routers.length) {
return null;
}
// debugger;
let routerObj = null;
for (let item of routers) {
if (item.name === name) {
return item;
}
routerObj = util.getRouterObjByName(item.children, name);
if (routerObj) {
return routerObj;
}
}
return null;
};
util.handleTitle = function (vm, item) {
return item.meta.title;
};
util.setCurrentPath = function (vm, name) {
let title = '';
let isOtherRouter = false;
vm.$store.state.app.routers.forEach(item => {
if (item.children.length === 1) {
if (item.children[0].name === name) {
title = util.handleTitle(vm, item);
if (item.name === 'main') {
isOtherRouter = true;
}
}
} else {
item.children.forEach(child => {
if (child.name === name) {
title = util.handleTitle(vm, child);
if (item.name === 'main') {
isOtherRouter = true;
}
}
});
}
});
let currentPathArr = [];
if (name === 'home') {
currentPathArr = [
{
meta: { title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home')), icon: 'ios-home' },
path: '/main/home',
name: 'home'
}
];
} else if ((name.indexOf('index') >= 0 || isOtherRouter) && name !== 'home') {
currentPathArr = [
{
meta: { title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home')), icon: 'ios-home' },
path: '/main/home',
name: 'home'
},
{
meta: { title: title },
path: '',
name: name
}
];
} else {
let currentPathObj = vm.$store.state.app.routers.filter(item => {
if (item.children.length <= 1) {
return item.children[0].name === name;
} else {
let i = 0;
let childArr = item.children;
let len = childArr.length;
while (i < len) {
if (childArr[i].name === name) {
return true;
}
i++;
}
return false;
}
})[0];
if (currentPathObj.children.length <= 1 && currentPathObj.name === 'home') {
currentPathArr = [
{
meta: { title: '首页', icon: 'ios-home' },
path: '/main/home',
name: 'home'
}
];
} else if (currentPathObj.children.length <= 1 && currentPathObj.name !== 'home') {
currentPathArr = [
{
meta: { title: '首页', icon: 'ios-home' },
path: '/main/home',
name: 'home'
},
{
meta: { title: currentPathObj.meta.title },
path: '',
name: name
}
];
} else {
let childObj = currentPathObj.children.filter((child) => {
return child.name === name;
})[0];
currentPathArr = [
{
meta: { title: '首页', icon: 'ios-home' },
path: '/main/home',
name: 'home'
},
{
meta: { title: currentPathObj.meta.title },
path: '',
name: currentPathObj.name
},
{
meta: { title: childObj.meta.title },
path: currentPathObj.path + '/' + childObj.path,
name: name
}
];
}
}
vm.$store.commit('app/setCurrentPath', currentPathArr);
return currentPathArr;
};
util.openNewPage = function (vm, name, argu, query) {
let pageOpenedList = vm.$store.state.app.pageOpenedList;
let openedPageLen = pageOpenedList.length;
let i = 0;
let tagHasOpened = false;
while (i < openedPageLen) {
if (name === pageOpenedList[i].name) { // 页面已经打开
vm.$store.commit('app/pageOpenedList', {
index: i,
argu: argu,
query: query
});
tagHasOpened = true;
break;
}
i++;
}
if (!tagHasOpened) {
let tag = vm.$store.state.app.tagsList.filter((item) => {
if (item.children) {
return name === item.children[0].name;
} else {
return name === item.name;
}
});
tag = tag[0];
if (tag) {
tag = tag.children ? tag.children[0] : tag;
if (argu) {
tag.argu = argu;
}
if (query) {
tag.query = query;
}
vm.$store.commit('app/increateTag', tag);
}
}
vm.$store.commit('app/setCurrentPageName', name);
};
util.toDefaultPage = function (routers, name, route, next) {
let len = routers.length;
let i = 0;
let notHandle = true;
while (i < len) {
if (routers[i].name === name && routers[i].children && routers[i].redirect === undefined) {
route.replace({
name: routers[i].children[0].name
});
notHandle = false;
next();
break;
}
i++;
}
if (notHandle) {
next();
}
};
util.extend = function(...args) {
let options, name, src, srcType, copy, copyType, copyIsArray, clone,
target = args[0] || {},
i = 1,
length = args.length,
deep = false;
if (typeof target === 'boolean') {
deep = target;
target = args[i] || {};
i++;
}
if (typeof target !== 'object' && typeof target !== 'function') {
target = {};
}
if (i === length) {
target = this;
i--;
}
for (; i < length; i++) {
if ((options = args[i]) !== null) {
for (name in options) {
src = target[name];
copy = options[name];
if (target === copy) {
continue;
}
srcType = Array.isArray(src) ? 'array': typeof src;
if (deep && copy && ((copyIsArray = Array.isArray(copy)) || typeof copy === 'object')) {
if (copyIsArray) {
copyIsArray = false;
clone = src && srcType === 'array' ? src : [];
} else {
clone = src && srcType === 'object' ? src: {};
}
target[name] = this.extend(deep, clone, copy);
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
}
// 重置权限树
util.resetPermissionTree = function(permissions) {
let resData = [];
permissions.forEach((item) => {
let children;
if(item.children && item.children.length > 0) {
children = this.resetPermissionTree(item.children);
}
let model = {
title: item.title,
name: item.name,
level: item.level,
checked: false,
expand: item.level > 2 ? false : true,
children: (children == undefined || children == null || children.Count <= 0 ? null : children)
};
resData.push(model);
});
return resData;
}
// 编辑默认选中
util.checkedPermissionTree = function(permissions, checkedNodes) {
let resData = [];
permissions.forEach((item) => {
let children, checkState;
if(item.children && item.children.length > 0) {
children = this.checkedPermissionTree(item.children, checkedNodes);
}
// 最末级别判断
if(children == undefined || children == null || children.Count <= 0) {
if(jQuery.inArray(item.name, checkedNodes) >= 0) {
checkState = true
}
else {
checkState = false;
}
}
else {
checkState = false;
}
let model = {
title: item.title,
name: item.name,
level: item.level,
checked: checkState,
expand: item.level > 2 ? false : true,
children: (children == undefined || children == null || children.Count <= 0 ? null : children)
};
resData.push(model);
});
return resData;
}
// 删除children空节点
util.removeNullChildrenNode = function(JsonObj) {
JsonObj.forEach((item) => {
if(!item.children) {
delete item['children'];
}
else {
this.removeNullChildrenNode(item.children);
}
});
return JsonObj;
}
export default util;
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Points/PointLog.cs
using System;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Points
{
/// <summary>
/// 平台会员积分日志
/// </summary>
public class PointLog : CreateAudited<Guid>
{
/// <summary>
/// 会员ID
/// </summary>
public int MemberId { get; set; }
/// <summary>
/// 积分值
/// </summary>
public int Points { get; set; }
/// <summary>
/// 动作类型
/// </summary>
public PointActionEnum ActionType { get; set; } = PointActionEnum.Upload;
/// <summary>
/// 动作描述
/// </summary>
public string ActionDesc { get; set; }
/// <summary>
/// 动作时间
/// </summary>
public DateTime ActionTime { get; set; } = System.DateTime.Now;
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/Products/Dto/ProductDto.cs
using System;
using System.Collections.Generic;
using Abp.AutoMapper;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Models.Products;
namespace JFJT.GemStockpiles.Products.Products.Dto
{
/// <summary>
/// 商品管理Dto
/// </summary>
[AutoMap(typeof(Product))]
public class ProductDto: EntityDto<Guid>
{
#region 基础字段
/// <summary>
/// 分类Id
/// </summary>
public Guid CategoryId { get; set; }
/// <summary>
/// 产品名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 产品编号
/// </summary>
public string Sn { get; set; }
/// <summary>
/// 证书号
/// </summary>
public string CertNo { get; set; }
/// <summary>
/// 重量(毫克)
/// </summary>
public int Weight { get; set; }
/// <summary>
/// 数量
/// </summary>
public int Number { get; set; }
/// <summary>
/// 价格(分)
/// </summary>
public int Price { get; set; }
/// <summary>
/// 产品备注
/// </summary>
public string Remark { get; set; }
/// <summary>
/// 产品属性列表
/// </summary>
public virtual List<ProductAttributeValue> ProductAttributeValues { get; set; } = new List<ProductAttributeValue>();
/// <summary>
/// 产品媒体列表
/// </summary>
public virtual List<ProductMedia> ProductMedias { get; set; } = new List<ProductMedia>();
#endregion
#region 应用字段
/// <summary>
/// 所属客户Id
/// </summary>
public int CustomerId { get; set; }
/// <summary>
/// 产品审核状态
/// </summary>
public ProductAuditStateEnum AuditState { get; set; } = ProductAuditStateEnum.Editing;
/// <summary>
/// 产品销售状态
/// </summary>
public ProductSaleStateEnum SaleState { get; set; } = ProductSaleStateEnum.OffShelves;
/// <summary>
/// 是否推荐商品
/// </summary>
public bool IsRecommend { get; set; } = false;
/// <summary>
/// 审核人登录帐号
/// </summary>
public string AuditedAccount { get; set; }
/// <summary>
/// 审核时间
/// </summary>
public DateTime? AuditedTime { get; set; }
/// <summary>
/// 驳回原因
/// </summary>
public string RejectedRemark { get; set; }
#endregion
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Enums/UserStateEnum.cs
using System;
namespace JFJT.GemStockpiles.Enums
{
/// <summary>
/// 注册用户审核状态
/// </summary>
public enum UserStateEnum
{
/// <summary>
/// 审核中
/// </summary>
Submited = 10,
/// <summary>
/// 审核不通过
/// </summary>
Rejected = 20,
/// <summary>
/// 审核通过
/// </summary>
Approved = 30
}
}
<file_sep>/vue/src/store/modules/common/session.js
import Util from '@/libs/util';
import Ajax from '@/libs/ajax';
const session = {
namespaced: true,
state: {
application: null,
user: null,
tenant: null
},
getters:{
getCurrentUser: state => {
if(!state.user) {
state.user = JSON.parse(localStorage.currentUser)
}
return state.user;
}
},
mutations: {
//
},
actions: {
async init(content) {
let response = await Ajax.get('/api/services/app/Session/GetCurrentLoginInformations', {
headers:{
'Abp.TenantId': Util.abp.multiTenancy.getTenantIdCookie()
}}
);
content.state.application = response.data.result.application;
content.state.user = response.data.result.user;
content.state.tenant = response.data.result.tenant;
//前端持久化数据
localStorage.currentUser = JSON.stringify(response.data.result.user);
}
}
};
export default session;
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Enums/PayModeEnum.cs
using System;
namespace JFJT.GemStockpiles.Enums
{
/// <summary>
/// 支付方式
/// </summary>
public enum PayModeEnum
{
/// <summary>
/// 线下付款
/// </summary>
OfflinePay = 10,
/// <summary>
/// 银联转账
/// </summary>
UnionPay = 20,
/// <summary>
/// 支付宝
/// </summary>
Alipay = 30,
/// <summary>
/// 微信
/// </summary>
WeChat = 40
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/CategoryAttributeItems/ICategoryAttributeItemAppService.cs
using System;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Products.CategoryAttributeItems.Dto;
namespace JFJT.GemStockpiles.Products.CategoryAttributeItems
{
public interface ICategoryAttributeItemAppService : IAsyncCrudAppService<CategoryAttributeItemDto, Guid, PagedResultRequestDto, CategoryAttributeItemDto, CategoryAttributeItemDto>
{
/// <summary>
/// 根据属性ID获取属性值列表数据
/// </summary>
/// <param name="attributeId"></param>
/// <returns></returns>
Task<ListResultDto<CategoryAttributeItemDto>> GetCategoryAttributeItems(Guid attributeId);
}
}
<file_sep>/vue/src/store/modules/point/pointRank.js
import Ajax from '@/libs/ajax';
const pointRank = {
namespaced: true,
state: {
totalCount: 0,
currentPage: 1,
pageSize: 10,
list: [],
loading: false,
editRankId: 0
},
mutations: {
setCurrentPage(state, page) {
state.currentPage = page;
},
setPageSize(state, pageSize) {
state.pageSize = pageSize;
},
edit(state, id) {
state.editRankId = id;
}
},
actions: {
async getAll(context, payload) {
context.state.loading = true;
let response = await Ajax.get('/api/services/app/PointRank/GetAll', {params: payload.data});
context.state.loading = false;
let page = response.data.result;
context.state.totalCount = page.totalCount;
// 积分区间计算
if(page.items.length > 0) {
page.items.forEach((item, index, array) => {
if(array[index+1]) {
let maxPoint = parseInt(array[index+1].minPoint);
maxPoint = maxPoint - 1;
if(item.minPoint != maxPoint) {
item.range = item.minPoint + ' ~ ' + maxPoint;
}
else {
item.range = item.minPoint;
}
}
else {
item.range = '>= ' + item.minPoint;
}
});
}
context.state.list = page.items;
},
async get(context, payload) {
return await Ajax.get('/api/services/app/PointRank/Get?Id=' + payload.id);
},
async create(context, payload) {
return await Ajax.post('/api/services/app/PointRank/Create', payload.data);
},
async update(context, payload) {
return await Ajax.put('/api/services/app/PointRank/Update', payload.data);
},
async delete(context, payload) {
return await Ajax.delete('/api/services/app/PointRank/Delete?Id=' + payload.data.id);
}
}
};
export default pointRank;
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Roles/Dto/PermissionTreeDto.cs
using System.Collections.Generic;
namespace JFJT.GemStockpiles.Roles.Dto
{
public class PermissionTreeDto
{
public string title { get; set; }
public string name { get; set; }
public int level { get; set; }
public bool expand { get; set; } = true;
public List<PermissionTreeDto> children { get; set; } = new List<PermissionTreeDto>();
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/Categorys/Dto/CategoryTreeDto.cs
using System;
using System.Collections.Generic;
namespace JFJT.GemStockpiles.Products.Categorys.Dto
{
public class CategoryTreeDto
{
public Guid value { get; set; }
public string title { get; set; }
public int level { get; set; }
public bool expand { get; set; } = true;
public List<CategoryTreeDto> children { get; set; } = new List<CategoryTreeDto>();
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Sessions/ISessionAppService.cs
using System.Threading.Tasks;
using Abp.Application.Services;
using JFJT.GemStockpiles.Sessions.Dto;
namespace JFJT.GemStockpiles.Sessions
{
public interface ISessionAppService : IApplicationService
{
Task<GetCurrentLoginInformationsOutput> GetCurrentLoginInformations();
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/Products/IProductAppService.cs
using System;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Products.Products.Dto;
namespace JFJT.GemStockpiles.Products.Products
{
public interface IProductAppService : IAsyncCrudAppService<ProductDto, Guid, PagedResultRequestDto, ProductDto, ProductDto>
{
}
}<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Authorization/GemStockpilesAuthorizationProvider.cs
using Abp.Authorization;
using Abp.Localization;
using Abp.MultiTenancy;
namespace JFJT.GemStockpiles.Authorization
{
public class GemStockpilesAuthorizationProvider : AuthorizationProvider
{
public override void SetPermissions(IPermissionDefinitionContext context)
{
var pages = context.GetPermissionOrNull(PermissionNames.Pages) ?? context.CreatePermission(PermissionNames.Pages, L("Pages"));
#region 系统管理
var systemManagement = pages.CreateChildPermission(PermissionNames.Pages_SystemManagement, L("SystemManagement"));
var roles = systemManagement.CreateChildPermission(PermissionNames.Pages_SystemManagement_Roles, L("Roles"));
roles.CreateChildPermission(PermissionNames.Pages_SystemManagement_Roles_View, L("View"));
roles.CreateChildPermission(PermissionNames.Pages_SystemManagement_Roles_Create, L("Create"));
roles.CreateChildPermission(PermissionNames.Pages_SystemManagement_Roles_Edit, L("Edit"));
roles.CreateChildPermission(PermissionNames.Pages_SystemManagement_Roles_Delete, L("Delete"));
var users = systemManagement.CreateChildPermission(PermissionNames.Pages_SystemManagement_Users, L("Users"));
users.CreateChildPermission(PermissionNames.Pages_SystemManagement_Users_View, L("View"));
users.CreateChildPermission(PermissionNames.Pages_SystemManagement_Users_Create, L("Create"));
users.CreateChildPermission(PermissionNames.Pages_SystemManagement_Users_Edit, L("Edit"));
users.CreateChildPermission(PermissionNames.Pages_SystemManagement_Users_Delete, L("Delete"));
var tenants = systemManagement.CreateChildPermission(PermissionNames.Pages_SystemManagement_Tenants, L("Tenants"), multiTenancySides: MultiTenancySides.Host);
tenants.CreateChildPermission(PermissionNames.Pages_SystemManagement_Tenants_View, L("View"), multiTenancySides: MultiTenancySides.Host);
tenants.CreateChildPermission(PermissionNames.Pages_SystemManagement_Tenants_Create, L("Create"), multiTenancySides: MultiTenancySides.Host);
tenants.CreateChildPermission(PermissionNames.Pages_SystemManagement_Tenants_Edit, L("Edit"), multiTenancySides: MultiTenancySides.Host);
tenants.CreateChildPermission(PermissionNames.Pages_SystemManagement_Tenants_Delete, L("Delete"), multiTenancySides: MultiTenancySides.Host);
#endregion
#region 积分管理
var pointManagement = pages.CreateChildPermission(PermissionNames.Pages_PointManagement, L("PointManagement"));
var pointRules = pointManagement.CreateChildPermission(PermissionNames.Pages_PointManagement_PointRules, L("PointRules"));
pointRules.CreateChildPermission(PermissionNames.Pages_PointManagement_PointRules_View, L("View"));
pointRules.CreateChildPermission(PermissionNames.Pages_PointManagement_PointRules_Create, L("Create"));
pointRules.CreateChildPermission(PermissionNames.Pages_PointManagement_PointRules_Edit, L("Edit"));
pointRules.CreateChildPermission(PermissionNames.Pages_PointManagement_PointRules_Delete, L("Delete"));
var pointRanks = pointManagement.CreateChildPermission(PermissionNames.Pages_PointManagement_PointRanks, L("PointRanks"));
pointRanks.CreateChildPermission(PermissionNames.Pages_PointManagement_PointRanks_View, L("View"));
pointRanks.CreateChildPermission(PermissionNames.Pages_PointManagement_PointRanks_Create, L("Create"));
pointRanks.CreateChildPermission(PermissionNames.Pages_PointManagement_PointRanks_Edit, L("Edit"));
pointRanks.CreateChildPermission(PermissionNames.Pages_PointManagement_PointRanks_Delete, L("Delete"));
#endregion
#region 商品管理
var ProductManagement = pages.CreateChildPermission(PermissionNames.Pages_ProductManagement, L("ProductManagement"));
var product = ProductManagement.CreateChildPermission(PermissionNames.Pages_ProductManagement_Products, L("Products"));
product.CreateChildPermission(PermissionNames.Pages_ProductManagement_Products_View, L("View"));
product.CreateChildPermission(PermissionNames.Pages_ProductManagement_Products_Create, L("Create"));
product.CreateChildPermission(PermissionNames.Pages_ProductManagement_Products_Edit, L("Edit"));
product.CreateChildPermission(PermissionNames.Pages_ProductManagement_Products_Delete, L("Delete"));
var settings = ProductManagement.CreateChildPermission(PermissionNames.Pages_ProductManagement_Categorys, L("ProductCategorys"));
settings.CreateChildPermission(PermissionNames.Pages_ProductManagement_Categorys_View, L("View"));
settings.CreateChildPermission(PermissionNames.Pages_ProductManagement_Categorys_Create, L("Create"));
settings.CreateChildPermission(PermissionNames.Pages_ProductManagement_Categorys_Edit, L("Edit"));
settings.CreateChildPermission(PermissionNames.Pages_ProductManagement_Categorys_Delete, L("Delete"));
var analysis = ProductManagement.CreateChildPermission(PermissionNames.Pages_ProductManagement_CategoryAttributes, L("CategoryAttributes"));
analysis.CreateChildPermission(PermissionNames.Pages_ProductManagement_CategoryAttributes_View, L("View"));
analysis.CreateChildPermission(PermissionNames.Pages_ProductManagement_CategoryAttributes_Create, L("Create"));
analysis.CreateChildPermission(PermissionNames.Pages_ProductManagement_CategoryAttributes_Edit, L("Edit"));
analysis.CreateChildPermission(PermissionNames.Pages_ProductManagement_CategoryAttributes_Delete, L("Delete"));
#endregion
#region 订单管理
var OrderManagement = pages.CreateChildPermission(PermissionNames.Pages_OrderManagement, L("OrderManagement"));
var orders = OrderManagement.CreateChildPermission(PermissionNames.Pages_OrderManagement_Orders, L("Orders"));
orders.CreateChildPermission(PermissionNames.Pages_OrderManagement_Orders_View, L("View"));
orders.CreateChildPermission(PermissionNames.Pages_OrderManagement_Orders_Create, L("Create"));
orders.CreateChildPermission(PermissionNames.Pages_OrderManagement_Orders_Edit, L("Edit"));
orders.CreateChildPermission(PermissionNames.Pages_OrderManagement_Orders_Delete, L("Delete"));
var comment = OrderManagement.CreateChildPermission(PermissionNames.Pages_OrderManagement_Comments, L("OrderComments"));
comment.CreateChildPermission(PermissionNames.Pages_OrderManagement_Comments_View, L("View"));
comment.CreateChildPermission(PermissionNames.Pages_OrderManagement_Comments_Create, L("Create"));
comment.CreateChildPermission(PermissionNames.Pages_OrderManagement_Comments_Edit, L("Edit"));
comment.CreateChildPermission(PermissionNames.Pages_OrderManagement_Comments_Delete, L("Delete"));
#endregion
}
private static ILocalizableString L(string name)
{
return new LocalizableString(name, GemStockpilesConsts.LocalizationSourceName);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Products/ProductMedia.cs
using System;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Products
{
/// <summary>
/// 产品媒体信息表
/// </summary>
public class ProductMedia : CreateAudited
{
/// <summary>
/// 产品ID
/// </summary>
public Guid ProductId { get; set; }
/// <summary>
/// 媒体类型
/// </summary>
public MediaTypeEnum Type { get; set; }
/// <summary>
/// url
/// </summary>
public string Url { get; set; }
/// <summary>
/// 排序
/// </summary>
public int Sort { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/Categorys/CategoryAppService.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Abp.UI;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Authorization;
using JFJT.GemStockpiles.Models.Products;
using JFJT.GemStockpiles.Products.Categorys.Dto;
namespace JFJT.GemStockpiles.Products.Categorys
{
[AbpAuthorize(PermissionNames.Pages_ProductManagement_Categorys)]
public class CategoryAppService : AsyncCrudAppService<Category, CategoryDto, Guid, PagedResultRequestDto, CategoryDto, CategoryDto>, ICategoryAppService
{
private readonly IRepository<Category, Guid> _categoryRepository;
public CategoryAppService(IRepository<Category, Guid> categoryRepository)
: base(categoryRepository)
{
_categoryRepository = categoryRepository;
}
[AbpAuthorize(PermissionNames.Pages_ProductManagement_Categorys_Create)]
public override async Task<CategoryDto> Create(CategoryDto input)
{
CheckCreatePermission();
if (_categoryRepository.GetAll().FirstOrDefault(b => b.Name == input.Name && b.ParentId == input.ParentId) != null)
throw new UserFriendlyException(input.Name + " 分类名称已存在");
if (_categoryRepository.GetAll().FirstOrDefault(b => b.Sort == input.Sort && b.ParentId == input.ParentId) != null)
throw new UserFriendlyException(input.Sort + " 当前排序已存在");
var entity = ObjectMapper.Map<Category>(input);
if (input.ParentId != null) {
}
entity = await _categoryRepository.InsertAsync(entity);
return MapToEntityDto(entity);
}
[AbpAuthorize(PermissionNames.Pages_ProductManagement_Categorys_View)]
public Task<ListResultDto<CategoryDto>> GetParent()
{
var entity = _categoryRepository.GetAllList().Where(a => a.ParentId == null);
return Task.FromResult(new ListResultDto<CategoryDto>(
ObjectMapper.Map<List<CategoryDto>>(entity)
));
}
#region Tree
public Task<ListResultDto<CategoryTreeDto>> GetTreeCategory()
{
List<CategoryTreeDto> treeList = new List<CategoryTreeDto>();
var Category = _categoryRepository.GetAllList();
var treeData = new ListResultDto<Category>(ObjectMapper.Map<List<Category>>(Category));
if (treeData != null)
{
treeList = GetTreePermissionList(treeData,null, 0);
}
return Task.FromResult(new ListResultDto<CategoryTreeDto>(ObjectMapper.Map<List<CategoryTreeDto>>(treeList)));
}
/// <summary>
/// 递归生成分类tree
/// </summary>
/// <param name="categoryData"></param>
/// <param name="parentId"></param>
/// <param name="parentLevel"></param>
/// <returns></returns>
private List<CategoryTreeDto> GetTreePermissionList(ListResultDto<Category> categoryData, Guid? parentId, int parentLevel)
{
List<CategoryTreeDto> treeList = new List<CategoryTreeDto>();
var level = parentLevel + 1;
var treeData = categoryData.Items.Where(b => b.ParentId == parentId).ToList();
foreach (var item in treeData)
{
var children = GetTreePermissionList(categoryData, item.Id, level);
var model = new CategoryTreeDto() { title = item.Name, level = level,value=item.Id };
model.children = children.Count <= 0 ? null : children;
model.expand = level <= 2 ? true : false;
treeList.Add(model);
}
return treeList;
}
#endregion
#region Cascader
public Task<ListResultDto<CategoryCascaderDto>> GetCascaderCategory()
{
List<CategoryCascaderDto> treeList = new List<CategoryCascaderDto>();
var Category = _categoryRepository.GetAllList();
var treeData = new ListResultDto<Category>(ObjectMapper.Map<List<Category>>(Category));
if (treeData != null)
{
treeList = GetCascaderCategoryList(treeData, null, 0);
}
return Task.FromResult(new ListResultDto<CategoryCascaderDto>(ObjectMapper.Map<List<CategoryCascaderDto>>(treeList)));
}
/// <summary>
/// 递归生成分类Cascader
/// </summary>
/// <param name="categoryData"></param>
/// <param name="parentId"></param>
/// <param name="parentLevel"></param>
/// <returns></returns>
private List<CategoryCascaderDto> GetCascaderCategoryList(ListResultDto<Category> categoryData, Guid? parentId, int parentLevel)
{
List<CategoryCascaderDto> treeList = new List<CategoryCascaderDto>();
var level = parentLevel + 1;
var treeData = categoryData.Items.Where(b => b.ParentId == parentId).ToList();
foreach (var item in treeData)
{
var children = GetCascaderCategoryList(categoryData, item.Id, level);
var model = new CategoryCascaderDto() { label = item.Name, value = item.Id };
model.children = children.Count <= 0 ? null : children;
treeList.Add(model);
}
return treeList;
}
#endregion
}
}<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Products/CategoryAttributeItems/CategoryAttributeItemAppService.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
using Abp.UI;
using Abp.Authorization;
using Abp.Domain.Entities;
using Abp.IdentityFramework;
using Abp.Domain.Repositories;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Authorization;
using JFJT.GemStockpiles.Models.Products;
using JFJT.GemStockpiles.Products.CategoryAttributeItems.Dto;
namespace JFJT.GemStockpiles.Products.CategoryAttributeItems
{
[AbpAuthorize(PermissionNames.Pages_ProductManagement_CategoryAttributes)]
public class CategoryAttributeItemAppService : AsyncCrudAppService<CategoryAttributeItem, CategoryAttributeItemDto, Guid, PagedResultRequestDto, CategoryAttributeItemDto, CategoryAttributeItemDto>, ICategoryAttributeItemAppService
{
private readonly IRepository<CategoryAttributeItem, Guid> _categoryAttributeItemRepository;
public CategoryAttributeItemAppService(IRepository<CategoryAttributeItem, Guid> categoryAttributeItemRepository)
: base(categoryAttributeItemRepository)
{
_categoryAttributeItemRepository = categoryAttributeItemRepository;
}
/// <summary>
/// 添加属性值
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_ProductManagement_CategoryAttributes_Create)]
public override async Task<CategoryAttributeItemDto> Create(CategoryAttributeItemDto input)
{
CheckCreatePermission();
CheckErrors(await CheckValueOrSortAsync(input.Id, input.CategoryAttributeId, input.Value, input.Sort));
var entity = ObjectMapper.Map<CategoryAttributeItem>(input);
entity = await _categoryAttributeItemRepository.InsertAsync(entity);
return MapToEntityDto(entity);
}
/// <summary>
/// 修改属性值
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_ProductManagement_CategoryAttributes_Edit)]
public override async Task<CategoryAttributeItemDto> Update(CategoryAttributeItemDto input)
{
CheckUpdatePermission();
var entity = await _categoryAttributeItemRepository.GetAsync(input.Id);
if (entity == null)
throw new EntityNotFoundException(typeof(CategoryAttributeItem), input.Id);
CheckErrors(await CheckValueOrSortAsync(input.Id, input.CategoryAttributeId, input.Value, input.Sort));
MapToEntity(input, entity);
entity = await _categoryAttributeItemRepository.UpdateAsync(entity);
return MapToEntityDto(entity);
}
/// <summary>
/// 删除属性值
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(PermissionNames.Pages_ProductManagement_CategoryAttributes_Delete)]
public override async Task Delete(EntityDto<Guid> input)
{
CheckDeletePermission();
var entity = await _categoryAttributeItemRepository.GetAsync(input.Id);
if (entity == null)
throw new EntityNotFoundException(typeof(CategoryAttributeItem), input.Id);
await _categoryAttributeItemRepository.DeleteAsync(entity);
}
/// <summary>
/// 根据属性ID获取属性值列表数据
/// </summary>
/// <param name="attributeId"></param>
/// <returns></returns>
public Task<ListResultDto<CategoryAttributeItemDto>> GetCategoryAttributeItems(Guid attributeId)
{
var entity = _categoryAttributeItemRepository.GetAll().Where(t => t.CategoryAttributeId == attributeId).OrderBy(t => t.Sort);
return Task.FromResult(new ListResultDto<CategoryAttributeItemDto>(
ObjectMapper.Map<List<CategoryAttributeItemDto>>(entity)
));
}
/// <summary>
/// Dto模型映射
/// </summary>
/// <param name="input"></param>
/// <param name="pointRank"></param>
protected override void MapToEntity(CategoryAttributeItemDto input, CategoryAttributeItem categoryAttributeItem)
{
ObjectMapper.Map(input, categoryAttributeItem);
}
/// <summary>
/// 检测属性值或排序值是否已存在
/// </summary>
/// <param name="expectedId"></param>
/// <param name="attributeId"></param>
/// <param name="value"></param>
/// <param name="sort"></param>
/// <returns></returns>
protected async Task<IdentityResult> CheckValueOrSortAsync(Guid? expectedId, Guid attributeId, string value, int sort)
{
var entity = await _categoryAttributeItemRepository.FirstOrDefaultAsync(b => b.CategoryAttributeId == attributeId && b.Value == value);
if (entity != null && entity.Id != expectedId)
{
throw new UserFriendlyException("属性值已存在");
}
entity = await _categoryAttributeItemRepository.FirstOrDefaultAsync(b => b.CategoryAttributeId == attributeId && b.Sort == sort);
if (entity != null && entity.Id != expectedId)
{
throw new UserFriendlyException("排序值已存在");
}
return IdentityResult.Success;
}
/// <summary>
/// 异常描述本地化转换函数
/// </summary>
/// <param name="identityResult"></param>
protected virtual void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Commons/Dto/IdAndNameDto.cs
using System;
namespace JFJT.GemStockpiles.Commons.Dto
{
public class IdAndNameDto
{
public int Id { get; set; }
public string Name { get; set; }
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Models/Customers/CustomerCompany.cs
using System;
using JFJT.GemStockpiles.Entities;
namespace JFJT.GemStockpiles.Models.Customers
{
/// <summary>
/// 客户公司信息表
/// </summary>
public class CustomerCompany : FullAudited<Guid>
{
/// <summary>
/// 客户ID
/// </summary>
public int UserId { get; set; }
/// <summary>
/// 公司名称
/// </summary>
public string CompanyName { get; set; }
/// <summary>
/// 公司地址
/// </summary>
public string Address { get; set; }
/// <summary>
/// 公司注册时间
/// </summary>
public DateTime? RegisterTime { get; set; } = DateTime.Now;
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Commons/ICommonAppService.cs
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Abp.Application.Services;
using JFJT.GemStockpiles.Users.Dto;
using JFJT.GemStockpiles.Commons.Dto;
namespace JFJT.GemStockpiles.Commons
{
public interface ICommonAppService : IApplicationService
{
/// <summary>
/// 系统用户语言切换
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task ChangeLanguage(ChangeUserLanguageDto input);
/// <summary>
/// 系统用户密码修改
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task ChangePassword(ChangePasswordDto input);
/// <summary>
/// 系统用户个人信息修改
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task<UserDto> UpdateUserInfo(ChangeUserInfoDto input);
/// <summary>
/// 文件上传
/// </summary>
/// <param name="file"></param>
/// <param name="uploadType"></param>
/// <param name="fileType"></param>
/// <returns></returns>
Task<UploadFileResultDto> UploadFile(IFormFile file, int uploadType, int fileType);
}
}
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Application/Points/PointLogs/Dto/PointLogDto.cs
using System;
using Abp.AutoMapper;
using Abp.Application.Services.Dto;
using JFJT.GemStockpiles.Enums;
using JFJT.GemStockpiles.Models.Points;
namespace JFJT.GemStockpiles.Points.PointLogs.Dto
{
/// <summary>
/// 积分日志DTO
/// </summary>
[AutoMap(typeof(PointLog))]
public class PointLogDto : EntityDto<Guid>
{
/// <summary>
/// 会员ID
/// </summary>
public int MemberId { get; set; }
/// <summary>
/// 动作类型
/// </summary>
public PointActionEnum ActionType { get; set; } = PointActionEnum.Upload;
/// <summary>
/// 动作描述
/// </summary>
public string ActionDesc { get; set; }
/// <summary>
/// 动作时间
/// </summary>
public DateTime ActionTime { get; set; } = System.DateTime.Now;
}
}
<file_sep>/vue/src/store/modules/product/category.js
import Ajax from '@/libs/ajax';
import Util from '@/libs/util.js';
const category={
namespaced: true,
state: {
totalCount: 0,
currentPage: 1,
pageSize: 10,
list: [],
loading: false,
editUser: null,
categoryTree:[],
cascaderCategory:[],
selectAttrList:[]
},
mutations: {
setCurrentPage(state, page) {
state.currentPage = page;
},
setPageSize(state, pageSize) {
state.pageSize = pageSize;
},
edit(state, user) {
state.editUser = user;
},
setAttrList(state, list) {
state.selectAttrList = list;
}
},
actions: {
async getAll(context, payload) {
context.state.loading = true;
let response = await Ajax.get('/api/services/app/Category/GetAll', {params: payload.data});
context.state.loading = false;
let page = response.data.result;
context.state.totalCount = page.totalCount;
context.state.list = page.items;
},
async get(context, payload) {
let response = await Ajax.get('/api/services/app/Category/Get?Id=' + payload.id);
return response.data.result;
},
async getCategory(context, payload) {
let response = await Ajax.get('/api/services/app/Category/GetParent');
return response.data.result;
},
async getTreeCategory(context) {
let response = await Ajax.get('/api/services/app/Category/GetTreeCategory');
context.state.categoryTree = response.data.result.items;
},
async getCascaderCategory(context) {
let response = await Ajax.get('/api/services/app/Category/GetCascaderCategory');
// 删除空children节点
context.state.cascaderCategory = Util.removeNullChildrenNode(response.data.result.items);
},
async create(context, payload) {
return await Ajax.post('/api/services/app/Category/Create', payload.data);
},
async update(context, payload) {
return await Ajax.put('/api/services/app/Category/Update', payload.data);
},
async delete(context, payload) {
return await Ajax.delete('/api/services/app/Category/Delete?Id=' + payload.data.id);
}
}
}
export default category;<file_sep>/README.md
# 测试
### 后端采用.net core+abp 前端vue+iview
1 asp.net EntityFrameworkCore,生成数据库
> 1.Enable-Migrations-EnableAutomaticMigrations
> 2.Add-Migration InitialCreate
> 3.Update-Database -Verbose
2 启动Web.Core
3 vscode启动vue文件夹下
> npm run dev
4 初始账户:admin 密码:<PASSWORD>
相关:
[ABP](https://github.com/aspnetboilerplate/aspnetboilerplate),[iview](https://github.com/iview/iview/),[iview-admin](https://github.com/iview/iview-admin)
<file_sep>/asp.net-core/src/JFJT.GemStockpiles.Core/Enums/ProductSaleStateEnum.cs
using System;
namespace JFJT.GemStockpiles.Enums
{
/// <summary>
/// 产品销售状态
/// </summary>
public enum ProductSaleStateEnum
{
/// <summary>
/// 下架
/// </summary>
OffShelves = 10,
/// <summary>
/// 上架
/// </summary>
OnSale = 20,
/// <summary>
/// 卖完了
/// </summary>
SoldOut = 30
}
}
| a46522c61c7ef37def53e00c1c71937883286881 | [
"JavaScript",
"C#",
"Markdown"
] | 92 | JavaScript | yung-chu/GemStockpiles | 77a3af0eb3bde320bb7d7294d7defee02667e49a | 732e73ed48e1e843a0a74505dc8452f54894cd47 |
refs/heads/master | <repo_name>RomanAyalew/Angular<file_sep>/src/app/tv-show-search/tv-show-search.component.ts
import { Component, OnInit, Output,EventEmitter } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { TvShowService } from '../tv-show/tv-show.service';
import { debounceTime } from 'rxjs/operators';
@Component({
selector: 'app-tv-show-search',
templateUrl: './tv-show-search.component.html',
styleUrls: ['./tv-show-search.component.css']
})
export class TvShowSearchComponent implements OnInit {
@Output() searchEvent = new EventEmitter<string>();
search = new FormControl('',[Validators.minLength(3)])
constructor(private tvshowservice : TvShowService) { }
ngOnInit() {
this.search.valueChanges.pipe(debounceTime(1000)).subscribe((searchValue : string) => {
if(!this.search.invalid){
this.searchEvent.emit(searchValue);
}
})
}
getErrorMessage(){
return this.search.hasError('minlength') ? 'Type three or more characters in the search bar' : '';
}
}
<file_sep>/src/app/itvshow-details.ts
export interface ITVShowDetails {
title: string
image: string
description: string
rating: number
genre: string
id: number
cast: any
}
<file_sep>/src/app/tv-show/tv-show.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { generate } from 'rxjs';
import { environment } from 'src/environments/environment';
import { ITVShowDetails } from '../itvshow-details';
import {map} from 'rxjs/operators';
import { TvShowSearchComponent } from '../tv-show-search/tv-show-search.component';
interface ITvShow{
name:string,
id:number,
genres:string,
summary:string,
image:{
original:string
},
rating:{
average:number
},
cast:string
}
@Injectable({
providedIn: 'root'
})
export class TvShowService {
constructor(private httpClient:HttpClient) {}
getTvShow(search:string){
return this.httpClient.get<ITvShow>(`${environment.baseUrl}api.tvmaze.com/singlesearch/shows?q=${search}`).pipe(map(data=>this.transformToITvShowDetails(data)))
}
getCast(id:number){
return this.httpClient.get<ITvShow>(`${environment.baseUrl}api.tvmaze.com/shows/${id}/cast`)
}
private transformToITvShowDetails(data:ITvShow):ITVShowDetails{
return{
title:data.name,
image:data.image.original,
description:data.summary,
rating:data.rating.average,
genre:data.genres,
id:data.id,
cast:data.cast
}
}
}
<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
import { ITVShowDetails } from './itvshow-details';
import { TvShowService } from './tv-show/tv-show.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'tv-maze-app';
loadedCast: Array<object> = [];
finalCast: any[] = [];
constructor(private tvshowservice : TvShowService){
}
currentshow : ITVShowDetails;
doSearch(searchValue){
if(searchValue){
this.loadedCast.length = 0;
this.finalCast.length = 0;
const userInput = searchValue.replace(' ','%20');
this.tvshowservice.getTvShow(userInput).subscribe(data => {
this.tvshowservice.getCast(data.id).subscribe(loadedCast => {
console.log(loadedCast);
for (let prop in loadedCast) {
this.finalCast.push(loadedCast[prop].person.name);
}
console.log(this.finalCast);
data.cast = this.finalCast;
console.log(data);
this.currentshow = data;
});
});
}
}
}
| 583977dc733f35cd894cbff5e6dea700f4831072 | [
"TypeScript"
] | 4 | TypeScript | RomanAyalew/Angular | c65ae4dc59802529085ba375ab778497b7f0394a | a8d6b26d376e5448db33f683bc04498dad1441f1 |
refs/heads/master | <repo_name>ggons/react-advanced<file_sep>/react/src/Root.js
import React from 'react';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension/logOnlyInProduction';
// import reduxPromise from 'redux-promise';
import async from 'middlewares/async';
import stateValidator from 'middlewares/stateValidator';
import reducers from 'reducers';
const composeEnhancers = composeWithDevTools({
// options like actionSanitizer, stateSanitizer
});
const store = createStore(reducers,
composeEnhancers(applyMiddleware(async, stateValidator))
);
const Root = ({ children }) => (
<Provider store={store}>
{ children }
</Provider>
)
export default Root;<file_sep>/react/src/middlewares/async.js
export default ({ dispatch }) => next => action => {
// next middleware
if (!action.payload || !action.payload.then) {
return next(action);
}
action.payload.then(function (response) {
const newAction = { ...action, payload: response };
dispatch(newAction);
})
}
// action -> dispatch -> middleware #1 -> next -> middleware #2 -> next -> ... -> reducers | 683b3f005b39f1d3f5a0ebe6b33794cb56690cb4 | [
"JavaScript"
] | 2 | JavaScript | ggons/react-advanced | 3f816e63d125211935f318b5b2fc1a286c5e4e3f | 01b4d6bac4ba1eb7d9c6b3a48f7ecb48037b2b5f |
refs/heads/master | <repo_name>omelkonian/presentations<file_sep>/[2019.08.20] BitML (SRC Presentation @ ICFP)/Makefile
MAIN=bitml-presentation
STYLE=stylish.fmt
default: all
all: $(MAIN).pdf
redo:
xelatex $(MAIN).tex
$(MAIN).pdf: $(MAIN).tex
xelatex $(MAIN).tex
%.tex : %.lagda $(STYLE) 1-intro.lagda 2-bitml.lagda 3-future.lagda
lhs2TeX --poly -o $@ $<
clean:
rm -f *.aux *.log *.out *.bbl *.lof *.blg *.lot *.pyg *.gz *.toc *.ptb *.dvi *.snm *.nav $(MAIN).tex $(MAIN).pdf
.PHONY: default all clean redo
<file_sep>/[2018.11.04] RHEA (REBLS @ SPLASH)/code/split.java
Stream<Int> st =
Stream.range(1, 10);
st.map(f)
st.filter(g)
<file_sep>/[2018.11.04] RHEA (REBLS @ SPLASH)/code/ros.cpp
bool scanReceived = FALSE, imageReceived = TRUE;
LaserScan scan; Image image;
subscribe<LaserScan>("/scan", scanCallback);
subscribe<Image>("/camera/rgb", imageCallback);
// Main ROS loop
while (ros::ok()) {
if (scanReceived && imageReceived) {
window.show(embedLaser(scan, image));
scanReceived = FALSE; imageReceived = FALSE;
}
ros::spinOnce();
}
// Callback for topic "/scan"
void scanCallback(LaserScan newScan) {
if (!scanReceived) {
scan = newScan;
scanReceived = TRUE;
}
}
// Callback for topic "/camera/rgb"
void imageCallback (Image newImage) {
if (!imageReceived) {
image = new Image(newImage);
imageReceived = TRUE;
}
}
// OpenCV stuff...
Mat embedLaser(LaserScan scan, Image image) { ... }
<file_sep>/[2023.06.15] Program logics for ledgers @ TYPES/Makefile
MAIN=main
PRE=agda.sty $(MAIN).agda-lib preamble.tex
AGDA=agda -i. --latex --latex-dir=. --only-scope-checking
LATEX=xelatex -shell-escape -halt-on-error -interaction=non-stop
.PHONY: default clean
default: $(MAIN).pdf
%.tex : %.lagda
$(AGDA) $<
%.pdf: %.tex $(PRE)
$(LATEX) $<
bibtex $* &> /dev/null
DEPS=$(patsubst %.lagda, %.tex, $(shell find . -type f -name '*.lagda'))
$(MAIN).pdf : $(DEPS)
clean:
rm -rf *.aux *.log *.out *.bbl *.lof *.blg *.lot *.gz *.toc *.ptb *.dvi \
*.pdf *~ *.agdai _build/ \
$(MAIN).tex $(MAIN).pdf $(DEPS)
<file_sep>/[2022.09.19] 3rd Year PhD Review/Makefile
MAIN=3rd-year-report
default: all
all: $(MAIN).pdf
$(MAIN).pdf: $(MAIN).tex 0-diagrams.tex
xelatex -shell-escape -pdf -f -halt-on-error -cd $<
clean:
rm -f *.aux *.log *.out *.bbl *.lof *.blg *.lot *.pyg *.gz *.toc *.ptb *.dvi *.snm *.nav $(MAIN).pdf
.PHONY: default all clean
<file_sep>/[2015.12.29] PL Seminar/code/Hamming.java
Stream.just(1).loop(entry -> mergeSort(
mergeSort(
entry.map(i -> 2 * i),
entry.map(i -> 3 * i)
),
entry.map(i -> 5 * i)
)
)
.startWith(1)
.subscribe(System.out::println);
Stream<Integer> mergeSort(Stream<Integer> s1, Stream<Integer> s2) {
Queue<Integer> queue = new PriorityQueue<>();
return Stream.zip(s1, s2, (i1, i2) -> {
Integer min = Math.min(i1, i2), max = Math.max(i1, i2);
queue.add(max);
if (min < queue.peek())
return min;
else {
queue.add(min);
return queue.poll();
}
}).concatWith(Stream.from(queue));
}<file_sep>/[2020.02.14] The Extended UTXO Model (WTSC @ FC)/Makefile
MAIN=eutxo-presentation
default: all
all: $(MAIN).pdf
$(MAIN).pdf: $(MAIN).tex 0-diagrams.tex 1-intro.tex 2-informal.tex 3-formal.tex 4-expressiveness.tex 5-related.tex
xelatex $(MAIN).tex
clean:
rm -f *.aux *.log *.out *.bbl *.lof *.blg *.lot *.pyg *.gz *.toc *.ptb *.dvi *.snm *.nav $(MAIN).pdf
.PHONY: default all clean
<file_sep>/[2018.11.04] RHEA (REBLS @ SPLASH)/code/chaos.java
Stream
.just(0, 0)
.loop(s -> s.map(f(1.4, .3)))
<file_sep>/[2023.05.15] Program logics for ledgers @ AIM XXXVI/Makefile
MAIN=main
PRE=agda.sty $(MAIN).agda-lib preamble.tex
AGDA=agda -i. --latex --latex-dir=. --only-scope-checking
LATEX=xelatex -shell-escape -halt-on-error # -interaction=batchmode # -pdf -f -cd
.PHONY: default all clean
default: all
all: $(MAIN).pdf
%.tex : %.lagda
$(AGDA) $<
%.pdf: %.tex $(PRE)
$(LATEX) $<
bibtex $* &> /dev/null
$(MAIN).tex : simple.tex simple-example.tex \
partial.tex partial-example.tex \
utxo.tex utxo-example.tex \
autxo.tex autxo-example.tex \
sound-abstraction.tex
clean:
rm -rf *.aux *.log *.out *.bbl *.lof *.blg *.lot *.gz *.toc *.ptb *.dvi \
*.pdf *~ *.agdai _build/ \
$(MAIN).tex \
simple.tex simple-example.tex \
partial.tex partial-example.tex \
utxo.tex utxo-example.tex \
autxo.tex autxo-example.tex \
sound-abstraction.tex
<file_sep>/[2015.12.29] PL Seminar/code/ControlPanel.java
// Sensors
Topic LASER = new Topic("/scan", LaserScan._TYPE);
Topic CAMERA = new Topic("/camera/rgb/image_color", Image._TYPE);
Topic DEPTH = new Topic("/camera/depth/image", Image._TYPE);
Topic TF = new Topic("/tf", TFMessage._TYPE);
// Actuators
Topic CMD = new Topic("/cmd_vel", VelCmd._TYPE);
Stream.setEvaluationStrategy(new RxjavaEvaluationStrategy());
// ROS topics
Stream<Point> laser = Stream.from(LASER).filter(LaserScan::valid).map(LaserScan::getCartesianPoint);
Stream<Mat> image = Stream.<Image>from(CAMERA).map(OpenCV::convertToMat);
Stream<TFMessage> tf = Stream.from(TF);
Stream.<Image>from(DEPTH).map(OpenCV::convertToGrayscale).subscribe(viz::displayDepth);
// Embed laser in color image
Stream.combineLatest(laser, image, (l, im) -> return im.embed(l))
// Detect faces
.sample(100, TimeUnit.MILLISECONDS)
.map(this::faceDetect)
// Display
.subscribe(viz::displayRGB);
// TF frames
tf.take(50).collect(HashMap::new, (map, msg) -> {
List<TransformStamped> transforms = msg.getTransforms();
for (TransformStamped transform : transforms) {
String parent = transform.getHeader().getFrameId();
String child = transform.getChildFrameId();
if (!map.containsKey(parent)) {
Set<String> init = new HashSet<>();
init.add(child);
map.put(parent, init);
} else map.get(parent).add(child);
}
})
.subscribe(viz::displayTF);
// Battery
Stream.interval(2, TimeUnit.SECONDS).map(v -> (100 - v) / 100.0).subscribe(viz::displayBattery);
// Control
Stream.<KeyEvent>from(KEYBOARD).map(CmdVel::new).subscribe(CMD);<file_sep>/[2022.09.08] agda2hs @ IOG Formal Methods/Makefile
MAIN=main
AGDA=agda-erased
TEX=xelatex -shell-escape -pdf -f -halt-on-error -cd
default: all
all: $(MAIN).pdf
%.tex : %.lagda
$(AGDA) -i. --latex --latex-dir . $<
$(MAIN).pdf: $(MAIN).tex
$(TEX) $<
clean:
rm -f *.aux *.log *.out *.bbl *.lof *.blg *.lot *.pyg *.gz *.toc *.ptb *.dvi \
*.snm *.nav *.vrb *.run.xml *blx.bib $(MAIN).tex $(MAIN).pdf
.PHONY: default all clean
<file_sep>/[2015.10.12] NCSR/code/control-data/imper.cpp
void handle_data(float val) {
if (val > threshold)
publish("cmd", act(val));
}
int main() {
ROS.subscribe("sensor", handle_data);
ROS.publish("cmd");
...
}<file_sep>/[2015.10.12] NCSR/code/example/imper.cpp
float arr[4] = {0, 0, 0, 0};
void callback_up(float val) { if (val > 0) arr[0] = val; }
void callback_down(float val) { if (val > 0) arr[1] = val; }
void callback_left(float val) { if (val > 0) arr[2] = val; }
void callback_right(float val) {
if (val > 0) arr[3] = val;
string cmd_ver = "", cmd_hor = "";
if (arr[0] > arr[1]) cmd_ver = "UP"
else if (arr[0] < arr[1]) cmd_ver = "DOWN"
else cmd_vertical = ""
if (arr[2] > arr[3]) cmd_hor = "LEFT"
else if (arr[2] < arr[3]) cmd_hor = "RIGHT"
else cmd_hor = ""
ROS.publish("cmd", cmd_ver + cmd_hor);
}
int main() {
ROS.subscribe("sensor_up", callback_up); ROS.subscribe("sensor_down", callback_down);
ROS.subscribe("sensor_left", callback_left); ROS.subscribe("sensor_right", callback_right);
ROS.publisher("cmd");
...
}<file_sep>/[2018.10.29] RHEA (MCCS @ UU)/code/adhoc/Panel.java
package robot_panel;
import org.rhea_core.Stream;
import org.rhea_core.util.functions.Func0;
import ros_eval.RosEvaluationStrategy;
import ros_eval.RosTopic;
import rx_eval.RxjavaEvaluationStrategy;
import org.opencv.core.*;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.objdetect.CascadeClassifier;
import sensor_msgs.Image;
import sensor_msgs.LaserScan;
import geometry_msgs.TransformStamped;
import tf2_msgs.TFMessage;
import javafx.application.Application;
import java.util.*;
import java.util.concurrent.TimeUnit;
import cv_bridge.CvImage;
import cv_bridge.ImageEncodings;
public class RobotPanel {
static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
static final String CLASSIFIER = "./classifiers/haarcascade_frontalface_default.xml";
static final CascadeClassifier faceDetector = new CascadeClassifier(CLASSIFIER);
// ROS Topics
static final Topic<LaserScan> LASER = new RosTopic<>("/hokuyo_base/scan", LaserScan._TYPE);
static final Topic<Image> CAMERA = new RosTopic<>("/rear_cam/image_raw", Image._TYPE);
static final Topic<TFMessage> TF = new RosTopic<>("/tf", TFMessage._TYPE);
public static void main(String[] args) {
// Visualization setup
new Thread(() -> Application.launch(Visualizer.class)).start();
Visualizer viz = Visualizer.waitForVisualizer();
// RHEA setup
Stream.evaluationStrategy = new RosEvaluationStrategy(
new RxjavaEvaluationStrategy(), "localhost", "myclient"
);
// Laser
Stream<LaserScan> laser = Stream.from(LASER);
// Camera feed
Stream<Mat> camera = Stream.<Image>from(CAMERA)
.map(this::convertImage) // convert images
.sample(400, TimeUnit.MILLISECONDS) // backpressure
.map(this::detectFaces); // detect faces
// TF
Stream<TFMessage> tf = Stream.from(TF);
// Embed laser
Stream.combineLatest(laser, camera, this::embedLaser)
.subscribe(viz::displayRGB);
// TF hierarchy
tf.take(50)
.collect((Func0<HashMap<String, Set<String>>>) HashMap::new, (m, msg) -> {
for (TransformStamped transform : msg.getTransforms()) {
String parent = transform.getHeader().getFrameId();
String child = transform.getChildFrameId();
if (!m.containsKey(parent)) {
Set<String> init = new HashSet<>();
init.add(child);
m.put(parent, init);
}
else m.get(parent).add(child);
}
})
.subscribe(viz::displayTF);
// Battery
Stream.interval(2, TimeUnit.SECONDS)
.map(v -> (100 - v) / 100.0)
.subscribe(viz::displayBattery);
}
private static Mat detectFaces(Mat im) {
if (Visualizer.faceDetection) {
// Operate on gray-scale image
Mat temp = new Mat();
MatOfRect faces = new MatOfRect();
Imgproc.cvtColor(im, temp, Imgproc.COLOR_BGR2GRAY, 3);
faceDetector.detectMultiScale(temp, faces, 1.25, 1, 0,
new Size(im.rows() / 18, im.rows() / 18), new Size(im.rows() / 5, im.cols() / 5));
for (Rect r : faces.toArray())
Imgproc.rectangle(im, new Point(r.x, r.y), new Point(r.x + r.width, r.y + r.height), new Scalar(0, 255, 0));
}
return im;
}
private static Mat embedLaser(LaserScan l, Mat im) {
// Operate on RGB image
int width = im.cols(), height = im.rows();
Point center = new Point(width / 2, height);
float curAngle = l.getAngleMin();
for (float range : l.getRanges()) {
double x = center.x + (width / 2 * range * Math.cos(curAngle + Math.PI / 2));
double y = center.y - (width / l.getRangeMax() * range * Math.sin(curAngle + Math.PI / 2));
if ((Math.abs(curAngle) < 0.3) && (y > height / 2))
Imgproc.line(im, center, new Point(x, y), new Scalar(0, 0, 255));
curAngle += l.getAngleIncrement();
}
return im;
}
private static Mat convertImage(final Image source) {
try {
return CvImage.toCvCopy(source).image;
} catch (Exception e) {
System.err.println(e);
return null;
}
}
}
<file_sep>/[2021.10.11] 2nd Year PhD Review/Makefile
MAIN=2nd-year-report
TEX=
AGDA=agda -i. --latex --latex-dir . --only-scope-checking
SRC=*.tex $(MAIN).bib
default: all
all: $(MAIN).pdf
%.tex : %.lagda
$(AGDA) $<
$(MAIN).pdf: $(MAIN).tex 0-diagrams.tex
xelatex -shell-escape -pdf -f -halt-on-error -cd $<
clean:
rm -f *.aux *.log *.out *.bbl *.lof *.blg *.lot *.pyg *.gz *.toc *.ptb *.dvi *.snm *.nav $(MAIN).pdf
.PHONY: default all clean
<file_sep>/[2020.10.28] Native Custom Tokens in The Extended UTXO Model (RSC @ ISoLA)/Makefile
MAIN=eutxoma-presentation
default: all
all: $(MAIN).pdf
$(MAIN).pdf: $(MAIN).tex\
0-diagrams.tex\
1-intro.tex\
2-eutxo.tex\
3-eutxoma.tex\
4-metatheory.tex\
5-related.tex
xelatex $(MAIN).tex
clean:
rm -f *.aux *.log *.out *.bbl *.lof *.blg *.lot *.pyg *.gz *.toc *.ptb *.dvi *.snm *.nav $(MAIN).pdf
.PHONY: default all clean
<file_sep>/[2019.08.23] Music Grammars (FARM @ ICFP)/Makefile
MAIN=music-grammars-presentation
STYLE=stylish.fmt
default: all
all: $(MAIN).pdf
redo:
xelatex $(MAIN).tex
$(MAIN).pdf: $(MAIN).tex
xelatex $(MAIN).tex
%.tex : %.lhs $(STYLE) 1-intro.lhs 2-ptgg.lhs 3-harmony.lhs 4-melody.lhs 5-rhythm.lhs 6-songs.lhs 7-conclusion.lhs
lhs2TeX --poly -o $@ $<
clean:
rm -f *.aux *.log *.out *.bbl *.lof *.blg *.lot *.pyg *.gz *.toc *.ptb *.dvi *.snm *.nav $(MAIN).tex $(MAIN).pdf
.PHONY: default all clean redo
<file_sep>/[2018.11.04] RHEA (REBLS @ SPLASH)/script.md
INTRO
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Hello everyone, I am Orestis and this is joint work with <NAME>, and is a result of an internship I did in a robotics research lab in Greece and also the topic of my bachelor thesis.
I am also glad to say that we published this paper and I will present it next week in the REBLS workshop at SPLASH in Boston.
And the title is:
"RHEA: ... "
oh, that's a mouthful... But let's first see how the
ANCIENT GREECE
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if you go for a walk in Utrecht and enter the Centraal Museum, you can find this painting by an early 17th century Utrecht painter called <NAME>,
which depicts the ancient greek philosopher Heraclitus.
His most famous quote is "Panta rei" which means (everything flows)" and comes
from the verb ρεω (to flow/stream). This quote nicely summarizes his philosophy, which emphasized the contantly-changing nature of the
world, that everything moves and nothing remains still, and so forth...
In fact, the name of our framework is etymologically derived from the same verb, and it is the name of the daughter of Uranus and Gaia and mother of all Olympian gods!!
So, I have explained how the acronym came to be, and the rest of the talk will
try to convince you that the adjectives that it expanded to are actually justified.
DATAFLOW
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Now a computational model that embodies this philosophy quite faithfully, is the dataflow model.
In contrast to the traditional von-Neumann model, we have a fully-decentralized
set of individual computational nodes that communicate data with each other via the dataflow edges.
We have a complete absense of control-flow structures (like `if` statements)
and no shared state, which makes execution implicitly concurrent!
As an example, we see a simple dataflow graph that calculates the set of natural numbers.
We start with the singular value 0, and then proceed to a feedback loop which increments the numbers by 1.
So, in the output edge we have the sequence of natural numbers.
Now, to see in what way this execution can be parallelized, let's assume on the far right you have an output node that prints its arguments. Tracing the initial value 0, we see that after it leaves the `concat` node it will be processed concurrently by the output node and the increment node.
MOTIVATION
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
There are quite a few application domains which naturally fit the dataflow model.
- `Sensor-based systems`, such as robotics and IoT, are very naturally expressed as dataflow graphs, since you always have sensors that provide continuous streams of information that you process and transform in whatever way, eventually leading to an actuator that will perform actions on the output stream.
- Another application domain is `Big Data`, where you have enormous amount of continuous streams of information (think of tweets or click-streams) and you need to process them in a scalable and efficient manner. There are many dataflow frameworks, such as
+ Apache´s flink
+ Google´s map-reduce which is a degenerate form of a dataflow graph
+ and Microsoft's ReactiveExtensions which was actually developed by our very own Erik Meijer (I think he did a post-doc here, right?).
- We also see a lot of dataflow incluences in `interactive systems`, where you have to respond to user input such as UIs and games.
In the functional programming world, game libraries like Yampa embrace the FRP paradigm, which is very closely related with the dataflow model.
- And an example I should mention due to its high popularity,
is `TensorFlow`, a neural network construction library, where the user immediately writes dataflow graphs (representing neural-nets) and the backend then optimizes them, distibutes them over many devices, CUDA cores, and so forth...
MOTIVATION: ROBOTICS
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Diving a bit deeper in Robotics now, the so called `RPA` where the robot senses information from its environment processses it and then acts on it to change its environment, is basically a dataflow graph.
Moreover, if you look into a `Control Theory` book, you will see a lot of dataflow diagrams inside, such as the famous PID feedback loop controller, which tries to reach a desired value by iteratively calculating an error and trying to minimize that.
ROS
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
On the programming side of things, robotic applications are most oftenly written in the `ROS` (ROS for short), which is a middleware that provides a PubSub kind-of messaging platform for different robots to communicate via messages on named topics. And this again can be viewed as a dataflow graph where the input streams are the topics that clients publish to and the output nodes are the topics that clients listen to.
Now, the problem here is how they program these things!
Here we see an example where we have 2 sensors (1 for the laser scan and 1 for the camera feed of the robot) and you combine them to show images with the laser information embedded in it by drawing them as red lines.
So what you do is subscribe to certain topics and register a callback function for each one, that will be called whenever a message arrives there.
And you have this ugly main loop that you check things, your callbacks use global variables and it's all spaghetti and for larger examples you cannot handle the callback hell that arises (think of early JS days).
RHEA
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
And that's exactly what our framework is trying to overcome, by having the user write in a declarative stream language. This will internally be a dataflow graph that we can then optimize, distribute across multiple machines, and evaluate using one or more EvaluationStrategies.
To make our framework abstract and extensible, all the components here (except the stream language itself) use the so-called Strategy design pattern, where the base library provided the interfaces, and other libraries can provide their own backends.
Our framework is built for the JVM, we mainly support Java or Scala for the Stream language, but of course you can use whatever JVM language you like. And the whole ecosystem resides in a Github organisation called `rhea-flow`, where you have `rhea-core` that provides the stream language, all the pluggable interfaces and some sane defaults, and you other libraries that provide their own strategies. For instance, `rx-eval` evaluates a dataflow graph by translating it to RxJava operations and `ros-eval` knows how to handle ROS topics as source/sink nodes, and so on and so forth.
Up to now, we can say that by the design itself our framework is abstract since it is, in principle, not constained by technical details and allows for maximum flexibility in the implementations.
STREAM LANGUAGE
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Let us see how the Stream language look like.
You have source nodes that provide the initial values, which can also come from a Topic as we said before, and then you have single-input nodes, like `map` here, that transform a single stream of values.
We can also have multiple-input nodes that combine multiple stream, such as `zip` that provides a value from combining an element of each of the incoming streams.
You can also bind a stream to a variable and re-use to allow sharing, and in the graph view you would have split that takes the same stream to two processing nodes.
And lastly, you can have cycles by using the syntax of the loop operator, which I hope it's intuitive. The inner lambda take the so-far constructed graph and continues the pipeline, but its output will be fed back to the merging point, which is always a concat node. So our previous natural numbers example is easily translated to the code on the left.
Now, since our execution is completely demand-driven, these graphs would just sit there and never be evaluated. So the last ingredient is placing a final output node (using the `subscribe` method) that actually acts on the resulting stream and triggers the whole evaluation.
With these kind of nodes, you can build any graph you might want to, and we have many operators that you can use and there is a very nice diagrammatical way to document them, the so-called Marble Diagrams.
You have input streams on the top and the resulting stream on the bottom, and then use colors and numbers to make you point.
An important thing I haven't mentioned is that streams can be finite, but either sending a `COMPLETE` signal or an `ERROR` signal. So here we see that merge just combines the input streams in arbitrary order and completes if either of its input streams completes.
And you have many operators, like `filter`,`takeWhile`,`scan` (which is a fold that emits all its intermediate results), `sampling` to allow for backpressure which means you want to manage the load of your processing pipeline.
OPTIMIZATIONS
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Before evaluating a given dataflow graph, our current default optimization strategy, will apply two stages of semantics-preserving transformations, namely ProactiveFiltering and GranularityAdjustment.
`Proactive filtering`, as the name suggests, tries to move filtering operations as early as possible in the pipeline. And although it might cost us a bit of computation time, it will certainly reduce the amount of data being transfered through dataflow edges, which can actually connect two different devices of the network, hence incurring significant communication overhead.
Just a few demonstrative examples here, a take after a map can always come before without changing the semantics, a filter after a map can be replaced with a filter of the composition and then the map, and we can move a filter after a concat to all of its input streams.
Now, the `NetworkProfilingStrategy` will detect how many resources are available (for instance, CPU cores) and will instruct the `OptimizationStrategy` to try reach this desired granularity. And it does so, by merging nodes when possible, such as replacing two maps with a single map of the composition or inlining maps on the inputs streams of a zip inside the zip node.
APPLICATION: ROBOT PANEL
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Let's see an actual example to make everything clear.
The goal is to monitor a robot by displaying useful information about it in a GUI on your computer, by utilizing the sensor information of 3 ROS topics.
- The `camera` topic that provides the image feed from the robot's camera.
- The `laser` topic that provides depth information.
- And the `tf` topic, which is a bit more complicated. The robot operates on different coordinate systems that form a hierarchy (think of it as scenes contained within other scenes that form some kind of tree). Now the robot emits messages that witness a single parent-child relation in that tree. So it will say this node is the parent of some other node, and after some time, this same node is the parent of another node, etc..
And because we do not have battery information from the sensors, we just mock one by using `interval` that provides the natural numbers in a timely manner.
So let's see the actual code!
I have kept the Visualization in a separate class, for you not to see the gory details of the UI code, that sets up the GUI window, etc...
We start by defining the three topics that we'll use, by setting the topic's name and type of values it carries.
Then we set the RosEvaluationStrategy that knows how to handle ROS topics, and internally uses RxJava to compute the maps, the folds and what have you.
And then we can get the streams out of these topics, where in the camera we need to do a conversion to an image format we can work, apply some backpressure, and run face detection using a trained classifier that will draw boxes around the faces it detects.
What we do now is combine the image and laser streams using the `embedLaser` function that will draw the laser as red lines in the image (let's not go into the details of the OpenCV code that does this). And instead of using `zip` here, we use `combineLatest` that immediately when a new element comes from either stream, will zip it with latest from the other stream. So it is like a more responsive version of `zip`.
And, of course, we subscribe the action to visualize the result.
Then, for the `tf` hierarchy we use collect, which is basically a fold that threads a data structure (in our case a `HashMap`). And after a finite number of observed relations will display it on the GUI.
And finally, the mocked battery that does this naive steady decrease of the battery level.
Let's see it running now!
We have to setup a ROS master server, which acts as the broker in the PubSub system and the `RosEvaluationStrategy` knows how to connect to it.
And because we don't have an actual robot here, we will play recorded data that are kept in the so-called `rosbag` files.
We can see on the right that the hierarchy is displayed properly, the mocked battery is slowly decreasing, we can enable face detection, and the laser lines become smaller as we approach the person.
So, from this example I think we can see that our system is reactive.
APPLICATION: ROBOT HOSPITAL GUIDE
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Let us now see a more heterogeneous example, where we use both a robot and an IoT device. In Iot you have a very similar PubSub middleware like ROS, called MQTT.
Our goal is to have a robot guided patients in different parts of a hospital (such as the cafeteria) and
assuming the robot knows how to do path planning, obstacle avoidance, etc.. we need to be able to adjust its speed according to the position of the patient.
We do so, by having the patient carry a smartphone that emits BLE signals (BLE for short), and the robot having a BLE receiver.
The dataflow graph is rather simple, we have an MQTT topic "ble",
we split this stream of signals, and map the ones that are near to SPEED_UP commands and the ones that are far away to SLOW_DOWN commands, and finally subscribe to the ROS topic, that controls the velocity of the robot's motors.
Now the setup code for this is a bit more involved than the previous example, because we need to have a distribution strategy that will run different parts of the dataflow to different devices, and we now also
need the MqttEvalStrategy to handle the MQTT topic.
We define our two topics, one for ROS and one for MQTT and then define 2 dataflows:
- the first one runs on the patient's smartphone and published its bluetooth signal to the "ble" topic
- and the second one runs on the robot and transforms the proximity information that it listens on the "ble" topic to the actuator commands for the robot's motors.
And in this example, we see how nicely RHEA can be used high-level declarative coordination language that glues together different parts of the system, running on different devices, and so forth...
So the motto here is: "dataflow in the large, and whatever in the small according to your needs"
DISTRIBUTION
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Let's see in a bit more detail how distribution works.
First of all, the granularity adjustment optimization that we saw may not be able to reach the desired number of nodes, so it the DistributionStrategy will now fuse parts of the dataflow graph into singular tasks, that can be run concurrently.
The most important step is to cleverly place this tasks on the network,
making sure that the communication overhead is as small as possible,
while satisfying some hard constraints, such as that the sensor nodes have to placed on a robot with such capabilities.
And this is done again using a PubSub communication platform (in our case Hazelcast), where nodes that were previously connected in the graph, must now communicate with intermediate topics.
And, of course, for this happen we need to serialize values of our Stream, keeping in mind that we should not throw an exception on serialization but rather materialize the stream on departure (that is transfer the complete/error signals as normal values) and de-materialize on arrival.
With these components in place, we can now say that our framework is heterogeneous.
ALGORITHMIC MUSIC
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
And now for something completely different!
So far we did boring stuff, robot controllers, hospitals....
so let's do something a bit more fun!
We will generate music using dataflow programming!
There is already a library that provides the necessary music datatypes, like `Note`, `Scale`, etc...
and in order to be able to use music-specific stream operators, we utilize Scala's implicit conversions feature, where you define a conversion between the imported `Stream` type and a more specialized version that only holds Music values, in which you can now define your domain-specific operators.
But how do we actually generate music? We are gonna use chaotic functions, which is a standard way to generate interesting music without using randomness.
The idea is very simple, a chaotic system is a set of recursive equations (called chaotic if it has a single variable, and complex otherwise) where you start with some initial values and recursively compute the next set of variables.
These systems typically have some parameters (alpha and beta in this example), and they are chaotic system because if you change the parameters or the initial values the output will change drastically.
We can express these systems quite naturally using our stream language, by just initiating the stream with you initial values and the make a feedback loop that recursively calculates the next values using your complex function.
So, let's the code!
We start with these interesting chaotic numeric sequences and then map them to notes and rhythms, constrained to a particular musical scale (in this case, Ab harmonic minor).
We produce two voices, one for the low register and one for the mid,
and assign an instrument to each of them. We can then write the output to a MIDI file, so let's listen to it.
To see a second example, we can also not constraint the notes in any particular to fully utililize the sound spectrum of the chaotic system.
So now, we see these lambdas that always return true which means we have no music-theoretic constraints on the output.
We also use non-typical instruments and apply some effects to get more interesting sounds. Let's see what *this* sounds like!
...It's weird but I like it.
We can now say that the system is extensible, since we managed to move to a completely different domain and use it there.
LIMITATIONS
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
But, of course, there are limitations.
We saw that it is rather difficult to extend the language with domain-specific operators, and more importantly the programmer has more freedom than needed. For example, you could assign to a stream variable multiple times, but this doesn't make any sense.
Moreover, you always have a specific program structure:
- you start with the configuration of your strategies
- you then define a set of disjoint dataflow graphs
- and the function you pass as arguments to higher-order operators like map are, in principle, pure functions without side-effects.
FUTURE WORK
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
There are a lot of things for future work.
- Our optimizations are rather naive, and there is extensive literature on optimizing stream pipelines, so you could implement these ideas as another OptStrategy.
- Node place is currently rather primitive, but there has been recent research on using reinforcement learning to place sequence of operators to specific kinds of devices, by having the computation time as the reward.
- Another great feature that we do not currently support is dynamic reconfiguration, that is being able to how-swap different nodes of the dataflow without having to restart everything.
- As far as error-handling is concerned, we could certainly use a more Erland-style approach, where instead of just propagating errors through the streams, you also monitor certain nodes, and gracefully recover in case of an error.
- Of course, one could implement more backends, for example a TensorFlow one that converts our dataflow representation to the one TensorFlow uses, and then easily integrate in a robotics/IoT application.
ZIRIA
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
One last thing I want to mention is Ziria: a dataflow DSL for wireless systems programming, and more specifically software-defined radios.
What they manage to do, is define a highly declarative language with network-specific operators, that is then compiled to highly-optimized C code using vectorization.
And when they compared to an existing low-level C++ library, they saw that the code for certain task was significantly small (3000 cs 23000 lines of code), while keeping the performance the same!! (which is a great thing, right?)
CONCLUSION
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Because if we look at this pattern a bit more generally, we can see that there are always certain domains that are fixated on low-level techniques while the FP paradigm can nicely overcome this.
And if I want to get one point across in this talk, is that there are always such domains and always such obsolete low-level ways of doing things in it
and, in these cases, we should always strive for higher and higher abstractions.
QUESTIONS
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
And that's all from me. Thank you!
| 27decd598eccfe27244192f3d1abc49162ad75ce | [
"Markdown",
"Java",
"Makefile",
"C++"
] | 18 | Makefile | omelkonian/presentations | 07eb7dffb1a4b83c110ef9b1d9acaac5a48ac98e | fb8e295192fad21ff90b9a0b6928706dd7cb61c4 |
refs/heads/main | <repo_name>rovallec/we-in<file_sep>/src/app/components/links/links.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-links',
templateUrl: './links.component.html',
styleUrls: ['./links.component.css']
})
export class LinksComponent implements OnInit {
items: {}[] = [
{ url: 'https://www.aido.es/estrellas-de-mar/', label: '¿Sabias que...?' },
{ url: 'https://www.instagram.com/nearsolgt/?hl=es-la', label: 'Directorio telefónico Nearsol' },
{ url: 'https://gt.linkedin.com/company/nearsol', label: '8vo aniversario Nearsol' },
{ url: 'https://www.tiktok.com/@nearsolgt/video/6855360985398578438?lang=es&sender_device=pc&sender_web_id=6906306792935753222&is_from_webapp=1', label: 'Nearsol Family' }
];
countries: {}[] = [
{ name: 'USA', checked: 'false'},
{ name: 'Philippines', checked: 'false'},
{ name: 'Mexico', checked: 'false'},
{ name: 'Jamaica', checked: 'false'},
{ name: 'Guatemala', checked: 'true'},
{ name: 'Dominican Republic', checked: 'false'},
{ name: 'Colombia', checked: 'false'}
]
constructor() { }
ngOnInit(): void {
}
}
<file_sep>/src/app/components/blog/blog.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-blog',
templateUrl: './blog.component.html',
styleUrls: ['./blog.component.css']
})
export class BlogComponent implements OnInit {
items: {}[] = [
{ title: 'NEARSOL Core Values Award Winners - Results-Driven', icon: 'Lifestyle', comentary: 'Being a person that is RESULTS-DRIVEN means that you are focused and obsessed with achieving a great outcome. You don’t want to just compete; you want to WIN!', writedby: '<NAME>', date: '10/12/2020', img: 'https://mcusercontent.com/fdf0393668a7b20c2604ca9f0/images/b3283996-c5d2-4a15-aaf8-26e9a126693f.png' },
{ title: 'Friendship day', icon: 'Friendship', comentary: 'Friendship is perhaps the most perfect form of love. Unlike ties with family, friendship is one that is chosen, not inherited. And at Nearsol we promote friendship by celebrating it on its day.', writedby: 'Anonimous Writer', date: '30/07/2020', img: 'https://scontent.fgua3-2.fna.fbcdn.net/v/t1.6435-9/131432553_1517796005076322_6320577936085176741_n.jpg?_nc_cat=103&ccb=1-3&_nc_sid=730e14&_nc_ohc=JAKr7UP6TfgAX_VBvaa&_nc_ht=scontent.fgua3-2.fna&oh=203363f09c562efb09634d52ffb3dace&oe=60A2FB92' },
{ title: '<NAME>', icon: 'Father', comentary: 'Thank you father, because I know that if you exist, life is a safe place. Because I know that you will be watching my steps no matter how far I go. Because I know that I will have your support, whatever I do and I will be where I am. For showing me that life is a challenge, a challenge and a gift ... thank you Dad! Nearsol family. Because being a father is also a blessing, Congratulations!', writedby: '<NAME>', date: '17/07/2020', img: 'https://scontent.fgua3-2.fna.fbcdn.net/v/t1.6435-9/103961029_1356676264521631_7954217515106165473_n.jpg?_nc_cat=104&ccb=1-3&_nc_sid=730e14&_nc_ohc=DhdCYDgxmkYAX83ZZyI&_nc_ht=scontent.fgua3-2.fna&oh=df7f0326e3ab6b8cc92baff69d227faf&oe=60A5D1EB'}
]
icon1: boolean = false;
icon2: boolean = false;
icon3: boolean = false;
icon4: boolean = false;
icon5: boolean = false;
miniicon1: boolean = false;
miniicon2: boolean = false;
miniicon3: boolean = false;
miniicon4: boolean = false;
miniicon5: boolean = false;
constructor() { }
ngOnInit(): void {
}
setIcon1(){
this.icon1 = !this.icon1;
}
setIcon2(){
this.icon2 = !this.icon2;
}
setIcon3(){
this.icon3 = !this.icon3;
}
setIcon4(){
this.icon4 = !this.icon4;
}
setIcon5(){
this.icon5 = !this.icon5;
}
setMiniIcon1(){
this.miniicon1 = !this.miniicon1;
}
setMiniIcon2(){
this.miniicon2 = !this.miniicon2;
}
setMiniIcon3(){
this.miniicon3 = !this.miniicon3;
}
setMiniIcon4(){
this.miniicon4 = !this.miniicon4;
}
setMiniIcon5(){
this.miniicon5 = !this.miniicon5;
}
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatSliderModule } from '@angular/material/slider';
import { CarouselComponent } from './components/carousel/carousel.component';
import { MDBBootstrapModule } from "angular-bootstrap-md";
import { BlogComponent } from './components/blog/blog.component';
import { LinksComponent } from './components/links/links.component';
import { CommentsComponent } from './components/comments/comments.component';
@NgModule({
declarations: [
AppComponent,
CarouselComponent,
BlogComponent,
LinksComponent,
CommentsComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatSliderModule,
MDBBootstrapModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/components/comments/comments.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-comments',
templateUrl: './comments.component.html',
styleUrls: ['./comments.component.css']
})
export class CommentsComponent implements OnInit {
options = [
{ value: '1', label: 'Tag 1' },
{ value: '2', label: 'Tag 2' },
{ value: '3', label: 'Tag 3' },
{ value: '4', label: 'Tag 4' },
{ value: '5', label: 'Tag 5' },
{ value: '6', label: 'Tag 6' }
];
icons = [
{ name: 'laugh-beam'},
{ name: 'grin-alt'},
{ name: 'grimace'},
{ name: 'meh'},
{ name: 'meh-blank'}
]
constructor() { }
ngOnInit(): void {
}
}
| ff95784a1ba45ce2055da7817b216da006d8cbd2 | [
"TypeScript"
] | 4 | TypeScript | rovallec/we-in | a5aa48a50c4c55aa6771b1c1b601faa5d425e36b | dda7c3957bac74b78a236ce7e8844853ca7f1212 |
refs/heads/master | <repo_name>Coddielam/MERN<file_sep>/routes/api/posts.js
const express = require("express");
const router = express.Router();
const auth = require("../../middlewares/auth");
const { check, validationResult } = require("express-validator");
const Post = require("../../models/Post");
const User = require("../../models/Users");
// @route POST api/posts
// @desc Add post
// @access Private
router.post(
"/",
[auth, [check("texts", "Cannot post without text.").not().isEmpty()]],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty())
return res.status(400).json({ errors: errors.array });
// building post object
try {
const user = await User.findById(req.user.id).select("-password");
let newPost = {
user: req.user.id,
texts: req.body.texts,
name: user.name,
avatar: user.avatar,
};
const post = new Post(newPost);
await post.save();
res.json(post);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error.");
}
}
);
// @route GET api/posts
// @desc Get all posts
// @access Private -- because the frontend made it you have to logged in to see the posts
router.get("/", auth, async (req, res) => {
try {
const posts = await Post.find().sort({ date: -1 });
res.json(posts);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error.");
}
});
// @route GET api/posts/:post_id
// @desc Get post by psot id
// @access Private -- because the frontend made it you have to logged in to see the posts
router.get("/:id", auth, async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post) return res.status(404).json({ msg: "Post not found." });
res.json(post);
} catch (err) {
console.error(err.message);
if (err.kind == "ObjectId")
return res.status(404).json({ msg: "Post not found." });
res.status(500).send("Server error.");
}
});
// @route DELETE api/posts/:id
// @desc Delete post
// @access Private
router.delete("/:id", auth, async (req, res) => {
try {
const post = await Post.findById(req.params.id);
// if post doesn't exist
if (!post) return res.status(404).json({ msg: "Post not found." });
// check if user is the user who owns the post
if (post.user.toString() !== req.user.id) {
return res.json({ msg: "Not authorized to remove post." });
}
post.remove();
res.json({ msg: "Post has been removed." });
} catch (err) {
console.error(err);
if (err.kind == "ObjectId")
return res.status(404).json({ msg: "Post not found." });
res.status(500).send("Server error.");
}
});
// @route PUT api/posts/like/:post_id
// @desc Add like to post
// @access Private
router.put("/like/:post_id", auth, async (req, res) => {
try {
// get the post
const post = await Post.findById(req.params.post_id);
// if invalid post id
if (!post) return res.status(404).json({ msg: "Post not found." });
// check if user already liked
const alreadyLiked = post.likes
.map((like) => like.user.toString())
.includes(req.user.id);
// if already liked, remove like
if (alreadyLiked)
return res.status(400).json({ msg: "Post already liked." });
// if not, add like
post.likes.unshift({ user: req.user.id });
await post.save();
res.json(post.likes);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error.");
}
});
// @route PUT api/posts/unlike/:post_id
// @desc Unlike a post
// @access Private
router.put("/unlike/:post_id", auth, async (req, res) => {
try {
// get the post
const post = await Post.findById(req.params.post_id);
// if invalid post id
if (!post) return res.status(404).json({ msg: "Post not found." });
// check if user already liked
const alreadyLiked = post.likes
.map((like) => like.user.toString())
.includes(req.user.id);
// if not already liked
if (!alreadyLiked)
return res.status(400).json({ msg: "Post has not yet been liked." });
// if alreadyLiked, splice
// find index
const postIndex = post.likes
.map((like) => like.toString())
.indexOf(req.params.post_id);
post.likes.splice(postIndex, 1);
await post.save();
res.json(post.likes);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error.");
}
});
// @route POST api/posts/comment/:post_id
// @desc Add comment
// @access Private
router.post(
"/comment/:post_id",
[auth, [check("text", "Cannot post comment without text.").not().isEmpty()]],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty())
return res.status(400).json({ errors: errors.array });
// building post object
try {
const user = await User.findById(req.user.id).select("-password");
let newComment = {
user: req.user.id,
text: req.body.text,
name: user.name,
avatar: user.avatar,
};
const post = await Post.findById(req.params.post_id);
post.comments.unshift(newComment);
await post.save();
res.json(post.comments);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error.");
}
}
);
// @route POST api/posts/comment/:post_id/:comment_id
// @desc Delete comment
// @access Private
router.delete("/comment/:post_id/:comment_id", auth, async (req, res) => {
try {
const post = await Post.findById(req.params.post_id);
// pull out the comment
const comment = post.comments.find(
(comment) => comment.id === req.params.comment_id
);
// if no comment
if (!comment) return res.status(404).json({ msg: "Comment not found." });
// check to make sure the user is the one made the comment
const isCommentOwner = comment.user.toString() === req.user.id;
if (!isCommentOwner)
return res.status(401).json({ msg: "Unauthorized to remove comment." });
const commentIndex = post.comments
.map((comment) => comment._id)
.indexOf(req.params.comment_id);
post.comments.splice(commentIndex, 1);
await post.save();
res.json(post.comments);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error.");
}
});
module.exports = router;
| 48f2e3103b8f8106f7eb4ffb06bfab76fe932942 | [
"JavaScript"
] | 1 | JavaScript | Coddielam/MERN | 0bc61459fa23438a76242dfcc5d043c39805f09d | 8419d1b00fdb75360ac5a1c55984b5408de9fb09 |
refs/heads/master | <file_sep>package za.co.wethinkcode.view;
import java.util.Scanner;
import java.util.List;
import za.co.wethinkcode.model.Game;
import za.co.wethinkcode.controller.GameController;
import za.co.wethinkcode.characters.Hero;
import za.co.wethinkcode.enums.CharacterType;
import za.co.wethinkcode.factories.CharacterFactory;
public class GameView
{
private GameController gameController;
private Hero hero;
private List<Hero> heroesList;
private Game game;
private char[][] map;
public GameView()
{
this.gameController = new GameController();
this.game = new Game();
this.map = game.getMap();
this.heroesList = gameController.getHeroesFromDB();
}
public int userChoice() {
Scanner scanner = new Scanner(System.in);
int choice;
while (true) {
System.out.println("Enter a number corresponding to your choice.");
System.out.println("1. Pick character from database.");
System.out.println("2. Make your own character.");
choice = scanner.nextInt();
if (choice < 1 || choice > 2) {
System.out.println("Invalid option, try again.");
}
else {
break;
}
}
return (choice);
}
/*
public void getUserInput() {
Scanner scanner = new Scanner(System.in);
int choice;
String input;
while (true) {
System.out.println("Enter a number corresponding to your choice.");
System.out.println("1. Pick character from database.");
System.out.println("2. Make your own character.");
input = scanner.nextLine();
try {
choice = Integer.parseInt(input);
if (choice == 1) {
System.out.println("choose a character from the list below.");
heroesList = this.gameController.getHeroesFromDB();
this.hero = chooseHero();
if (this.hero == null) {
System.out.println("Hero not found.");
}
break;
}
else if (choice == 2) {
System.out.println("Make your own character.");
this.hero = this.gameController.makeHero(this.chooseHeroClass());
System.out.println(this.hero);
this.game.setHero(this.hero);
break;
} else {
System.out.println("Voetsek satan. Can't you read instructions?");
break;
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.out.println("Voetsek satan. Can't you read instructions?");
}
}
scanner.close();
}
*/
public Hero makeHero() {
Hero newHero = null;
CharacterType heroType = chooseHeroClass();
try {
newHero =this.gameController.makeHero(heroType);
} catch (Exception e) {
System.out.println("ERROR: could not make the hero.");
}
return (newHero);
}
public Hero chooseHero() {
// Hero newHero;
Scanner scanner = new Scanner(System.in);
int heroID;
for (Hero hero : heroesList) {
System.out.println(hero);
System.out.println();
}
System.out.println("Enter the ID of the hero you want:");
heroID = scanner.nextInt();
for (Hero hero : heroesList) {
if (hero.getHeroID() == heroID) {
return (hero);
}
}
return (null);
}
public void displayHeroes() {
System.out.println("Heroes list:");
for (Hero hero : heroesList ) {
System.out.println(hero);
}
}
public CharacterType chooseHeroClass() {
Scanner scanner = new Scanner(System.in);
String input;
int choice;
while (true) {
System.out.println("Choose a hero class.");
System.out.println("1. Damage class");
System.out.println("2. Flank class");
System.out.println("3. Tank class");
input = scanner.nextLine();
try {
choice = Integer.parseInt(input);
switch (choice) {
case 1:
return (CharacterType.DAMAGE);
case 2:
return (CharacterType.FLANK);
case 3:
return (CharacterType.TANK);
default:
System.out.println("Voetsek wena! can't you see the options you were given?");
}
} catch (Exception ex) {
System.out.println("Voetsek choose again you fool.");
scanner.close();
}
}
}
public void addCharacterToGame(Hero character) {
this.game.addCharacterToMap(character);
}
public void mapNavigation() {
Scanner scanner = new Scanner(System.in);
String move;
System.out.println("Use WASD for navigation or Q to quit:");
while (true) {
move = scanner.next();
System.out.println(move);
if (move.toLowerCase() == "q") {
break;
}
}
}
public void makeMap(Hero hero) {
this.game.generateMap(hero);
}
public int getMapHeight() {
return (this.game.getMapHeight());
}
public int getMapWidth() {
return (this.game.getMapWidth());
}
public char[][] getMap()
{
return (this.game.getMap());
}
public void displayMap() {
this.game.displayMap();
}
public Hero getHero() {
return (this.hero);
}
}<file_sep>package za.co.wethinkcode.model;
import java.util.Random;
// import lombok.val;
import lombok.Getter;
// import lombok.Setter;
import java.util.List;
import za.co.wethinkcode.characters.Hero;
import za.co.wethinkcode.characters.VillainBuilder;
import za.co.wethinkcode.model.Coordinates;
/**
* Game map
*/
public class Game {
List<Hero> villainsList;
char[][] map;
int mapHeight;
int mapWidth;
@Getter
Hero hero;
public Game() {
this.mapHeight = 0;
this.mapWidth = 0;
}
public void setHero(Hero newHero) {
if (this.hero == null) {
this.hero = newHero;
} else {
System.out.println("There is already a hero in the game.");
}
}
public void generateMap(Hero hero) {
this.mapHeight = (hero.getHeroLevel() - 1) * 5 + 10 - (hero.getHeroLevel() % 2);
this.mapWidth = this.mapHeight;
map = new char[mapWidth][mapHeight];
for (int h = 0; h < this.mapHeight; h++) {
for (int w = 0; w < this.mapWidth; w++) {
this.map[h][w] = '*';
}
}
}
public void displayMap() {
if (this.mapHeight == 0 || this.mapWidth == 0) {
System.out.println("Cannot display: map is empty");
} else {
for (int h = 0; h < this.mapHeight; h++) {
for (int w = 0; w < this.mapWidth; w++) {
System.out.print(map[w][h] + " ");
}
System.out.println();
}
}
}
public char[][] getMap() {
return(this.map);
}
public int getMapHeight() {
return (this.mapHeight);
}
public int getMapWidth() {
return (this.mapWidth);
}
public void addVillain(Hero villainHero) {
if (villainsList.contains(villainHero)) {
System.out.println("This villain has already been added.");
} else {
villainsList.add(villainHero);
}
}
public List<Hero> getVillains() {
return (this.villainsList);
}
public void addCharacterToMap(Hero character) {
Random random = new Random();
char value;
if (character.getHeroClass().equals("Villain")) {
value = 'V';
} else {
int y = this.mapHeight / 2;
int x = this.mapWidth / 2;
value = 'H';
this.map[x][y] = value;
return;
}
while (true) {
int x = random.nextInt(this.mapWidth);
int y = random.nextInt(this.mapHeight);
if (x == 0) {
x += 1;
}
if (x == this.mapWidth) {
x -= 2;
}
if (y == 0) {
y += 1;
}
if (y == this.mapHeight) {
y -= 2;
}
if (this.map[x][y] == '*') {
this.map[x][y] = value;
Coordinates position = new Coordinates(x, y);
character.setPosition(position);
break;
}
}
}
}<file_sep>package za.co.wethinkcode.factories;
import za.co.wethinkcode.characters.Hero;
import za.co.wethinkcode.characters.DamageHeroBuilder;
import za.co.wethinkcode.characters.TankHeroBuilder;
import za.co.wethinkcode.characters.VillainBuilder;
import za.co.wethinkcode.characters.FlankHeroBuilder;
import za.co.wethinkcode.enums.CharacterType;
public class CharacterFactory {
private Hero newCharacter;
public CharacterFactory() {
}
public Hero createCharacter(CharacterType type, String name) throws Exception {
switch (type) {
case FLANK:
FlankHeroBuilder flankHeroBuilder = new FlankHeroBuilder();
flankHeroBuilder.buildHeroName(name);
flankHeroBuilder.buildHeroAttack();
flankHeroBuilder.buildHeroClass();
flankHeroBuilder.buildHeroDefense();
flankHeroBuilder.buildHeroExperience();
flankHeroBuilder.buildHeroHitPoints();
flankHeroBuilder.buildHeroLevel();
newCharacter = flankHeroBuilder.getHero();
break;
case DAMAGE:
DamageHeroBuilder dmgBuilder = new DamageHeroBuilder();
dmgBuilder.buildHeroName(name);
dmgBuilder.buildHeroAttack();
dmgBuilder.buildHeroClass();
dmgBuilder.buildHeroDefense();
dmgBuilder.buildHeroExperience();
dmgBuilder.buildHeroHitPoints();
dmgBuilder.buildHeroLevel();
newCharacter = dmgBuilder.getHero();
break;
case TANK:
TankHeroBuilder tankBuidler = new TankHeroBuilder();
tankBuidler.buildHeroName(name);
tankBuidler.buildHeroAttack();
tankBuidler.buildHeroClass();
tankBuidler.buildHeroDefense();
tankBuidler.buildHeroExperience();
tankBuidler.buildHeroHitPoints();
tankBuidler.buildHeroLevel();
newCharacter = tankBuidler.getHero();
break;
case VILLAIN:
VillainBuilder villainBuidler = new VillainBuilder();
villainBuidler.buildHeroName(name);
villainBuidler.buildHeroAttack();
villainBuidler.buildHeroClass();
villainBuidler.buildHeroDefense();
villainBuidler.buildHeroExperience();
villainBuidler.buildHeroHitPoints();
villainBuidler.buildHeroLevel();
newCharacter = villainBuidler.getHero();
break;
default:
throw new Exception("ERROR: Invalid character type");
}
return (newCharacter);
}
}<file_sep>package za.co.wethinkcode.interfaces;
import za.co.wethinkcode.characters.Hero;
public interface HeroBuilder {
public void buildHeroName(String name);
public void buildHeroClass();
public void buildHeroLevel();
public void buildHeroExperience();
public void buildHeroAttack();
public void buildHeroDefense();
public void buildHeroHitPoints();
public Hero getHero();
};<file_sep>package za.co.wethinkcode.characters;
import java.util.Random;
import za.co.wethinkcode.interfaces.HeroBuilder;
public class VillainBuilder implements HeroBuilder
{
private Hero villainHero;
private Random randNumGenerator;
public VillainBuilder()
{
randNumGenerator = new Random();
villainHero = new Hero();
this.villainHero.setHeroID();
}
public void buildHeroName(String name) {
this.villainHero.setHeroName(name);
}
public void buildHeroClass() {
this.villainHero.setHeroClass("Villain");
}
public void buildHeroLevel() {
int level = randNumGenerator.nextInt(5) + 1;
this.villainHero.setHeroLevel(level);
}
public void buildHeroExperience() {
int exp = randNumGenerator.nextInt(100) + 1;
this.villainHero.setHeroExperience(exp);
}
public void buildHeroAttack() {
int attack = randNumGenerator.nextInt(20) + 1;
this.villainHero.setHeroAttack(attack * 100);
}
public void buildHeroDefense() {
int defense = randNumGenerator.nextInt(10) + 1;
this.villainHero.setHeroDefense(defense * 100);
}
public void buildHeroHitPoints() {
int hp = randNumGenerator.nextInt(50) + 1;
this.villainHero.setHeroHitPoints(hp * 100);
}
public Hero getHero() {
return (this.villainHero);
}
} | 07c7c9b30b04e1942e8335d5b0ea39a1c18be6b5 | [
"Java"
] | 5 | Java | Supreme-Zungula/Swingy | 2e8684281c9b31c311ee7bcf4cee7cfed0940365 | bbc588fa4d178dc3c709167378fd54e2921d073d |
refs/heads/master | <file_sep>ARG BUILD_IMAGE_BASE
FROM ${BUILD_IMAGE_BASE}
ARG KMODVER
ARG KVER
RUN mkdir -p /etc/pki/entitlement
COPY pki.key /etc/pki/entitlement/entitlement.pem
COPY pki.key /etc/pki/entitlement/entitlement-key.pem
COPY build_kernel.sh /
WORKDIR /root
RUN yum install -y git-core gcc elfutils-libelf-devel make kmod
RUN git clone --branch n5010/fpga-ofs-dev-5.10-lts https://github.com/OPAE/linux-dfl-backport.git && \
cd linux-dfl-backport && \
git checkout ${KMODVER} && \
grep -l -v -r MODULE_VERSION drivers/ | xargs sed -i '/^MODULE_LICENSE/ s/$/\nMODULE_VERSION(KMODVER);/' && \
cd -
RUN /build_kernel.sh ${KVER} ${KMODVER}
FROM registry.access.redhat.com/ubi8/ubi-minimal
RUN microdnf install kmod
RUN mkdir -p /lib/modules/${KVER}
COPY --from=0 /lib/modules/${KVER} /lib/modules/${KVER}
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
<file_sep>.PHONY: all image push
KMODVER := eea9cbc
IMAGE_REGISTRY ?= quay.io/ryan_raasch
BUILDTOOL ?= docker
DRIVER_TOOLKIT = registry.redhat.io/openshift4/driver-toolkit-rhel8
PKI_PATH ?= $(shell echo $$HOME)/pems/export/entitlement_certificates/pki.key
OCP_KVER_4_6 = 4.18.0-193
OCP_KVER_4_7 = 4.18.0-240
OCP_KVER_4_8 = 4.18.0-305
BUILD_ARGS_OCP_4_6 = --build-arg KVER=$(OCP_KVER_4_6) --build-arg BUILD_IMAGE_BASE=$(DRIVER_TOOLKIT):v4.6.0
BUILD_ARGS_OCP_4_7 = --build-arg KVER=$(OCP_KVER_4_7) --build-arg BUILD_IMAGE_BASE=$(DRIVER_TOOLKIT):v4.7.0
BUILD_ARGS_OCP_4_8 = --build-arg KVER=$(OCP_KVER_4_7) --build-arg BUILD_IMAGE_BASE=$(DRIVER_TOOLKIT):v4.8.0
BUILDTOOL?= docker
all: ocp-4.6 ocp-4.7 ocp-4.8
pem:
cp -v $(PKI_PATH) pki.key
ocp-4.6: pem
$(BUILDTOOL) build . $(BUILD_ARGS_OCP_4_6) -t $(IMAGE_REGISTRY)/dfl-drivercontainer:$(OCP_KVER_4_6)-$(KMODVER)
ocp-4.7: pem
$(BUILDTOOL) build . $(BUILD_ARGS_OCP_4_7) -t $(IMAGE_REGISTRY)/dfl-drivercontainer:$(OCP_KVER_4_7)-$(KMODVER)
ocp-4.8: pem
$(BUILDTOOL) build . $(BUILD_ARGS_OCP_4_8) -t $(IMAGE_REGISTRY)/dfl-drivercontainer:$(OCP_KVER_4_8)-$(KMODVER)
push:
$(BUILDTOOL) push $(IMAGE_REGISTRY)/dfl-drivercontainer:$(OCP_KVER_4_6)-$(KMODVER)
$(BUILDTOOL) push $(IMAGE_REGISTRY)/dfl-drivercontainer:$(OCP_KVER_4_7)-$(KMODVER)
$(BUILDTOOL) push $(IMAGE_REGISTRY)/dfl-drivercontainer:$(OCP_KVER_4_8)-$(KMODVER)
<file_sep>#!/bin/bash
export KERNEL=$(basename /usr/src/kernels/${1}*)
export KERNELDIR=/lib/modules/$KERNEL/build
export KMODVER=${2}
if [ ! -e $KERNELDIR ] ; then
mkdir -p /lib/modules/$KERNEL
ln -s /usr/src/kernels/$KERNEL
/lib/modules/$KERNEL/build;
fi
rm -rf /lib/modules/${KVER}/kernel
make -C linux-dfl-backport "EXTRA_CFLAGS=-DKMODVER=\\\"${KMODVER}\\\"" -j4
make -C linux-dfl-backport install -j4
depmod -a ${KERNEL}
| 5245d0a7ada965bb7e60ff38d26b5bec66c7a59b | [
"Makefile",
"Dockerfile",
"Shell"
] | 3 | Dockerfile | rmr-silicom/dfl-drivercontainer | 5b5cb08aef7dd721fddf3e626013af750bd30164 | 389528bd1b0f08006b85fcf382d03ace67933b87 |
refs/heads/master | <repo_name>lamhoyannn/2017<file_sep>/README.md
# MATH 210 Introduction to Mathematical Computing
MATH 210 at the [University of British Columbia](http://www.math.ubc.ca) is an introduction to scientific computing in Python. We will start with basic Python programming including datatypes, logical statements, loops and functions and then focus on the scientific computing packages NumPy, SciPy, matplotlib and pandas. We will use these packages to solve problems in calculus, linear algebra, differential equations, statistics and data visualization.
### Lecture Notes
* Week 1
* Introduction to Jupyter notebooks, Markdown and LaTeX -- [January 6, 2017](notes-week-01/notes-2017-01-06.ipynb)
* More LaTeX -- [January 9, 2017](notes-week-01/notes-2017-01-09.ipynb)
* Basic Python: datatypes `int` and `float` -- [January 11, 2017](notes-week-01/notes-2017-01-11.ipynb)
* Basic Python: integers, floats, lists, tuples; list comprehensions; builtin functions -- [January 13, 2017](notes-week-01/notes-2017-01-13.ipynb)
* Week 2
* More Python dataypes, logic and if statements -- [January 16, 2017](notes-week-02/notes-2017-01-16.ipynb)
* Functions -- [January 18, 2017](notes-week-02/notes-2017-01-18.ipynb)
* Functions and for loops -- [January 20, 2017](notes-week-02/notes-2017-01-20.ipynb)
* Week 3
* For loops and while loops -- [January 23, 2017](notes-week-03/notes-2017-01-23.ipynb)
* More example using for loops -- [January 25, 2017](notes-week-03/notes-2017-01-25.ipynb)
* Python modules and packages; Scientific computing packages in Python -- [January 27, 2017](notes-week-03/notes-2017-01-27.ipynb)
* Week 4
* Introduction to NumPy and matplotlib -- [January 30, 2017](notes-week-04/notes-2017-01-30.ipynb)
* NumPy arrays, mathematical functions and plotting with matplotlib -- [February 1, 2017](notes-week-04/notes-2017-02-01.ipynb)
* More plotting examples; NumPy arrays: methods, attributes, indexing and slicing -- [February 3, 2017](notes-week-04/notes-2017-02-03.ipynb)
* Week 5
* `pyplot` commands, subplots, and scatter and bar plots -- [February 6, 2017](notes-week-05/notes-2017-02-06.ipynb)
* Plotting in 3D with mplot3d -- [February 8, 2017](notes-week-05/notes-2017-02-08.ipynb)
* More 3D plotting; miscellaneous topics: functions with keyword arguments, default values, and more list comprehensions -- [February 10, 2017](notes-week-05/notes-2017-02-10.ipynb)
* Week 6
* Review: number theory, sequences, series, solving equations -- [February 15, 2017](notes-week-06/notes-2017-02-15.ipynb)
* *Reading week*
* Week 7
* Definite integrals, Riemann sums and the trapezoid rule -- [February 27, 2017](notes-week-07/notes-2017-02-27.ipynb)
* Trapezoid rule, Simpson's rule and QUADPACK -- [March 1, 2017](notes-week-07/notes-2017-03-01.ipynb)
* More definite integrals; Numerical differentiation -- [March 3, 2017](notes-week-07/notes-2017-03-03.ipynb)
* Week 8
* More numerical differentiation; Linear algebra with SciPy, matrix multiplication and solving linear equations -- [March 6, 2017](notes-week-08/notes-2017-03-06.ipynb)
* More linear algebra: determinant, transpose, trace, eigenvectors and eigenvalues -- [March 8, 2017](notes-week-08/notes-2017-03-08.ipynb)
* More linear algebra: matrix powers and projections -- [March 10, 2017](notes-week-08/notes-2017-03-10.ipynb)
* Week 9
* Applications: Least squares linear regression -- [March 13, 2017](notes-week-09/notes-2017-03-13.ipynb)
* More about NumPy arrays; LU factorization -- [March 15, 2017](notes-week-09/notes-2017-03-15.ipynb)
* Numerical solutions of first order ODEs in SciPy -- [March 17, 2017](notes-week-09/notes-2017-03-17.ipynb)
* Week 10
* Solving first and second order ODEs with SciPy -- [March 20, 2017](notes-week-10/notes-2017-03-20.ipynb)
* More solving linear/nonlinear systems of ODEs with SciPy -- [March 22, 2017](notes-week-10/notes-2017-03-22.ipynb)
* Planetary orbits -- [March 24, 2017](notes-week-10/notes-2017-03-24.ipynb)
* Week 11
* Introduction to pandas; Canada population data -- [March 27, 2017](notes-week-11/notes-2017-03-27.ipynb)
* Exploring the World Bank Databank -- [March 29, 2017](notes-week-11/notes-2017-03-29.ipynb)
* Wind speed and temperature at the Vancouver airport; Vancouver crime data -- [March 31, 2017](notes-week-11/notes-2017-03-31.ipynb)
* Week 12
* Building .csv files from text; NBA Stats via [basketball-reference.com](http://www.basketball-reference.com/) -- [April 3, 2017](notes-week-12/notes-2017-04-03.ipynb)
* Federal Electoral District Tax Statistics -- [April 5, 2017](notes-week-12/notes-2017-04-05.ipynb)<file_sep>/notes-week-03/number_theory.py
# number_theory.py
# A module containing functions related to number theory
# UBC Math 210 Introduction to Mathematical Computing
# January 27, 2017
def factorial(N):
"""Compute N!=N(N-1) ... (2)(1)."""
# Initialize the outpout variable to 1
product = 1
for n in range(2,N + 1):
# Update the output variable
product = product * n
return product
def n_choose_k(N,K):
"""Compute N choose K."""
return factorial(N) // (factorial(N - K) * factorial(K))
def divisors(N):
"""Return the list of divisors of N."""
# Initialize the list of divisors
divisor_list = [1]
# Check division by d for d <= N/2
for d in range(2,N // 2 + 1):
if N % d == 0:
divisor_list.append(d)
divisor_list.append(N)
return divisor_list
def is_square(N):
"""Determine is N is square."""
return N == round(N**(0.5))**2
def rep_as_squares(N):
"""Find all representations of N as a sum of squares a**2 + b**2 = N."""
reps = []
stop = int((N/2)**0.5) + 1 # a must be less than \sqrt{N/2}
for a in range(1,stop):
b_squared = N - a**2
if is_square(b_squared):
b = round((b_squared)**(0.5))
reps.append([a,b])
return reps
def collatz(a):
"""Compute the Collatz sequence starting at a."""
# Initialze the sequence with the fist value a.
x_list = [a]
# Continue computing values in the sequence until we reach 1.
while x_list[-1] != 1:
# Check if the last element in the list is even
if x_list[-1] % 2 == 0:
# Compute and append the new values
x_list.append(x_list[-1] // 2)
else:
# Compute and append the new values
x_list.append(3*x_list[-1] + 1)
return x_list
def is_prime(N):
"Determine whether or not N is a prime number."
if N <= 1:
return False
# N is prime if N is only divisible by 1 and itself
# We should test whether N is divisible by d for all 1 < d < N
for d in range(2,N):
# Check if N is divisible by d
if N % d == 0:
return False
# If we exit the for loop, then N is not divisible by any d
# Therefore N is prime
return True | 1ad87a849266071876cf8b6ecf40ae9a19910d13 | [
"Markdown",
"Python"
] | 2 | Markdown | lamhoyannn/2017 | 6a665662ac8da618214df5577caebc2f3bda54a9 | ae515944586af9d9fdb0dbfe34aaadc4813f6e77 |
refs/heads/main | <repo_name>ibryans/ctf-walkthroughs<file_sep>/tryhackme/rrootme/test.php5
<?php system($_GET[‘q’]);?><file_sep>/README.md
# Capture the flag walkthroughs
All my *Capture the flag* challenges, with walktroughs and created files.
``Tryhackme, Hacthebox, and more...``
<file_sep>/tryhackme/rrootme/readme.md
# Can you Root me? - Tryhackme CTF
``host: 10.10.180.52``
## Reconnaissance
______
NMAP:
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.29 ((Ubuntu))
______
**How many ports are open?**
-> 2
**What version of Apache is runnig?**
-> 2.4.29
**What service is running on port 22?**
-> ssh
**What is the hidden directory?**
-> /panel/
## Getting a shell
Using /panel upload form to upload a reverse shell in php
**test.phtml**
```
$ nc -lnvp 7777
```
After executing the reverse shell by php file, find user.txt
``/var/www/user.txt``
-> THM{y0u_g0t_a_sh3ll}
## Privilege escalation
**Search for files with SUID permission, which file is weird?**
Searching for files with SUID permission
```
$ find . -perm /4000
```
> This will find all files with permission /4000 = SUID
``/usr/bin/python``
Why python can be executed with root privileges?
We can explore that, running a bash by python `os.execl` command, so we have access to a root shell. * Privilege Escalation *
```
$ python -c 'import os; os.execl("/bin/sh", "sh", "-p");'
```
**root.txt**
```
$ find / -type f -iname root.txt 2> /dev/null
```
/root/root.txt
-> THM{pr1v1l3g3_3sc4l4t10n}
| 9647715740fce743bf8ef45caa13bc871e0dbc3d | [
"Markdown",
"PHP"
] | 3 | PHP | ibryans/ctf-walkthroughs | 84814fbf930fe329106fd695716851137f77a6cd | 7e30d207592ab254d4d8febe516e61b9de25d61c |
refs/heads/master | <repo_name>ethansx/Low-Inventory-Email-Alert<file_sep>/app/code/local/GaugeInteractive/LowStockAlert/Model/Observer.php
<?php
class GaugeInteractive_LowStockAlert_Model_Observer
{
const XML_PATH_LOWSTOCKALERT_ENABLED = 'low_qty_alert/settings/enabled';
const XML_PATH_RECIPIENT_EMAIL = 'low_qty_alert/settings/recipient_email';
const XML_PATH_RECIPIENT_NAME = 'low_qty_alert/settings/recipient_name';
const XML_PATH_SENDER_EMAIL = 'low_qty_alert/settings/sender_email';
const XML_PATH_EMAIL_TEMPLATE_ID = 'low_qty_alert/settings/low_inventory_email_template';
const XML_PATH_BCC_LIST = 'low_qty_alert/settings/bcc_list';
const XML_PATH_MIN_QTY_THRESHOLD = 'low_qty_alert/settings/min_qty_threshold';
function checkQuantity($observer)
{
$enabled = Mage::getStoreConfig(self::XML_PATH_LOWSTOCKALERT_ENABLED);
$recipientEmail = Mage::getStoreConfig(self::XML_PATH_RECIPIENT_EMAIL);
$recipientName = Mage::getStoreConfig(self::XML_PATH_RECIPIENT_NAME);
$senderEmail = Mage::getStoreConfig(self::XML_PATH_SENDER_EMAIL);
$emailTemplateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE_ID);
$minQtyThreshold = Mage::getStoreConfig(self::XML_PATH_MIN_QTY_THRESHOLD);
$bccList = Mage::getStoreConfig(self::XML_PATH_BCC_LIST);
if ($enabled) {
$order = $observer->getOrder();
$items = $order->getAllVisibleItems();
foreach ($items as $item) {
$sku = $item->getSku();
$product = Mage::getModel('catalog/product')->load($item->getProductId());
$qty = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();
if ($qty < $minQtyThreshold) {
$bccList = explode(';', $bccList);
// Store all variables in an array
$vars = array(
'sku' => $sku,
'sender_email' => $senderEmail,
'recipient_email' => $recipientEmail,
'recipient_name' => $recipientName,
'email_template_id' => $emailTemplateId,
'qty' => $qty,
'bcc' => $bccList,
);
$this->sendTransactionalEmail($vars);
}
}
}
}
function sendTransactionalEmail($vars)
{
$storeId = Mage::app()->getStore()->getStoreId();
// Set sender information
$senderName = Mage::getStoreConfig('trans_email/ident_support/name');
$sender = array(
'name' => $senderName,
'email' => $vars['sender_email']
);
// Set variables that can be used in email template
$templateVariables = array(
'qty' => $vars['qty'],
'sku' => $vars['sku'],
'customerName' => $vars['recipient_name'],
'customerEmail' => $vars['recipient_email']
);
$translate = Mage::getSingleton('core/translate');
// Send Transactional Email
$send = Mage::getModel('core/email_template');
$send->addBcc($vars['bcc']);
$send->sendTransactional($vars['email_template_id'], $sender, $vars['recipient_email'], $vars['recipient_name'], $templateVariables, $storeId);
$translate->setTranslateInline(true);
Mage::log($vars['sku'] . ' has a qty of ' . $vars['qty'], null, 'ethanLowQty.log');
}
}<file_sep>/app/code/local/GaugeInteractive/LowStockAlert/Helper/Data.php
<?php
/**
* Created by Gauge Interactive
* Date: 3/13/15
* Time: 4:18 PM
*/
class GaugeInteractive_LowStockAlert_Helper_Data extends Mage_Core_Helper_Abstract {
} | 4e581d90c8571cbc7c19de86f45b21ab44e34798 | [
"PHP"
] | 2 | PHP | ethansx/Low-Inventory-Email-Alert | b1670076ee99301d88020c24a6981fdedbe5548c | e8a751bb3a944a147916a306a2fc7517af1126ea |
refs/heads/master | <repo_name>evan10s/wake-me-cgm<file_sep>/README.md
# wake-me-cgm<file_sep>/app/src/main/java/at/str/evan/wakemecgm/MainActivity.java
package at.str.evan.wakemecgm;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.github.mikephil.charting.charts.ScatterChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.realm.implementation.RealmScatterDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import java.util.Date;
import java.util.Locale;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
public class MainActivity extends AppCompatActivity {
private final String TAG = "WAKEMECGM";
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(new NotificationChannel("HIGH_ALERTS", "High BG Alerts", NotificationManager.IMPORTANCE_HIGH));
notificationManager.createNotificationChannel(new NotificationChannel("LOW_ALERTS", "Low BG Alerts", NotificationManager.IMPORTANCE_HIGH));
}
}
final Button confirmAlertBtn = findViewById(R.id.confirm_alert);
confirmAlertBtn.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
if (BgUpdateService.runningAlert != null) {
BgUpdateService.runningAlert.interrupt();
}
}
});
Realm realm = Realm.getDefaultInstance();
final RealmResults<BGReading> last24Hr = realm.where(BGReading.class).greaterThan("timestamp", new Date(System.currentTimeMillis() - 86400 * 1000)).findAll();
final ScatterChart chart = findViewById(R.id.chart);
RealmScatterDataSet<BGReading> dataSet = new RealmScatterDataSet<>(last24Hr, "timeDecimal", "reading");
dataSet.setColor(Color.BLACK);
dataSet.setValueTextColor(Color.BLUE);
dataSet.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet.setScatterShape(ScatterChart.ScatterShape.CIRCLE);
ScatterData lineData = new ScatterData(dataSet);
chart.setData(lineData);
chart.setScaleYEnabled(false);
chart.getLegend().setEnabled(false);
chart.getLegend().setForm(Legend.LegendForm.CIRCLE);
chart.getDescription().setEnabled(false);
chart.setVisibleXRangeMinimum(1);
chart.setVisibleXRangeMaximum(3);
chart.setVisibleXRangeMaximum(24);
lineData.setDrawValues(false);
YAxis rightAxis = chart.getAxisRight();
rightAxis.setAxisMinimum(40);
rightAxis.setAxisMaximum(400);
YAxis leftAxis = chart.getAxisLeft();
leftAxis.setEnabled(false);
XAxis xAxis = chart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setGranularity(1);
IAxisValueFormatter xAxisFormatter = new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
int hours = (int) value;
float mins = value - hours;
int newHours = hours;
Log.i(TAG, "getFormattedValue: " + value);
Log.i(TAG, "getFormattedValue: " + mins);
int minsInt = Math.round(mins * 60);
String AMPM = "AM";
if (hours > 12) {
newHours = hours - 12;
AMPM = "PM";
} else if (hours == 0) {
newHours = 12;
AMPM = "AM";
} else if (hours == 12) {
newHours = 12;
AMPM = "PM";
}
String minsStr = (minsInt < 10) ? "0" + minsInt : "" + minsInt;
return newHours + ":" + minsStr + " " + AMPM;
}
};
xAxis.setValueFormatter(xAxisFormatter);
LimitLine low = new LimitLine(65, "");
low.setLineColor(Color.RED);
low.setLineWidth(1f);
low.setTextSize(12f);
LimitLine high = new LimitLine(240, "");
high.setLineColor(Color.rgb(255,171,0));
high.setLineWidth(1f);
high.setTextSize(12f);
rightAxis.addLimitLine(low);
rightAxis.addLimitLine(high);
chart.invalidate(); // refresh
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.at.str.evan.wakemecgm.BG_DATA",Context.MODE_PRIVATE);
int lastBg = sharedPref.getInt("lastBg", -1);
String lastTrend = sharedPref.getString("lastTrend","");
long startDate = sharedPref.getLong("startDate",-1);
Log.d("WAKEMECGM", "stored prev BG: " + lastBg);
if (startDate == -1) {
SharedPreferences.Editor editor2 = sharedPref.edit();
editor2.putLong("startDate",new Date().getTime());
editor2.apply();
}
RealmChangeListener<Realm> realmListener = new RealmChangeListener<Realm>() {
@Override
public void onChange(Realm realm) {
BGReading lastBGObj = realm.where(BGReading.class).sort("timestamp").findAll().last();
if (lastBGObj != null) {
int bg = (int) lastBGObj.getReading();
String trend = lastBGObj.getTrend();
Log.i(TAG, "onChange: BG reading is " + bg);
Log.i(TAG, "onChange: Trend is " + trend);
updateBGTextView(bg, trend);
chart.notifyDataSetChanged();
chart.invalidate();
}
}
};
realm.addChangeListener(realmListener);
updateBGTextView(lastBg, lastTrend);
}
private void updateBGTextView(int bg, String trend) {
//Sensor stopped, latest_bg=1
//Sensor warm-up, latest_bg=5
TextView lastBgTextView = findViewById(R.id.bg);
if (bg == 1) {
lastBgTextView.setText(R.string.sensor_stopped);
} else if (bg == 5) {
lastBgTextView.setText(R.string.sensor_warmup);
} else if (bg == 39) {
lastBgTextView.setText(R.string.LOW);
} else if (bg >= 40 && bg <= 401) {
lastBgTextView.setText(String.format(Locale.getDefault(), "%d %s", bg, trend));
} else {
lastBgTextView.setText("---");
}
}
}
<file_sep>/app/src/main/java/at/str/evan/wakemecgm/bgUpdateService.java
package at.str.evan.wakemecgm;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.joda.time.DateTime;
import java.util.Date;
import java.util.Map;
import io.realm.Realm;
public class BgUpdateService extends FirebaseMessagingService {
final static String TAG = "WAKEMECGM";
public static Thread runningAlert;
public BgUpdateService() {
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
Log.d("WAKEMECGM", "From: " + remoteMessage.getFrom());
Log.d("WAKEMECGM", remoteMessage.getData().toString());
//save the last received BG value
Context context = getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
"com.at.str.evan.wakemecgm.BG_DATA", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
Map<String, String> msgData = remoteMessage.getData();
int bg = Integer.parseInt(msgData.get("latest_bg"));
String trendVal = msgData.get("trend");
String trendSymbol = "";
String bg_date = msgData.get("display_time");
DateTime bgTime = new DateTime(bg_date);
DateTime now = new DateTime();
if (bgTime.isBefore(now.minusMinutes(6))) {
Log.i(TAG, "onMessageReceived: Ignoring old reading");
return;
}
Runnable alertSound = new Runnable() {
@Override
public void run() {
Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.lowalert));
Log.d("wakemecgm","running");
while(!Thread.interrupted()) {
ringtone.play();
try {
Thread.sleep(4500);
} catch (InterruptedException e) {
ringtone.stop();
Thread.currentThread().interrupt();
}
}
}
};
runningAlert = new Thread (alertSound);
if (bg <= 65 && bg >= 39) { //39 is the lowest reading - when CGM displays LOW, but 30 is used
runningAlert.start();
}
switch (trendVal) {
case "FLAT":
trendSymbol = "→";
break;
case "UP_45":
trendSymbol = "↗";
break;
case "SINGLE_UP":
trendSymbol = "↑";
break;
case "DOUBLE_UP":
trendSymbol = "⇈";
break;
case "DOWN_45":
trendSymbol = "↘";
break;
case "SINGLE_DOWN":
trendSymbol = "↓";
break;
case "DOUBLE_DOWN":
trendSymbol = "⇊";
break;
case "NOT_COMPUTABLE":
trendSymbol = "";
break;
}
editor.putInt("lastBg", bg);
editor.putString("lastTrend",trendSymbol);
Log.d("WAKEMECGM", "now: " + bg_date);
editor.putString("lastReadDate",bg_date);
editor.apply();
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
BGReading bgReading = realm.createObject(BGReading.class); // Create a new object
long startDate = sharedPref.getLong("startDate",-1);
bgReading.setTimestamp(new Date(),startDate); //TODO: use the date passed in the object
bgReading.setReading(bg);
bgReading.setTrend(trendSymbol);
realm.commitTransaction();
String title = bg + " " + trendSymbol;
title = title.trim(); //remove the space after BG if the trend is NOT_COMPUTABLE
String body;
//only notify for out-of-range BGs
if (bg <= 65 && bg >= 39) {
body = "Low BG";
notifyLow(title, body);
} else if (bg >= 240) {
body = "High BG";
notifyHigh(title, body);
}
}
private NotificationCompat.Builder constructNotification(String title, String body, String channelId) {
Log.i(TAG, "constructNotification: entered");
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
return new NotificationCompat.Builder(getApplicationContext(), channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setLights(Color.BLUE, 1, 1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
}
private void notifyLow(String messageTitle, String messageBody) {
long[] vibrateLow = {400, 400, 400, 400, 400, 400};
NotificationCompat.Builder notificationBuilder = constructNotification(messageTitle, messageBody, "LOW_ALERTS");
notificationBuilder.setVibrate(vibrateLow)
.setColor(Color.RED);
Notification bgAlert = notificationBuilder.build();
bgAlert.flags = Notification.FLAG_INSISTENT;
sendNotification(notificationBuilder);
}
private void notifyHigh(String messageTitle, String messageBody) {
long[] vibrateHigh = {500, 500, 500, 500};
NotificationCompat.Builder notificationBuilder = constructNotification(messageTitle, messageBody, "HIGH_ALERTS");
notificationBuilder.setVibrate(vibrateHigh)
.setColor(Color.YELLOW);
sendNotification(notificationBuilder);
}
private void sendNotification(NotificationCompat.Builder notificationBuilder) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
}
| f106f8319fe8e91c002dfe6c16a2ab4a0f6db035 | [
"Markdown",
"Java"
] | 3 | Markdown | evan10s/wake-me-cgm | c841c76408e8cf5b5a577e57f2e9608b86fd61a9 | d82a21c10dca7862901db5098e8309e56bd63146 |
refs/heads/master | <file_sep>// object Literal
// let mahasiswa1 = {
// nama: "indra",
// energi: 10,
// makan: function(porsi) {
// this.energi = this.energi + porsi;
// console.log(`Halo ${this.nama}, selamat makan`);
// }
// };
// let mahasiswa2 = {
// nama: "indri",
// energi: 20,
// makan: function(porsi) {
// this.energi = this.energi + porsi;
// console.log(`Halo ${this.nama}, selamat makan`);
// }
// };
// Function declaration
// function Mahasiswa(nama, energi) {
// let mahasiswa = {};
// mahasiswa.nama = nama;
// mahasiswa.energi = energi;
// mahasiswa.makan = function(porsi) {
// this.energi += porsi;
// console.log(`Hallo ${this.nama}, Selamat makan`);
// };
// mahasiswa.main = function(jam) {
// this.energi -= jam;
// console.log(`Hallo ${this.nama}, Selamat bermain`);
// };
// return mahasiswa;
// }
// let indra = Mahasiswa("indra", 10);
// let indri = Mahasiswa("indri", 15);
// construtor
function Mahasiswa(nama, energi) {
this.nama = nama;
this.energi = energi;
this.makan = function(porsi) {
this.energi += porsi;
console.log(`Hallo ${this.nama}, Selamat makan`);
};
this.main = function(jam) {
this.energi -= jam;
console.log(`Hallo ${this.nama}, Selamat bermain`);
};
}
let indra = new Mahasiswa("indra", 10);
let indri = new Mahasiswa("indri", 20);
<file_sep>// ambil semua elemen video
const videos = Array.from(document.querySelectorAll("[data-duration]"));
// console.log(video);
// pilih hanya yang 'Javascript lanjutan'
let vidJavascript = videos
.filter((video) => video.textContent.includes("JAVASCRIPT LANJUTAN"))
// console.log(vidJavascript);
// ambil durasi masing masing video
.map((item) => item.dataset.duration)
// ubah durasi menjadi float, ubah menit menjadi detik
.map((waktu) => {
//10:30 -> [10, 30] split
const parts = waktu.split(":").map((part) => parseFloat(part));
return parts[0] * 60 + parts[1];
})
// jumlahkan semua detik
.reduce((total, detik) => total + detik);
// ubah formatnya jadi jam menit detik
const jam = Math.floor(vidJavascript / 3600);
vidJavascript = vidJavascript - jam * 3600;
const menit = Math.floor(vidJavascript / 60);
const detik = vidJavascript - menit * 60;
// dimpan di DOM
const jumlahVideo = videos.filter((video) =>
video.textContent.includes("JAVASCRIPT LANJUTAN")
).length;
const tVideo = document.querySelector(".jumlah-video");
tVideo.textContent = `${jumlahVideo} video`;
const tDurasi = document.querySelector(".jumlah-durasi");
tDurasi.textContent = `${jam} jam,${menit} menit, ${detik} detik.`;
console.log(jam, menit, detik);
<file_sep>// for..of
// array
// const mhs = ["indra", "indri", "indira"];
// for (let i = 0; i < mhs.length; i++) {
// console.log(mhs[i]);
// }
// mhs.forEach((m) => console.log(m));
// for (const m of mhs) {
// console.log(m);
// }
// string
// const nama = "indra";
// for (const m of nama) {
// console.log(m);
// }
// const mhs = ["indra", "indri", "indira"];
// mhs.forEach((m, i) => {
// console.log(`${m} adalah mahasiswa ke-${i + 1}`);
// });
// for (const [i, m] of mhs.entries()) {
// console.log(`${m} adalah mahasiswa ke-${i + 1}`);
// }
// Nodelist
// const liNama = document.querySelectorAll(".nama");
// liNama.forEach((n) => console.log(n.textContent));
// for (n of liNama) {
// console.log(n.innerHTML);
// }
// Arguments
// function jumlahkanAngka() {
// let jumlah = 0;
// for (a of arguments) {
// jumlah += a;
// }
// return jumlah;
// }
// console.log(jumlahkanAngka(1, 2, 3, 4, 5));
// For...in
const mhs = {
nama: "indra",
umur: 22,
email: "<EMAIL>",
};
for (m in mhs) {
console.log(mhs[m]);
}
<file_sep>// Destructuring
// function penjumlahPerkalian(a, b) {
// return [a + b, a - b, a * b, a / b];
// }
// function kalkulasi(a, b) {
// return [a + b, a - b, a * b, a / b];
// }
// const jumlah = penjumlahPerkalian(2, 3)[0];
// const kali = penjumlahPerkalian(2, 3)[1];
// const [jumlah, kali] = penjumlahPerkalian(2, 3);
// console.log(jumlah);
// console.log(kali);
// const [jumlah, kurang, kali, bagi = "tidak ada"] = kalkulasi(2, 3);
// console.log(bagi);
// function kalkulasi(a, b) {
// return {
// tambah: a + b,
// kurang: a - b,
// kali: a * b,
// bagi: a / b,
// };
// }
// const { tambah, kali, kurang, bagi } = kalkulasi(2, 3);
// console.log(kali);
// Destructuring function arguments
const mhs1 = {
nama: "<NAME>",
umur: 22,
email: "<EMAIL>",
nilai: {
tugas: 80,
uts: 85,
uas: 75,
},
};
function cetakMhs({ nama, umur, nilai: { tugas, uts, uas } }) {
return `halo, nama saya ${nama}, dan umur saya ${umur}, mempunyai nilai uas ${uas}`;
}
console.log(cetakMhs(mhs1));
<file_sep>const angka = [10, 3, 2, 1, -3, 5, 8, 11, 29, -15];
// const newAngka = [];
// for (let i = 0; i < angka.length; i++) {
// if (angka[i] >= 3) {
// newAngka.push(angka[i]);
// }
// }
// console.log(newAngka);
// filter
// const angka = [10, 3, 2, 1, -3, 5, 8, 11, 29, -15];
// const newAngka = angka.filter(function (a) {
// return a >= 3;
// });
// const newAngka = angka.filter((a) => a >= 3);
// console.log(newAngka);
// Map
// const newAngka = angka.map((a) => a * 2);
// console.log(newAngka);
// reduce
// jumlahkan seluruh elemen pada array
// const newAngka = angka.reduce(
// (accumulator, currenValue) => accumulator + currenValue,
// 0
// );
// console.log(newAngka);
// chaining
// cari angka > 5
// kalikan 3
// jumlahkan
const newAngka = angka
.filter((a) => a > 3)
.map((a) => a * 3)
.reduce((acc, cur) => acc + cur, 0);
console.log(newAngka);
<file_sep>// function expresion
// const tampilNama = function(nama){
// return `Halo, ${nama}`;
// }
// console.log(tampilNama('indra'));
// const tampilNama = (nama, waktu) => {
// return `Halo ${nama}, selamat ${waktu}`;
// };
// console.log(tampilNama("indra", "malam"));
// implicite retrun and one paramater
// const tampilNama = nama => `Halo, ${nama}`;
// console.log(tampilNama("indra"));
// none parameter
// const tampilNama = () => `helo world`;
// console.log(tampilNama());
// example
// let mahasiswa = ["indra", "indira", "saputra"];
// let jumlahHuruf = mahasiswa.map(function(nama) {
// return nama.length;
// });
// console.log(jumlahHuruf());
// let jumlahHuruf = mahasiswa.map(nama => nama.length);
// console.log(jumlahHuruf());
// return to object bungkus lagi gan
// let jumlahHuruf = mahasiswa.map(nama => ({
// nama: nama,
// jmlhHuruf: nama.length
// }));
// console.table(jumlahHuruf);
// Arrow function Lanjutan
// constructor function
// const Mahasiswa = function() {
// this.nama = "indra";
// this.umur = 33;
// this.sayHello = function() {
// console.log(`Hallo ${this.nama}, ${this.umur}`);
// };
// };
// const indra = new Mahasiswa();
// Arrow function
// const Mahasiswa = function() {
// this.nama = "indra";
// this.umur = 33;
// this.sayHello = () => {
// console.log(`Hallo ${this.nama}, ${this.umur}`);
// };
// };
// const indra = new Mahasiswa();
// object literal
// const mhs1 = {
// nama: "indra",
// umur: 14,
// sayHello: function() {
// console.log(`Hallo ${this.nama}, ${this.umur}`);
// }
// };
// console.log(mhs1);
// const Mahasiswa = function() {
// this.nama = "indra";
// this.umur = 14;
// this.sayHello = function() {
// console.log(`Halo nama saya ${this.nama}, umur saya ${this.umur}`);
// };
// setInterval(() => {
// console.log(this.umur++);
// }, 500);
// };
// const indra = new Mahasiswa();
// kasus real life
const box = document.querySelector(".box");
box.addEventListener("click", function() {
let satu = "size";
let dua = "caption";
if (this.classList.contains(satu)) {
[satu, dua] = [dua, satu];
}
this.classList.toggle(satu);
setTimeout(() => {
this.classList.toggle(dua);
}, 600);
});
| ed4c569d3181404bbde40a6be1d26e0708fcf76c | [
"JavaScript"
] | 6 | JavaScript | evriyanaindrasaputra/Belajar-JS | d43f396dbae01a10c5bb5591f7da9c40737b8836 | 2156eb82142201085291a21a373f7207da7f303b |
refs/heads/main | <file_sep># Pet-of-Dreams<file_sep>//Create variables here
var database;
var dog,dogImage,dogImage1,food,foodImage,foodStock,foodRef;
var feed;
var fedTime,lastFed,foodRem;
var foodObj;
var value;
var milkimg,milkbottle;
function preload()
{
dogimage = loadImage("dogImg.png");
dogimage2 = loadImage("dogImg1.png");
milkimg = loadImage("Milk.png");
}
function setup() {
createCanvas(500, 500);
foodObj=new Food();
//foodObj.updateFoodStock(20);
dog = createSprite(250,300);
dog.addImage(dogimage);
dog.scale = 0.2;
database = firebase.database();
//food = database.ref('Food');
//food.on("value",readStock);
feed = createButton("Feed your dog");
feed.position(650,100);
feed.mousePressed(feedDog);
addFood=createButton("Add Food");
addFood.position(450,100);
addFood.mousePressed(addFoods);
milkbottle = createSprite(150,320)
milkbottle.addImage(milkimg)
milkbottle.visible = 0
milkbottle.scale = 0.1
}
function draw() {
background(46, 139, 87);
drawSprites();
console.log(value)
foodObj.display();
fedTime=database.ref('FeedTime');
fedTime.on("value",function(data){
lastFed=data.val();
})
fill("white");
textSize(15);
if(lastFed>=12){
text("Last Fed : "+ lastFed%12 + " PM", 150,25);
}else if(lastFed==0){
text("Last Fed : 12 AM",350,30);
}else{
text("Last Fed : "+ lastFed + " AM", 150,25);
}
fill(4,23,117)
textSize(20)
text(value,400,dog.y-80)
}
function feedDog()
{
foodObj.getFoodStock();
if(foodObj.foodStock<=0)
{
foodObj.foodStock=0;
milkbottle.visible=0;
dog.addImage(dogimage);
}
else{
dog.addImage(dogimage2);
if(foodObj.foodStock===1)
{
milkbottle.visible=0;
dog.addImage(dogimage);
}
else
milkbottle.visible = 1
foodObj.updateFoodStock(foodObj.foodStock-1);
database.ref('/').update({
Food:foodObj.foodStock,
FeedTime:hour()
});
}
}
function addFoods()
{
foodObj.updateFoodStock(foodObj.foodStock+1);
database.ref('/').update({
Food:foodObj.foodStock
});
}
/*function readStock(data){
foodStock = data.val();
}*/
/*function keyPressed(){
if(keyWentDown(UP_ARROW)){
food = database.ref("Food");
foodStock = foodStock - 1;
food.set(foodStock);
dog.addImage(dogimage2);
}
else{
dog.addImage(dogimage)
}
} */
| a9da4f1f8191223966f5ca44596db6b52af6c149 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Lucky2167/Project-39 | 4963c0dfdb21ddfea85ed106be4a9b3de0c5df05 | d1a66910204bffb9a9144adc391c9ee21c6e38bc |
refs/heads/master | <repo_name>oneski/SAAST-Summer-Program-Project<file_sep>/README.md
saast-hw
========
Code written for UPenn's SAAST Computer Science Course
Teacher: Peter-<NAME>
Contributers:
=============
<NAME>
<NAME>
<NAME>
<NAME>
<file_sep>/hw4.py
from drawingpanel import *
import random
'''
def upTriangle(canvas,x,y,z):
canvas.create_polygon([x,y+z,x+z/2,y,x+z,y+z],outline="black", fill="white") #fill with rand colors later
sirP(canvas,x,y,n-1,z)
def sirP(canvas,x,y,n,z):
if(n==0):
pass
elif(n==1):
upTriangle(canvas,x, y,z)
else:
upTriangle(canvas, 3*x/4, y,z/2)
upTriangle(canvas, x/2, y/2, z/2)
upTriangle(canvas, x/4, y, z/2)
def main():
panal = DrawingPanel(500,500)
canvas = panal.canvas
sirP(canvas,100,100,3,100)
main()
'''
def downTriangle(canvas,x,y,z,n):
canvas.create_polygon([x,y+z,x+z/2,y+2*z,x+z,y+z],outline="black", fill="white")
sirP(canvas, x,y,z,n-1)
def background(canvas,x,y,z):
canvas.create_polygon([x,y+z,x+z/2,y,x+z,y+z],outline="black", fill="white")
def sirP(canvas, x, y, z, n):
if n == 0:
#background(canvas, x, y, z)
pass
elif n == 1:
#downTriangle(canvas, x/2, y, z/2)
pass
else:
downTriangle(canvas,x*1.25, y, z/2,n)
downTriangle(canvas,x*.75,y*3, z/2,n)
downTriangle(canvas,x*1.75,y*3,z/2,n)
def main():
panal = DrawingPanel(500,500)
canvas = panal.canvas
background(canvas, 50, 50, 200)
#downTriangle(canvas, 100, 50, 100,0) #center
"""downTriangle(canvas, 125, 50, 50) #top triangle
downTriangle(canvas, 75, 150, 50) #bottom left
downTriangle(canvas, 175, 150, 50) #bottom right"""
sirP(canvas,100,50,100,3)
main()
<file_sep>/pygame/microgames/main.py
from pygame.locals import *
from locals import *
import sys, traceback, pygame
from game import Game
import loader
def main():
""" Entry point of the microgames... game """
pygame.init()
try:
surface = pygame.display.set_mode((WIDTH, HEIGHT))
game = Game()
pygame.display.set_caption('Microgames - SAAST Comp Sci 2013')
clock = pygame.time.Clock()
while not game.finished:
clock.tick(FPS)
game.update()
game.render(surface)
pygame.display.flip()
except Exception as e:
print 'An exception occurred. Terminating the game!'
ty, v, tb = sys.exc_info()
print traceback.print_exception(ty, v, tb)
pygame.quit()
sys.exit()
if __name__ == '__main__':
main()
<file_sep>/pygame/microgames-tester/games/ssb/game.py
# Pygame imports
import pygame, pygame.mixer
from pygame import Surface
from pygame.image import load
from pygame.locals import *
from pygame.mixer import music
from pygame.rect import Rect
from pygame.sprite import Group, Sprite, OrderedUpdates
from pygame.time import get_ticks
# Path imports
from os.path import join
# Random imports
from random import randint, choice
# Microgame-specific imports
import locals
from microgame import Microgame
##### LOADER-REQUIRED FUNCTIONS ################################################
def make_game():
return Super_Saast_Bros()
def title():
return 'SUPER SAAST BROS'
def thumbnail():
return join('games', 'ssb', 'thumbnail.png')
def hint():
return 'Don\'t get hit'
################################################################################
def _load_image(name, x, y):
'''
Loads an image file, returning the surface and rectangle corresponding to
that image at the given location.
'''
try:
image = load(name)
if image.get_alpha is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, msg:
print 'Cannot load image: {}'.format(name)
raise SystemExit, msg
rect = image.get_rect().move(x, y)
return image, rect
##### MODEL CLASSES ############################################################
##### CHARACTER SELECT #########################################################
class Player1_Selector(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'player1_selector.png')
self.image, self.rect = _load_image(imgpath, 300, 600)
self.lvelocity = 0
self.rvelocity = 0
self.uvelocity = 0
self.dvelocity = 0
def update(self):
self.vvelocity = self.uvelocity + self.dvelocity
self.hvelocity = self.lvelocity + self.rvelocity
self.rect = self.rect.move(self.hvelocity, self.vvelocity)
class Player2_Selector(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'player2_selector.png')
self.image, self.rect = _load_image(imgpath, 600, 600)
self.lvelocity = 0
self.rvelocity = 0
self.uvelocity = 0
self.dvelocity = 0
def update(self):
self.vvelocity = self.uvelocity + self.dvelocity
self.hvelocity = self.lvelocity + self.rvelocity
self.rect = self.rect.move(self.hvelocity, self.vvelocity)
class Falco_Selector(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'falco_selector.png')
self.image, self.rect = _load_image(imgpath, 150, 100)
class Fox_Selector(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'fox_selector.png')
self.image, self.rect = _load_image(imgpath, 350, 100)
class Samus_Selector(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'samus_selector.png')
self.image, self.rect = _load_image(imgpath, 550, 100)
class Pit_Selector(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'pit_selector.png')
self.image, self.rect = _load_image(imgpath, 750, 100)
class Snake_Selector(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'snake_selector.png')
self.image, self.rect = _load_image(imgpath, 200, 500)
class Mewtwo_Selector(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'mewtwo_selector.png')
self.image, self.rect = _load_image(imgpath, 450, 500)
class Zelda_Selector(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'zelda_selector.png')
self.image, self.rect = _load_image(imgpath, 700, 500)
###### GAME ####################################################################
class Final_Destination(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'fd.png')
self.image, self.rect = _load_image(imgpath, 100, 500)
class Character(Sprite):
def __init__(self):
Sprite.__init__(self)
self.uvelocity = 0
self.lvelocity = 0
self.rvelocity = 0
self.hvelocity = 0
self.jumps = 2
self.direct = 'right'
self.no_projectile_time = 0
self.percent = 0
self.knockback = 0
def update(self):
self.uvelocity += GRAVITY
if self.knockback > 0:
self.knockback -= KNOCKBACK_RESISTANCE
elif self.knockback < 0:
self.knockback += KNOCKBACK_RESISTANCE
self.hvelocity = self.lvelocity + self.rvelocity + self.knockback
self.rect = self.rect.move(self.hvelocity, self.uvelocity)
def knockback_calc(self, hitbox):
if hitbox.velocity > 0:
self.knockback = int(float(self.percent) / 5) * hitbox.damage
elif hitbox.velocity < 0:
self.knockback = (int(float(self.percent) / 5) * hitbox.damage) * -1
if self.knockback > hitbox.max_knockback:
self.knockback = hitbox.max_knockback
elif self.knockback < (hitbox.max_knockback * -1):
self.knockback = (hitbox.max_knockback * -1)
######## PROJECTILES ###########################################################
class Samus_Charge_Shot(Sprite):
def __init__(self, x, y):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'samus', 'charge_shot.png')
self.image, self.rect = _load_image(imgpath, x, y)
self.velocity = 20
self.damage = 5
self.max_knockback = 130
def update(self):
self.rect = self.rect.move(self.velocity, 0)
class Fox_Laser(Sprite):
def __init__(self, x, y):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'fox', 'laser.png')
self.image, self.rect = _load_image(imgpath, x, y)
self.velocity = 40
self.damage = 3
self.max_knockback = 100
def update(self):
self.rect = self.rect.move(self.velocity, 0)
class Falco_Laser(Sprite):
def __init__(self, x, y):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'falco', 'laser.png')
self.image, self.rect = _load_image(imgpath, x, y)
self.velocity = 40
self.damage = 5
self.max_knockback = 100
def update(self):
self.rect = self.rect.move(self.velocity, 0)
class Mewtwo_Shadow_Ball(Sprite):
def __init__(self, x, y):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'mewtwo', 'shadow_ball.png')
self.image, self.rect = _load_image(imgpath, x, y)
self.velocity = 20
self.uvelocity = 20
self.damage = 4
self.y = y
self.max_knockback = 120
def update(self):
if self.rect.topleft[1] > self.y:
self.uvelocity -= 10
elif self.rect.topleft[1] < self.y:
self.uvelocity += 10
self.rect = self.rect.move(self.velocity, self.uvelocity)
class Zelda_Fireball(Sprite):
def __init__(self, x, y):
Sprite.__init__(self)
imgpath = join('games', 'ssb', 'zelda', 'fireball.png')
self.image, self.rect = _load_image(imgpath, x, y)
self.velocity = 10
self.damage = 5
self.max_knockback = 80
def update(self):
self.rect = self.rect.move(self.velocity, 0)
class Pit_Arrow(Sprite):
def __init__(self, x, y, direct):
Sprite.__init__(self)
if direct == 'right':
imgpath = join('games', 'ssb', 'pit', 'arrowright.png')
elif direct == 'left':
imgpath = join('games', 'ssb', 'pit', 'arrowleft.png')
self.image, self.rect = _load_image(imgpath, x, y)
self.velocity = 60
self.damage = 3
self.max_knockback = 100
def update(self):
self.rect = self.rect.move(self.velocity, 0)
class Snake_Missile(Sprite):
def __init__(self, x, y, direct):
Sprite.__init__(self)
if direct == 'right':
imgpath = join('games', 'ssb', 'snake', 'missileright.png')
if direct == 'left':
imgpath = join('games', 'ssb', 'snake', 'missileleft.png')
self.image, self.rect = _load_image(imgpath, x, y)
self.velocity = 1
self.damage = 4
self.max_knockback = 200
def update(self):
self.velocity = self.velocity * 1.3
self.rect = self.rect.move(self.velocity, 0)
##### CHARACTERS #################################################################
class Fox(Character):
def __init__(self):
Character.__init__(self)
self.run = [join('games', 'ssb', 'fox', 'runright.png'), join('games', 'ssb', 'fox', 'runleft.png')]
self.gun = [join('games', 'ssb', 'fox', 'gunright.png'), join('games', 'ssb', 'fox', 'gunleft.png')]
self.idle = [join('games', 'ssb', 'fox', 'idleright.png'), join('games', 'ssb', 'fox', 'idleleft.png')]
self.image, self.rect = _load_image(self.idle[0], 0, 0)
self.reloadtime = 400
self.projectilecount = 3
self.projectilesound = pygame.mixer.Sound(join('games', 'ssb', 'fox', 'laser.ogg'))
self.jumpsounds = [pygame.mixer.Sound(join('games', 'ssb', 'fox', 'hah.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'fox', 'hah2.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'fox', 'hah3.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'fox', 'shooh.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'fox', 'shuh.ogg'))]
def make_projectile(self, x, y, charac):
if charac.direct == 'right':
self.projectile = Fox_Laser(x, y + 24)
self.projectile.velocity = charac.projectile.velocity
elif charac.direct == 'left':
self.projectile = Fox_Laser(x - 44, y + 24)
self.projectile.velocity = charac.projectile.velocity * (-1)
def projectile_logic(self):
if (self.projectilecount == 0) and ((pygame.time.get_ticks() - self.no_projectile_time) >= self.reloadtime):
self.projectilecount = 3
class Samus(Character):
def __init__(self):
Character.__init__(self)
self.run = [join('games', 'ssb', 'samus', 'runright.png'), join('games', 'ssb', 'samus', 'runleft.png')]
self.gun = [join('games', 'ssb', 'samus', 'gunright.png'), join('games', 'ssb', 'samus', 'gunleft.png')]
self.idle = [join('games', 'ssb', 'samus', 'idleright.png'), join('games', 'ssb', 'samus', 'idleleft.png')]
self.image, self.rect = _load_image(self.idle[0], 0, 0)
self.reloadtime = 1200
self.projectilecount = 1
self.projectilesound = pygame.mixer.Sound(join('games', 'ssb', 'samus', 'charge_shot.ogg'))
self.jumpsounds = [pygame.mixer.Sound(join('games', 'ssb', 'samus', 'hah.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'samus', 'heh.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'samus', 'hoo.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'samus', 'huh.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'samus', 'tu.ogg'))]
def make_projectile(self, x, y, charac):
if charac.direct == 'right':
self.projectile = Samus_Charge_Shot(x, y + 5)
self.projectile.velocity = charac.projectile.velocity
elif charac.direct == 'left':
self.projectile = Samus_Charge_Shot(x - 50, y + 5)
self.projectile.velocity = charac.projectile.velocity * (-1)
def projectile_logic(self):
if (self.projectilecount == 0) and ((pygame.time.get_ticks() - self.no_projectile_time) >= self.reloadtime):
self.projectilecount = 1
class Falco(Character):
def __init__(self):
Character.__init__(self)
self.run = [join('games', 'ssb', 'falco', 'runright.png'), join('games', 'ssb', 'falco', 'runleft.png')]
self.gun = [join('games', 'ssb', 'falco', 'gunright.png'), join('games', 'ssb', 'falco', 'gunleft.png')]
self.idle = [join('games', 'ssb', 'falco', 'idleright.png'), join('games', 'ssb', 'falco', 'idleleft.png')]
self.image, self.rect = _load_image(self.idle[0], 0, 0)
self.reloadtime = 500
self.projectilecount = 1
self.projectilesound = pygame.mixer.Sound(join('games', 'ssb', 'falco', 'laser.ogg'))
self.jumpsounds = [pygame.mixer.Sound(join('games', 'ssb', 'falco', 'huh.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'falco', 'hah.ogg'))]
def make_projectile(self, x, y, charac):
if charac.direct == 'right':
self.projectile = Falco_Laser(x, y + 30)
self.projectile.velocity = charac.projectile.velocity
elif charac.direct == 'left':
self.projectile = Falco_Laser(x - 50, y + 30)
self.projectile.velocity = charac.projectile.velocity * (-1)
def projectile_logic(self):
if (self.projectilecount == 0) and ((pygame.time.get_ticks() - self.no_projectile_time) >= self.reloadtime):
self.projectilecount = 1
class Mewtwo(Character):
def __init__(self):
Character.__init__(self)
self.run = [join('games', 'ssb', 'mewtwo', 'runright.png'), join('games', 'ssb', 'mewtwo', 'runleft.png')]
self.gun = [join('games', 'ssb', 'mewtwo', 'gunright.png'), join('games', 'ssb', 'mewtwo', 'gunleft.png')]
self.idle = [join('games', 'ssb', 'mewtwo', 'idleright.png'), join('games', 'ssb', 'mewtwo', 'idleleft.png')]
self.image, self.rect = _load_image(self.idle[0], 0, 0)
self.reloadtime = 800
self.projectilecount = 1
self.projectilesound = pygame.mixer.Sound(join('games', 'ssb', 'mewtwo', 'shadow_ball.ogg'))
self.jumpsounds = [pygame.mixer.Sound(join('games', 'ssb', 'mewtwo', 'mewtwojump.ogg'))]
def make_projectile(self, x, y, charac):
if charac.direct == 'right':
self.projectile = Mewtwo_Shadow_Ball(x, y)
self.projectile.velocity = charac.projectile.velocity
elif charac.direct == 'left':
self.projectile = Mewtwo_Shadow_Ball(x, y)
self.projectile.velocity = charac.projectile.velocity * (-1)
def projectile_logic(self):
if (self.projectilecount == 0) and ((pygame.time.get_ticks() - self.no_projectile_time) >= self.reloadtime):
self.projectilecount = 1
class Zelda(Character):
def __init__(self):
Character.__init__(self)
self.run = [join('games', 'ssb', 'zelda', 'runright.png'), join('games', 'ssb', 'zelda', 'runleft.png')]
self.gun = [join('games', 'ssb', 'zelda', 'gunright.png'), join('games', 'ssb', 'zelda', 'gunleft.png')]
self.idle = [join('games', 'ssb', 'zelda', 'idleright.png'), join('games', 'ssb', 'zelda', 'idleleft.png')]
self.image, self.rect = _load_image(self.idle[0], 0, 0)
self.reloadtime = 1800
self.projectilecount = 2
self.projectilesound = pygame.mixer.Sound(join('games', 'ssb', 'zelda', 'fireball.ogg'))
self.jumpsounds = [pygame.mixer.Sound(join('games', 'ssb', 'zelda', 'hap.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'zelda', 'hah.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'zelda', 'ha.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'zelda', 'hah.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'zelda', 'hut.ogg'))]
def make_projectile(self, x, y, charac):
if charac.direct == 'right':
self.projectile = Zelda_Fireball(x, y)
self.projectile.velocity = charac.projectile.velocity
elif charac.direct == 'left':
self.projectile = Zelda_Fireball(x, y)
self.projectile.velocity = charac.projectile.velocity * (-1)
def projectile_logic(self):
if (self.projectilecount == 0) and ((pygame.time.get_ticks() - self.no_projectile_time) >= self.reloadtime):
self.projectilecount = 2
class Pit(Character):
def __init__(self):
Character.__init__(self)
self.run = [join('games', 'ssb', 'pit', 'runright.png'), join('games', 'ssb', 'pit', 'runleft.png')]
self.gun = [join('games', 'ssb', 'pit', 'gunright.png'), join('games', 'ssb', 'pit', 'gunleft.png')]
self.idle = [join('games', 'ssb', 'pit', 'idleright.png'), join('games', 'ssb', 'pit', 'idleleft.png')]
self.image, self.rect = _load_image(self.idle[0], 0, 0)
self.reloadtime = 1000
self.projectilecount = 10
self.projectilesound = pygame.mixer.Sound(join('games', 'ssb', 'pit', 'laser.ogg'))
self.jumpsounds = [pygame.mixer.Sound(join('games', 'ssb', 'pit', 'huh.ogg'))]
def make_projectile(self, x, y, charac):
if charac.direct == 'right':
self.projectile = Pit_Arrow(x, y + 25, charac.direct)
self.projectile.velocity = charac.projectile.velocity
elif charac.direct == 'left':
self.projectile = Pit_Arrow(x - 50, y + 25, charac.direct)
self.projectile.velocity = charac.projectile.velocity * (-1)
def projectile_logic(self):
if (self.projectilecount == 0) and ((pygame.time.get_ticks() - self.no_projectile_time) >= self.reloadtime):
self.projectilecount = 10
class Snake(Character):
def __init__(self):
Character.__init__(self)
self.run = [join('games', 'ssb', 'snake', 'runright.png'), join('games', 'ssb', 'snake', 'runleft.png')]
self.gun = [join('games', 'ssb', 'snake', 'gunright.png'), join('games', 'ssb', 'snake', 'gunleft.png')]
self.idle = [join('games', 'ssb', 'snake', 'idleright.png'), join('games', 'ssb', 'snake', 'idleleft.png')]
self.image, self.rect = _load_image(self.idle[0], 0, 0)
self.reloadtime = 1300
self.projectilecount = 2
self.projectilesound = pygame.mixer.Sound(join('games', 'ssb', 'snake', 'gun.ogg'))
self.jumpsounds = [pygame.mixer.Sound(join('games', 'ssb', 'snake', 'huh.ogg')),
pygame.mixer.Sound(join('games', 'ssb', 'snake', 'hah.ogg'))]
def make_projectile(self, x, y, charac):
if charac.direct == 'right':
self.projectile = Snake_Missile(x, y + 24, charac.direct)
self.projectile.velocity = charac.projectile.velocity
elif charac.direct == 'left':
self.projectile = Snake_Missile(x - 44, y + 24, charac.direct)
self.projectile.velocity = charac.projectile.velocity * (-1)
def projectile_logic(self):
if (self.projectilecount == 0) and ((pygame.time.get_ticks() - self.no_projectile_time) >= self.reloadtime):
self.projectilecount = 2
##### MICROGAME CLASS ##########################################################
# TODO: rename this class to your game's name...
GRAVITY = 2
JUMP_BOOST = -25
AIR_JUMP_BOOST = -20
KNOCKBACK_RESISTANCE = 1
class Super_Saast_Bros(Microgame):
def __init__(self):
Microgame.__init__(self)
self.character_select = True
self.player1_selector = Player1_Selector()
self.player2_selector = Player2_Selector()
self.falco = Falco_Selector()
self.fox = Fox_Selector()
self.samus = Samus_Selector()
self.snake = Snake_Selector()
self.pit = Pit_Selector()
self.mewtwo = Mewtwo_Selector()
self.zelda = Zelda_Selector()
self.character_possibilities = Group(self.falco, self.fox, self.samus, self.snake, self.pit, self.mewtwo, self.zelda)
self.sprites = OrderedUpdates(self.falco, self.fox, self.samus, self.snake, self.pit, self.mewtwo, self.zelda, self.player1_selector, self.player2_selector)
self.player1 = Fox()
self.player2 = Falco()
self.p1victory = pygame.image.load(join('games', 'ssb', 'p1_win.png'))
self.p2victory = pygame.image.load(join('games', 'ssb', 'p2_win.png'))
self.platform = Final_Destination()
self.p1win = False
self.p2win = False
self.wincondition = False
self.a_track = False
self.d_track = False
self.lshift_track = False
self.quote_track = False
self.l_track = False
self.rshift_track = False
self.playergroup = Group(self.player1, self.player2)
self.player1_projectiles = Group()
self.player2_projectiles = Group()
def start(self):
pygame.mixer.music.load(join('games', 'ssb', 'battlefield_melee.ogg'))
pygame.mixer.music.play()
def stop(self):
pygame.mixer.music.stop()
def update(self, events):
if self.wincondition == False:
if self.character_select == True:
player_1_character = self.detect_character(self.player1_selector, self.character_possibilities)
player_2_character = self.detect_character(self.player2_selector, self.character_possibilities)
if player_1_character == self.falco:
self.player1 = Falco()
elif player_1_character == self.fox:
self.player1 = Fox()
elif player_1_character == self.samus:
self.player1 = Samus()
elif player_1_character == self.snake:
self.player1 = Snake()
elif player_1_character == self.pit:
self.player1 = Pit()
elif player_1_character == self.mewtwo:
self.player1 = Mewtwo()
elif player_1_character == self.zelda:
self.player1 = Zelda()
if player_2_character == self.falco:
self.player2 = Falco()
elif player_2_character == self.fox:
self.player2 = Fox()
elif player_2_character == self.samus:
self.player2 = Samus()
elif player_2_character == self.snake:
self.player2 = Snake()
elif player_2_character == self.pit:
self.player2 = Pit()
elif player_2_character == self.mewtwo:
self.player2 = Mewtwo()
elif player_2_character == self.zelda:
self.player2 = Zelda()
for event in events:
self.player1_selector_logic(event, self.player1_selector)
self.player2_selector_logic(event, self.player2_selector)
self.character_select_logic(event)
self.sprites.update()
if self.character_select == False:
self.detect_hit(self.player2, self.player1_projectiles)
self.detect_hit(self.player1, self.player2_projectiles)
self.remove_projectiles(self.player1_projectiles, self.sprites)
self.remove_projectiles(self.player2_projectiles, self.sprites)
self.sprites.update()
self.detect_floor()
for event in events:
self.char_logic1(event, self.player1)
self.char_logic2(event, self.player2)
self.player1.projectile_logic()
self.player2.projectile_logic()
y1 = self.player1.rect.top
y2 = self.player2.rect.top
if (y1 > 1200) or (y2 > 1200):
if y1 > 1200:
self.p2win = True
if y2 > 1200:
self.p1win = True
self.sprites.remove(self.platform, self.player1, self.player2)
self.wincondition = True
self.win_time = pygame.time.get_ticks()
elif self.wincondition == True:
if pygame.time.get_ticks() - self.win_time >= 3000:
self.win()
def player1_selector_logic(self, event, player_selector):
if event.type == KEYDOWN:
if event.key == K_w:
player_selector.uvelocity -= 15
elif event.key == K_d:
player_selector.rvelocity += 15
elif event.key == K_s:
player_selector.dvelocity += 15
elif event.key == K_a:
player_selector.lvelocity -= 15
if event.type == KEYUP:
if event.key == K_w:
player_selector.uvelocity += 15
elif event.key == K_d:
player_selector.rvelocity -= 15
elif event.key == K_s:
player_selector.dvelocity -= 15
elif event.key == K_a:
player_selector.lvelocity += 15
def player2_selector_logic(self, event, player_selector):
if event.type == KEYDOWN:
if event.key == K_p:
player_selector.uvelocity -= 15
elif event.key == K_QUOTE:
player_selector.rvelocity += 15
elif event.key == K_SEMICOLON:
player_selector.dvelocity += 15
elif event.key == K_l:
player_selector.lvelocity -= 15
if event.type == KEYUP:
if event.key == K_p:
player_selector.uvelocity += 15
elif event.key == K_QUOTE:
player_selector.rvelocity -= 15
elif event.key == K_SEMICOLON:
player_selector.dvelocity -= 15
elif event.key == K_l:
player_selector.lvelocity += 15
def detect_character(self, player_selector, character_possibilities):
for character in pygame.sprite.spritecollide(player_selector, character_possibilities, False):
return character
def character_select_logic(self, event):
if event.type == KEYDOWN:
if event.key == K_t:
self.character_select = False
self.player1.direct = 'right'
self.player2.direct = 'left'
self.player1.image, self.player1.rect = _load_image(self.player1.idle[0], 250, 350)
self.player2.image, self.player2.rect = _load_image(self.player2.idle[1], 650, 350)
self.sprites.remove(self.falco, self.fox, self.samus, self.snake, self.pit, self.mewtwo, self.zelda, self.player1_selector, self.player2_selector)
self.sprites.add(self.platform, self.player1, self.player2)
self.playergroup.add(self.player1, self.player2)
def detect_floor(self):
for char in pygame.sprite.spritecollide(self.platform, self.playergroup, False):
char.rect.y = (self.platform.rect.topleft[1] - char.rect.height)
char.uvelocity = 0
char.jumps = 2
def detect_hit(self, receiver, hitboxes):
for hitbox in pygame.sprite.spritecollide(receiver, hitboxes, True):
receiver.percent += hitbox.damage
receiver.knockback_calc(hitbox)
def remove_projectiles(self, projectilegroup, spritegroup):
for projectile in projectilegroup:
x_left, _ = projectile.rect.topleft
x_right, _ = projectile.rect.bottomright
if (x_left <= 0) or (x_right >= locals.WIDTH):
spritegroup.remove(projectile)
def render(self, surface):
surface.fill(Color(0, 0, 0))
self.sprites.draw(surface)
if self.p1win == True:
surface.blit(self.p1victory, (0, 0))
elif self.p2win == True:
surface.blit(self.p2victory, (0, 0))
def get_timelimit(self):
return 60
def char_logic1(self, event, charac):
x, y = charac.rect.topleft
if event.type == KEYDOWN:
if event.key == K_w:
self.jump_logic(charac)
elif event.key == K_a:
self.a_track = True
charac.image, charac.rect = _load_image(charac.run[1], x, y)
charac.lvelocity -= 10
charac.direct = 'left'
elif event.key == K_d:
self.d_track = True
charac.rvelocity += 10
charac.image, charac.rect = _load_image(charac.run[0], x, y)
charac.direct = 'right'
elif event.key == K_LSHIFT:
if charac.projectilecount > 0:
charac.projectilesound.play()
self.lshift_track = True
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.gun[0], x, y)
x, y = charac.rect.topright
charac.make_projectile(x, y, charac)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.gun[1], x, y)
x, y = charac.rect.topleft
charac.make_projectile(x, y, charac)
self.sprites.add(charac.projectile)
self.player1_projectiles.add(charac.projectile)
charac.projectilecount -= 1
if charac.projectilecount == 0:
charac.no_projectile_time = pygame.time.get_ticks()
elif event.type == KEYUP:
if event.key == K_a:
charac.lvelocity += 10
self.a_track = False
if self.d_track == False:
if self.lshift_track == False:
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
elif self.lshift_track == True:
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
elif self.d_track == True:
if self.lshift_track == False:
charac.image, charac.rect = _load_image(charac.run[0], x, y)
charac.direct = 'right'
elif self.lshift_track == True:
charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
elif event.key == K_d:
charac.rvelocity -= 10
self.d_track = False
if self.a_track == False:
if self.lshift_track == False:
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
elif self.lshift_track == True:
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
elif self.a_track == True:
if self.lshift_track == False:
charac.image, charac.rect = _load_image(charac.run[1], x, y)
charac.direct = 'left'
elif self.lshift_track == True:
charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
elif event.key == K_LSHIFT:
self.lshift_track = False
if (self.a_track == False) and (self.d_track == False):
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
elif (self.a_track == False) and (self.d_track == True):
charac.image, charac.rect = _load_image(charac.run[0], x, y)
charac.direct = 'right'
elif (self.a_track == True) and (self.d_track == False):
charac.image, charac.rect = _load_image(charac.run[1], x, y)
charac.direct = 'left'
elif (self.a_track == True) and (self.d_track == False):
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.gun[0], x, y)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.gun[1], x, y)
def char_logic2(self, event, charac):
x, y = charac.rect.topleft
if event.type == KEYDOWN:
if event.key == K_p:
self.jump_logic(charac)
elif event.key == K_l:
self.l_track = True
charac.image, charac.rect = _load_image(charac.run[1], x, y)
charac.lvelocity -= 10
charac.direct = 'left'
elif event.key == K_QUOTE:
self.quote_track = True
charac.rvelocity += 10
charac.image, charac.rect = _load_image(charac.run[0], x, y)
charac.direct = 'right'
elif event.key == K_RSHIFT:
if charac.projectilecount > 0:
charac.projectilesound.play()
self.rshift_track = True
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.gun[0], x, y)
x, y = charac.rect.topright
charac.make_projectile(x, y, charac)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.gun[1], x, y)
x, y = charac.rect.topleft
charac.make_projectile(x, y, charac)
self.sprites.add(charac.projectile)
self.player2_projectiles.add(charac.projectile)
charac.projectilecount -= 1
if charac.projectilecount == 0:
charac.no_projectile_time = pygame.time.get_ticks()
elif event.type == KEYUP:
if event.key == K_l:
charac.lvelocity += 10
self.l_track = False
if self.quote_track == False:
if self.rshift_track == False:
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
elif self.rshift_track == True:
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
elif self.quote_track == True:
if self.rshift_track == False:
charac.image, charac.rect = _load_image(charac.run[0], x, y)
charac.direct = 'right'
elif self.rshift_track == True:
charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
elif event.key == K_QUOTE:
charac.rvelocity -= 10
self.quote_track = False
if self.l_track == False:
if self.rshift_track == False:
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
elif self.rshift_track == True:
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
elif self.l_track == True:
if self.rshift_track == False:
charac.image, charac.rect = _load_image(charac.run[1], x, y)
charac.direct = 'left'
elif self.rshift_track == True:
charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
elif event.key == K_RSHIFT:
self.rshift_track = False
if (self.l_track == False) and (self.quote_track == False):
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
elif (self.l_track == False) and (self.quote_track == True):
charac.image, charac.rect = _load_image(charac.run[0], x, y)
charac.direct = 'right'
elif (self.l_track == True) and (self.quote_track == False):
charac.image, charac.rect = _load_image(charac.run[1], x, y)
charac.direct = 'left'
elif (self.l_track == True) and (self.quote_track == False):
if charac.direct == 'right':
charac.image, charac.rect = _load_image(charac.gun[0], x, y)
elif charac.direct == 'left':
charac.image, charac.rect = _load_image(charac.gun[1], x, y)
def jump_logic(self, ch):
if ch.jumps == 2:
ch.uvelocity = JUMP_BOOST
ch.jumpsounds[randint(0, len(ch.jumpsounds) - 1)].play()
elif ch.jumps == 1:
ch.uvelocity = AIR_JUMP_BOOST
ch.jumpsounds[randint(0, len(ch.jumpsounds) - 1)].play()
ch.jumps -= 1<file_sep>/loot/small/preSuf.py
from random import randint
def preSuf(a):
roll = a
#print roll
if(roll == 0):
return ("","","","")
elif(roll == 1):
f = open("MagicPrefix.txt").readlines()
f = [item.replace("\n", "").split(",") for item in f[1:len(f)]]
selector = randint(0,len(f)-1)
attibute = str(randint(int(f[selector][2]),int((f[selector][3])))) + " " + str(f[selector][1])
return (f[selector][0]+ " ", attibute,"","")
elif(roll == 2):
f = open("MagicSuffix.txt").readlines()
f = [item.replace("\n", "").split(",") for item in f[1:len(f)]]
selector = randint(0,len(f)-1)
attibute = str(randint(int(f[selector][2]),int((f[selector][3])))) + " " + str(f[selector][1])
return ("",""," "+f[selector][0], attibute)
else:
pref = preSuf(1)
suff = preSuf(2)
return (pref[0],pref[1],suff[2],suff[3])
"""else:
f = open("MagicPrefix.txt").readlines()
f = [item.replace("\n", "") for item in f[1:len(f)]]
f = [item.split(",") for item in f]
selector = randint(0,len(f)-1)
attibute = str(randint(int(f[selector][2]),int((f[selector][3])))) + " " + str(f[selector][1])
g = open("MagicSuffix.txt").readlines()
g = [item.replace("\n", "") for item in g[1:len(g)]]
g = [item.split(",") for item in g]
selector2 = randint(0,len(g)-1)
attibute2 = str(randint(int(g[selector2][2]),int((g[selector2][3])))) + " " + str(g[selector2][1])
print (f[selector][0],attibute,g[selector][0],attibute2)
return (f[selector][0],attibute,g[selector][0],attibute2)"""
#f = open(inputFile).readlines()
print preSuf(randint(0,3))
'''
def armor(item):
with open("armor.txt") as f:
lines = f.readlines()
items = [i.split(",")[0] for i in lines[1:]]
print items
print items.index(item)
a, b = items[items.index(item)].split(",")[1], items[items.index(item)].split(",")[2]
return random.randint(a, b + 1)
'''<file_sep>/encryption/toolkit3.py
from string import ascii_lowercase
def caesar(plaintext, key):
print "".join([chr((ord(i) - ord("a") + key) % 26 + 97) for i in list(plaintext)])
while True:
if getInput("Would you like to run again? (y or n):", lambda x: x != "y" and x != "n") == "y": caesar(plaintext, key + 1)
else: break
def main():
print caesar(getInput("All lowercases and no spaces please: ", lambda ans: len([i for i in list(ans) if i not in list(ascii_lowercase)])), int(getInput("Numerical key: ", lambda key: not key.isdigit())))
def getInput(prompt, condition, output = "ASDF"):
while condition(output): output = str(raw_input(prompt))
return output
def vignere(ctfilename = "dracula-enc.txt", keyfilename = "dracula-keywords.txt"):
with open(ctfilename) as f:
cypherText = f.readlines()
with open(keyfilename) as g:
keys = [x for x in g.readlines() if x != "\n"]
print cypherText
print keys
for i in range(len(keys)):
print vignereDecrypter(cypherText[i].strip(), keys[i].strip())
def vignereDecrypter(line, key):
return "".join([addChars(line[i], key[i % len(key)]) for i in range(len(line))])
def addChars(a, b):
return chr((ord(a) - ord(b)) % 26 + 97)
def onetimepad(ciphertext, key):
if len(ciphertext) == len(key):
return "".join([addChars(ciphertext[i], key[i]) for i in range(len(ciphertext))])
else:
raise ValueError("Ciphertext and key were not same length.")
def subCipher(ciphertext, filename = "subst-table-ex.txt"):
subDict = tbl(filename)
return "".join( [subDict[char] for char in ciphertext] )
def tbl(filename):
output = {}
with open(filename) as f:
lines = f.readlines()
for i in range(26):
output[chr(i + 97)] = lines[i].strip()
return output
print subCipher("edddaikglyedh\
ltkllktvkuvnalooh\
txvgtxvddtlktxvh\
rvtdlhvqivltih\
qldbvktxgpdlyqygw\
aikgxlkxtlelyedh\
aookxgwtxvirhilbaye\
txvitxvvuanvytvdgs\
ihypnovldrgir")<file_sep>/pygame/microgames-tester/pong/game.py
import pygame, pygame.mixer
from pygame import Surface
from pygame.image import load
from pygame.locals import *
from pygame.mixer import music
from pygame.rect import Rect
from pygame.sprite import Group, Sprite
from random import randint, choice
import locals
from microgame import Microgame
##### GAME CONSTANTS ###########################################################
SPEED_BASE = 10
BAT_SPEED = 10
BALL_SPEED_BASE = 10
BALL_SPEED_RANGE = 10
AI_TRACKING_SLACK = 10
TIME_TO_WIN_AFTER_BOUNCE = 2000
##### LOADER-REQUIRED FUNCTIONS ################################################
def make_game():
return PongMicrogame()
def title():
return 'Pong'
def thumbnail():
return 'games/pong/thumbnail.png'
def hint():
return 'Return it!'
################################################################################
def _load_image(name, x, y):
'''
Loads an image file, returning the surface and rectangle corresponding to
that image at the given location.
'''
try:
image = load(name)
if image.get_alpha is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, msg:
print 'Cannot load image: {}'.format(name)
raise SystemExit, msg
rect = image.get_rect().move(x, y)
return image, rect
##### MODEL CLASSES ###########################################################
class Ball(Sprite):
'''
A ball in the Pong Microgame.
Attributes:
rect - the bounding box encasing this ball
image - the rendering surface of this ball
vx - the x-component of the ball's velocity
vy - the y-component of the ball's velocity
bat_sound - the sound played when hitting a bat
wall_sound - the sound played when hitting a wall
area - the bounding box of the game world
game - the PongMicrogame object that owns this Ball
'''
def __init__(self, game, x, y, vx, vy):
Sprite.__init__(self)
self.image, self.rect = _load_image('games/pong/ball.png', x, y)
self.vx = vx
self.vy = vy
self.bat_sound = pygame.mixer.Sound('games/pong/ping.wav')
self.wall_sound = pygame.mixer.Sound('games/pong/pong.wav')
self.area = game.rect
self.game = game
def update(self):
# Store the future position of the ball (in rect), and ask...
rect = self.rect.move(self.vx, self.vy)
# Did the ball leave the playfield (i.e., hit a wall)?
if not self.area.contains(self.rect):
self.wall_sound.play()
tl = not self.area.collidepoint(rect.topleft)
tr = not self.area.collidepoint(rect.topright)
bl = not self.area.collidepoint(rect.bottomleft)
br = not self.area.collidepoint(rect.bottomright)
if tl and tr or bl and br:
self.vy = -self.vy
if tl and bl:
# Collision on the left-hand side --- win!
self.vx = -self.vx
self.game.win()
if tr and br:
# Collision on the right-hand side --- lose!
self.vx = -self.vx
self.game.lose()
rect = self.rect.move(self.vx, self.vy)
# Did the ball collide with the left bat?
elif self.rect.colliderect(self.game.lbat.rect):
self.bat_sound.play()
self.vx = -self.vx
rect.x = self.game.lbat.rect.x + self.game.lbat.rect.width + 1
# Did the ball colilide with the right bat?
elif self.rect.colliderect(self.game.rbat.rect):
self.bat_sound.play()
self.vx = -self.vx
rect.x = self.game.rbat.rect.x - rect.width - 1
self.game.start_win_countdown()
# Commit the future position of the ball as its current position
self.rect = rect
class Bat(Sprite):
'''
A Bat in the Pong Microgame
Attributes:
image - the rendering surface of this bat
rect - the bounding box of the bat
direction - direction of movement: -1 = up, 0 = not moving, 1 = down
area - the bounding box of the area enclosing the playfield
ball - the ball object that this bat will track (if ai is enabled)
ai - True if this bat is controlled by the ai, false otherwise
'''
def __init__(self, x, y, area, ball, ai=False):
Sprite.__init__(self)
self.direction = 0
self.image, self.rect = _load_image('games/pong/bat.png', x, y)
self.area = area
self.ball = ball
self.ai = ai
def _get_delta(self):
if self.direction == -1:
return -BAT_SPEED
elif self.direction == 0:
return 0
else:
return BAT_SPEED
def update(self):
# If the bat is AI controlled, determine its direction
if self.ai:
bat_midpoint = self.rect.y + self.rect.height / 2
ball_midpoint = self.ball.rect.y + self.ball.rect.height / 2
if bat_midpoint > ball_midpoint + AI_TRACKING_SLACK:
self.direction = -1
elif bat_midpoint < ball_midpoint - AI_TRACKING_SLACK:
self.direction = 1
# Store the future position of the bat (in rect) and ask...
rect = self.rect.move(0, self._get_delta())
# Did the bat collide with the boundaries of the playfield?
if not self.area.contains(self.rect):
tl = not self.area.collidepoint(rect.topleft)
tr = not self.area.collidepoint(rect.topright)
bl = not self.area.collidepoint(rect.bottomleft)
br = not self.area.collidepoint(rect.bottomright)
if tl and tr:
rect.y = 1
elif bl and br:
rect.y = self.area.height - rect.height - 1
# Commit the finalized position of the bat
self.rect = rect
class PongMicrogame(Microgame):
'''
Simple Pong Microgame.
An example Microgame. Single bounce Pong.
Attributes:
rect - the bounding box of the playfield
ball - the ball of the microgame
lbat - the left-hand bat of this microgame, ai-controlled
rbat - the right-hand bat of this microgame, user-controlled
sprites - the sprite group that contains the sprites of the game
timeSinceWin - the time in (ms) when the player won the game, or 0 if the
game has not been won yet
'''
def __init__(self):
Microgame.__init__(self)
self.rect = Rect(0, 0, locals.WIDTH, locals.HEIGHT)
speed = BALL_SPEED_BASE
widthqrt = self.rect.width / 4
heightqrt = self.rect.height / 4
self.ball = Ball(self, 150, randint(heightqrt, heightqrt * 3), \
randint(speed, speed + BALL_SPEED_RANGE), \
choice([speed, -speed]))
self.lbat = Bat(100, randint(heightqrt, heightqrt * 3), \
self.rect, self.ball, True)
self.rbat = Bat(self.rect.width - 150, \
randint(heightqrt, heightqrt * 3), \
self.rect, self.ball)
self.sprites = Group((self.ball, self.lbat, self.rbat))
self.timeSinceWin = 0
def start_win_countdown(self):
'''
Starts the successful hit countdown --- once this is up, the player wins
the game.
'''
self.timeSinceWin = pygame.time.get_ticks()
def start(self):
music.load('games/pong/music.mp3')
music.play(0, 0.5)
def stop(self):
music.stop()
def update(self, events):
time = pygame.time.get_ticks()
if self.timeSinceWin > 0 and \
time > self.timeSinceWin + TIME_TO_WIN_AFTER_BOUNCE:
self.win()
self.sprites.update()
for event in events:
if event.type == KEYDOWN:
if event.key == K_UP:
self.rbat.direction = -1
elif event.key == K_DOWN:
self.rbat.direction = 1
if event.type == KEYUP:
if event.key == K_UP or event.key == K_DOWN:
self.rbat.direction = 0
def render(self, surface):
surface.fill(Color(0, 0, 0))
self.sprites.draw(surface)
def get_timelimit(self):
return 10
<file_sep>/encryption/passfind2.py
def compute_inventories(words):
output = {}
for i in range(len(words)):
output[words] = LetterInv(word)
return output
def prune_by_inventory(dic, li):
return {key : dic[key] for key in dic.keys() if is_in(dic[key], li)}
def prune_by_length(dic, n):
return {key : dic[key] for key in dic.keys() if len(key) >= n}
def prune_by_w(dic):
return {key : dic[key] for key in dic.keys() if key[0] == w}
def notMain(stringg,wordList):
output = []
def iterator(stringgg,wordListt,listBuiltSoFar):
invent = create_inventory(stringg)
WordListt = prune_by_inventory(wordListt,invent)
if len(WordListt):
for key in WordList.keys():
if(is_in(WordList[key],invent)):
tempListBuiltSo = [x for x in listBuiltSoFar]
tempListBuiltSo += [str(key)]
if to_str(subtract(wordList[key],invent)) == "":
output += [tempListBuiltSo]
else:
iterator(to_str(subtract(wordList[key],invent)),wordListt,tempListBuiltSo)
else:
pass
else:
pass
iterator(stringg,wordList,[])
return output
def create_inventory(s):
letter_list = [chr(c) for c in range(ord('a'), ord('z') + 1)]
counts = [s.count(chr(c)) for c in range(ord('a'), ord('z') + 1)]
z = zip(letter_list, counts)
return {k : v for k, v in z}
def subtract(li1, li2):
result = {}
diffs = []
for i in range(0, len(li1.values())):
diffs.append(abs(li1[chr( ord('a') + i )] - li2[chr( ord('a') + i)]))
z = zip([chr(c) for c in range(ord('a'), ord('z') + 1)], diffs)
return {k : v for k,v in z}
def is_in(li1, li2):
v1 = li1.values()
v2 = li2.values()
bools = []
for i in range(0, len((v1)) - 1):
if (v1[i] > 0):
bools.append(v2[i] > 0)
return False not in bools
def to_str(li):
values = li.values()
keys = li.keys()
result = ""
for i in range(0, len(keys) - 1):
result += values[i] * str(keys[i])
return result
print notMain("doghousezoo", "wordlist.txt")
<file_sep>/pygame/microgames/transition.py
from pygame.font import Font
from pygame.locals import *
from pygame.time import get_ticks
import pygame, pygame.image, pygame.mixer, pygame.transform
from locals import *
from microgame import Microgame
FONT_SIZE = 56
Y_DIST = 60
THUMBNAIL_SIZE = (256, 256)
class Transition(Microgame):
'''
The transition scene
The transition scene transitions between the various microgames displaying
relevant information such as the player's score and their number of lives
left.
'''
def __init__(self, hint, thumbnail):
''' Creates a transition with the given hint and next scene '''
Microgame.__init__(self)
font = Font(GAME_FONT_FILENAME, FONT_SIZE)
self.thumbnail, _ = load_image(thumbnail, 0, 0)
self.thumbnail = pygame.transform.scale(self.thumbnail,
THUMBNAIL_SIZE)
self.hint = font.render(hint, True, C_WHITE)
twidth, theight = self.thumbnail.get_size()
hwidth, hheight = self.hint.get_size()
self.thumbnail_rect = ( (WIDTH - twidth) / 2
, (HEIGHT - theight - hheight) / 2
, twidth
, theight )
self.hint_rect = ( (WIDTH - hwidth) / 2
, HEIGHT / 2 + hheight
, hwidth
, hheight )
def _elapsed_time(self):
return (get_ticks() - self.time) / 1000.0
def start(self):
self.time = get_ticks()
pygame.mixer.music.load('transition.ogg')
pygame.mixer.music.play()
def stop(self):
pygame.mixer.music.stop()
def update(self, events):
if self._elapsed_time() > WAIT_PERIOD:
self.win()
def render(self, surface):
surface.fill(C_BLACK)
surface.blit(self.thumbnail, self.thumbnail_rect)
surface.blit(self.hint, self.hint_rect)
def get_timelimit(self):
return 15
<file_sep>/pygame/microgames-tester/koala/game.py
import pygame, sys, os
from os.path import join
from pygame.locals import *
from pygame.color import Color
from pygame.sprite import Sprite, Group
from pygame.surface import Surface
from pygame.rect import Rect
import locals
from microgame import Microgame
##### LOADER-REQUIRED FUNCTIONS ################################################
def make_game():
return KoalaGame()
def title():
return 'Koala'
def thumbnail():
return 'games/koala/koala.jpg'
def hint():
return 'Eat stuff!'
################################################################################
class Koala(Sprite):
def __init__(self):
Sprite.__init__(self)
self.image = pygame.image.load('games/koala/koala.jpg').convert_alpha()
self.rect = self.image.get_rect()
self.velocity = (0, 0)
def update(self):
self.rect.x += self.velocity[0]
self.rect.y += self.velocity[1]
class KoalaGame(Microgame):
def __init__(self):
Microgame.__init__(self)
self.koala = Koala()
self.entities = Group([self.koala])
def start(self):
pass
def stop(self):
pass
def update(self, events):
self.entities.update()
for event in events:
if event.type == KEYUP and event.key == K_q:
self.lose()
elif event.type == KEYDOWN and event.key == K_RIGHT:
self.koala.velocity = (5, 0)
elif event.type == KEYUP and event.key == K_RIGHT:
self.koala.velocity = (0, 0)
elif event.type == KEYDOWN and event.key == K_UP:
self.koala.velocity = (0, -5)
elif event.type == KEYUP and event.key == K_UP:
self.koala.velocity = (0, 0)
elif event.type == KEYDOWN and event.key == K_DOWN:
self.koala.velocity = (0, 5)
elif event.type == KEYUP and event.key == K_DOWN:
self.koala.velocity = (0, 0)
elif event.type == KEYDOWN and event.key == K_LEFT:
self.koala.velocity = (-5, 0)
elif event.type == KEYUP and event.key == K_LEFT:
self.koala.velocity = (0, 0)
def render(self, surface):
surface.fill(Color(0, 0, 0))
self.entities.draw(surface)
def get_timelimit():
return 5
<file_sep>/pygame/microgames-tester/games/ssb/characters.py
class Snake(Character):
def __init__(self):
Character.__init__(self)
self.run = [join('games', 'ssb', 'snake', 'runright.png'), join('games', 'ssb', 'snake', 'runleft.png')]
self.gun = [join('games', 'ssb', 'snake', 'gunright.png'), join('games', 'ssb', 'snake', 'gunleft.png')]
self.idle = [join('games', 'ssb', 'snake', 'idleright.png'), join('games', 'ssb', 'snake', 'idleleft.png')]
self.image, self.rect = _load_image(self.idle[0], 0, 0)
self.reloadtime = 1500
self.projectilecount = 2
self.projectilesound = pygame.mixer.Sound(join('games', 'ssb', 'snake', 'gun.ogg'))
self.jumpsounds = [pygame.mixer.Sound(join('games', 'ssb', 'snake', 'huh.ogg')),
self.jumpsounds = [pygame.mixer.Sound(join('games', 'ssb', 'snake', 'hah.ogg')),
def make_projectile(self, x, y, charac):
if charac.direct == 'right':
self.projectile = snake_Laser(x, y + 24)
self.projectile.velocity = charac.projectile.velocity
elif charac.direct == 'left':
self.projectile = snake_Laser(x - 44, y + 24)
self.projectile.velocity = charac.projectile.velocity * (-1)
def projectile_logic(self):
if (self.projectilecount == 0) and ((pygame.time.get_ticks() - self.no_projectile_time) >= self.reloadtime):
self.projectilecount = 2<file_sep>/speed-read/wordGenTesting.py
#IMPORTS
import random
#VARIBLE DEFININTIONS
class WordGenerator:
"""Deck of Cards"""
def __init__(self, files):
self.lastAccess = 0
with open(files) as f:
temp = []
for line in f.readlines():
temp.extend(line.split())
self.words = temp
def hit(self):
if(self.lastAccess<len(self.words)):
output = self.words[self.lastAccess]
self.lastAccess += 1
return output
else:
raise ValueError("End of File")
gen = WordGenerator("text.txt")
def main():
try:
print gen.hit()
except ValueError:
print "Value Error"
main()<file_sep>/day6.py
output = []
def codons(gg,i):
global output
codonFull = []
codonInProduction = []
h = list(gg[i].replace("-","").upper())
for i in range(0,(len(h))):
if(i%3 == 2):
codonInProduction += [h[i]]
codonFull += ["".join(codonInProduction)]
codonInProduction = []
else:
codonInProduction += [h[i]]
output += ["Codons List: %s \n" % (str(codonFull))]
return codonFull
def isProtein(codonFull):
global output
if(codonFull[0] == "ATG" and ((codonFull[len(codonFull)-1]) == "TAA" or codonFull[len(codonFull)-1] == "TAG" or codonFull[len(codonFull)-1] == "TGA")) :
output += ["Is Protein?: YES \n"]
else:
output += ["Is Protein?: NO \n"]
def dna():
#VARIABLES AND FUNCTIONS
global output
output = []
inputFile = raw_input("DISH DAT INPUT FILE BRAHHHHHHHHHHHHH! \n - VIVIAN, brothority\nInput File: ")
outputFile = raw_input("Can you please give me a location to output your results? \n Thank you! \n - <NAME> (dsilvs)\nOutput File: ")
f = open(inputFile).readlines()
#f.split("\n")
g = [item.replace("\n","") for item in f]
#print g
for i in range(0,len(g)):
if(i%2==0):
output += ["Region Name: %s \n" % (g[i])]
else:
output += ["Nucleotides: %s \n" % (g[i].replace("-","").upper())]
output += ["Nuc. Counts: %s \n" % (str([g[i].upper().count("A"),g[i].upper().count("C"),g[i].upper().count("G"),g[i].upper().count("T")]))]
totalMass = [float(g[i].upper().count("A")*135.128),float(g[i].upper().count("C")*111.103),float(g[i].upper().count("G")*151.128),float(g[i].upper().count("T")*125.107),float(g[i].count("-")*100.000)]
output += ["Total Mass%: [{0:.2f},{1:.2f},{2:.2f},{3:.2f}] of {4:.2f} \n".format((totalMass[0]/float(sum(totalMass)))*100,(totalMass[1]/float(sum(totalMass)))*100,(totalMass[2]/float(sum(totalMass)))*100,(totalMass[3]/float(sum(totalMass)))*100,float(sum(totalMass)))]
codonFull = codons(g,i)
output += ["\n"]
#ACGT
i += 1
with open(outputFile, "w'") as s:
s.writelines(output)
return output
output = g
dna()<file_sep>/pygame/testStuff.py
import sys, pygame
pygame.init()
size = width, height = 350, 240
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.gif")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
if pygame.key.get_focused():
press=pygame.key.get_pressed()
if(press[273]):
if(speed[1]<0):
speed[1] -= 1
else:
speed[1] += 1
elif(press[274]):
if(speed[1]<0):
speed[1] += 1
else:
speed[1] -= 1
elif(press[275]):
if(speed[0]<0):
speed[0] += 1
else:
speed[0] -= 1
speed[0] += 1
elif(press[276]):
speed[0] -= 1
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
"""
while True:
for i in pygame.event.get():
if i.type==QUIT:
exit()
a=100
screen.fill((255,255,255))
if pygame.key.get_focused():
press=pygame.key.get_pressed()
for i in xrange(0,len(press)):
if press[i]==1:
name=pygame.key.name(i)
text=f1.render(name,True,(0,0,0))
screen.blit(text,(100,a))
a=a+100
pygame.display.update()
"""<file_sep>/pygame/microgames/locals.py
import pygame
# True if the game should failfast when it encounters a bad module.
FAILFAST = False
# The width of the screen
WIDTH = 1024
# The height of the screen
HEIGHT = 768
# The (fixed) frame rate of the game
FPS = 30
# The number of lives the player has
LIVES = 2
# The time in-between games
WAIT_PERIOD = 2
# The game-wide font to use
GAME_FONT_FILENAME = 'FrancoisOne.ttf'
# Common color constants
C_BLACK = pygame.Color(0, 0, 0)
C_WHITE = pygame.Color(255, 255, 255)
C_GOLD = pygame.Color(255, 215, 0)
def load_image(name, x, y):
"""
Loads an image file, returning the surface and rectangle corresponding to
that image at the given location
"""
try:
image = pygame.image.load(name)
if image.get_alpha is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, msg:
print 'Cannot load image: {}'.format(name)
raise SystemExit, msg
rect = image.get_rect().move(x, y)
return image, rect
<file_sep>/speed-read/animate.py
from drawingpanel import *
def animate(generator, files="text.txt", height=500,width=500,fontt=16,timeout=200):
def create_textt(canvas,fontr,textt):
canvas.create_text(height/2,width/2,text=textt,font=fontr)
def sleep(obj,timee):
obj.update()
time.sleep(timee / 1000.0)
obj.update()
fonter = ("Helvetica", fontt)
panal = DrawingPanel(height,width)
canvas = panal.canvas
while True:
try:
word = generator.next_word()
create_textt(canvas,fonter,word)
sleep(canvas,timeout)
except ValueError:
print "End of File"
break
animate(gen)<file_sep>/pygame/microgames/game.py
from locals import *
from menu import Menu
import loader
class Game():
'''
The Microgames game.
Main model for the Microgames game.
Attributes:
finished - True iff the Microgames game is over.
scene - The current scene this game is playing.
microgames - The list of loaded microgame modules
'''
def __init__(self):
''' Initializes a new game to the start screen. '''
self.finished = False
self.scene = None
self.microgames = loader.load(FAILFAST)
self.change(Menu(self))
def change(self, scene):
''' Changes the current scene to the given scene. '''
if self.scene:
self.scene.stop()
self.scene = scene
self.scene.start()
def update(self):
'''
Updates the overall game by passing the request to the underlying
scene.
'''
self.scene.update()
def render(self, surface):
'''
Renders this game to the given by passing the request to the underying
scene.
'''
self.scene.render(surface)
<file_sep>/pygame/microgames/scene.py
class Scene(object):
'''
Base class for all scenes.
A scene is an abstract game component run by the top-level Game. Scenes
include the menu and the microgame engine.
Attributes:
game - the Game object this scene operates under.
finished - True iff this scene has completed
'''
def __init__(self, game):
self.game = game
self.finished = False
def start(self):
'''
Initializes this scene.
init is called precisely when the scene begins. In contrast, the
constructor (__init__) may be called to construct a scene, but the game
itself may not be start until some time after.
'''
raise NotImplementedError('Scene.start')
def stop(self):
'''
Stops this scene.
stop is called when the scene is over. If this scene requires any
cleanup, it should be done here.
'''
raise NotImplementedError('Scene.stop')
def update(self):
'''
Updates this scene.
update is called on every game tick in main and should handle all user
input for that tick as well as update the scene's own model.
'''
raise NotImplementedError('Scene.update')
def render(self, surface):
'''
Renders this scene to the given surface.
render is called on every game tick in main and should handle all
rendering of this scene to the given surface.
'''
raise NotImplementedError('Scene.render')
<file_sep>/loot/small/TC.py
import random
def TC(inputTC):
def generate(classes, tok):
if tok not in classes:
return tok
else:
return generate(classes, random.choice(classes[tok].split(",")))
with open("TreasureClassEx.txt") as f:
lines = f.readlines()[1:]
classes = {}
for line in lines:
a, b = line.split(",", 1)
classes[a] = b.strip()
return generate(classes, inputTC)
print TC("Cow (H)")<file_sep>/pygame/microgames-tester/games/lineMathCombo/line/game.py
# Pygame imports
import os.path
import pygame, pygame.mixer
from pygame import Surface
from pygame.image import load
from pygame.locals import *
from pygame.mixer import music
from pygame.rect import Rect
from pygame.sprite import Group, Sprite
# Random imports
from random import randint, choice
# Microgame-specific imports
import locals
from microgame import Microgame
##### LOADER-REQUIRED FUNCTIONS ################################################
def make_game():
return evade()
pass
def title():
return "Ember Defense"
pass
def thumbnail():
return os.path.join("games", "line", "emberHD.png")
pass
def hint():
return "Don't let the ember get \n hit!"
pass
################################################################################
def _load_image(name, x, y):
'''
Loads an image file, returning the surface and rectangle corresponding to
that image at the given location.
'''
try:
image = load(name)
if image.get_alpha is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, msg:
print 'Cannot load image: {}'.format(name)
raise SystemExit, msg
rect = image.get_rect().move(x, y)
return image, rect
##### MODEL CLASSES ###########################################################
class e_icicle(Sprite):
def __init__(self):
Sprite.__init__(self)
imgRand = randint(0,1)
if(imgRand):
imgpath = os.path.join("games", "line", "retro.png")
else:
imgpath = os.path.join("games","line","syspref.png")
self.image, self.rect = _load_image(imgpath, 0, 0)
#self.rect.bottom = y
#self.rect.left = randint(0, locals.WIDTH / 3 - ICICLE_WIDTH)
self.rect.left = 0
posRand = randint(0,2)
if posRand == 0:
self.rect.centery = locals.HEIGHT/8
elif posRand == 1:
self.rect.centery = 2*locals.HEIGHT/8
else:
self.rect.centery = 3*locals.HEIGHT/8
self.velocity = 1
def update(self):
#self.rect.y += self.velocity
self.rect.x += self.velocity
self.velocity += 1
if self.rect.right > locals.WIDTH:
asdf = randint(1, 20)
if asdf == 1:
#self.rect.top = 0
#self.rect.left = randint(0, locals.WIDTH / 3 - ICICLE_WIDTH)
imgRand = randint(0,1)
if(imgRand):
imgpath = os.path.join("games", "line", "retro.png")
else:
imgpath = os.path.join("games","line","syspref.png")
self.image, self.rect = _load_image(imgpath, 0, 0)
self.rect.left = 0
posRand = randint(0,2)
if posRand == 0:
self.rect.centery = locals.HEIGHT/8
elif posRand == 1:
self.rect.centery = 2*locals.HEIGHT/8
else:
self.rect.centery = 3*locals.HEIGHT/8
self.velocity = 0
class eskimo(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = os.path.join("games", "line", "fireguy.png")
self.image, self.rect = _load_image(imgpath, 60, 60)
self.rect.centery = 2*(locals.HEIGHT/8)
self.rect.left = 2*locals.WIDTH/3
#self.velocity = 0
def update(self):
#self.rect.x += self.velocity
pass
##### MICROGAME CLASS #########################################################
class evade(Microgame):
def __init__(self):
Microgame.__init__(self)
self.e_icicles = [e_icicle(), e_icicle()]
self.e_eskimo = eskimo()
self.sprites = Group(self.e_eskimo, *self.e_icicles)
def start(self):
music.load(os.path.join("games", "line", "alt_song.wav"))
music.play()
def stop(self):
music.stop()
self.lose()
def update(self, events):
self.sprites.update()
for event in events:
if event.type == KEYUP and (event.key == K_UP or event.key == K_w) and (event.key == K_DOWN or event.key == K_s):
pass
elif event.type == KEYUP and event.key == K_q:
self.win()
elif event.type == KEYUP and (event.key == K_UP or event.key == K_w):
if(self.e_eskimo.rect.centery == 2*locals.HEIGHT/8):
self.e_eskimo.rect.centery = locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == locals.HEIGHT/8):
self.e_eskimo.rect.centery = locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == 3*locals.HEIGHT/8):
self.e_eskimo.rect.centery = 2*locals.HEIGHT/8
elif event.type == KEYUP and (event.key == K_DOWN or event.key == K_s):
if(self.e_eskimo.rect.centery == 2*locals.HEIGHT/8):
self.e_eskimo.rect.centery = 3*locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == locals.HEIGHT/8):
self.e_eskimo.rect.centery = 2*locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == 3*locals.HEIGHT/8):
self.e_eskimo.rect.centery = 3*locals.HEIGHT/8
"""keys = pygame.key.get_pressed()
if keys[K_q]:
self.win()
elif (keys[K_UP] or keys[K_w]) and (keys[K_DOWN] or keys[K_s]):
pass
elif keys[K_UP] or keys[K_w]:
if(self.e_eskimo.rect.centery == 2*locals.HEIGHT/8):
self.e_eskimo.rect.centery = locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == locals.HEIGHT/8):
self.e_eskimo.rect.centery = locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == 3*locals.HEIGHT/8):
self.e_eskimo.rect.centery = 2*locals.HEIGHT/8
elif keys[K_DOWN] or keys[K_s]:
if(self.e_eskimo.rect.centery == 2*locals.HEIGHT/8):
self.e_eskimo.rect.centery = 3*locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == locals.HEIGHT/8):
self.e_eskimo.rect.centery = 2*locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == 3*locals.HEIGHT/8):
self.e_eskimo.rect.centery = 3*locals.HEIGHT/8
"""
for icicle in self.e_icicles:
if self.e_eskimo.rect.colliderect(icicle.rect):
music.stop()
self.lose()
def render(self, surface):
surface.fill((0, 0, 0))
imgpathh = os.path.join("games", "line", "tile.png")
test_image = pygame.image.load(imgpathh)
surface.blit(test_image,(0,0))
imgpathhh = os.path.join("games", "line", "linesBG.png")
test_imagee = pygame.image.load(imgpathhh)
surface.blit(test_imagee,(377,0))
self.sprites.draw(surface)
def get_timelimit(self):
return 15
<file_sep>/encryption/dict_formatter.py
from string import ascii_lowercase
def line_formatter(li):
#exclude = [",", ".", ";", ":", "'", " ", "!", "\xef", "\"]
new_vals = []
for line in li:
new_lines = [l.lower() for l in line if l.isalpha()]
new_vals.append(''.join(new_lines))
return new_vals
def gen_dict(filename):
lines = gen_list(filename)
#print lines
result = {chr(c) : 0 for c in range(ord('a'), ord('z') + 1)}
for line in lines:
# gen_sub_dict returns a dictionary with the counts of each letter of the string
subdict = gen_sub_dict(line)
for key in subdict.keys():
result[key] += subdict[key]
return result
def gen_list(filename):
with open(filename) as f:
return line_formatter([f.strip().replace(" ", "") for f in f.readlines() if f.strip() != ""])
def calc_frequency(dic):
'''
Takes in a dictionary where {(letter) : count(letter)}
'''
total = 0.0
for key in dic.keys():
total += dic[key]
return {key : "{:.1f}".format(100 * (dic[key] / total)) for key in list(ascii_lowercase)}
def gen_sub_dict(s):
counts = [s.count(chr(c)) for c in range(ord('a'), ord('z') + 1)]
z = zip(list(ascii_lowercase), counts)
content = {k : v for k, v in z}
return content
def subCipher(ciphertext, outfile, filename = "subst-table-ex.txt"):
subDict = tbl(filename)
result = []
out = open(outfile, 'w')
for line in ciphertext:
out.write("".join(subDict[char] for char in line))
out.write("\n")
out.close()
def tbl(filename):
output = {}
with open(filename) as f:
lines = f.readlines()
for i in range(26):
output[chr(i + 97)] = lines[i].strip()
return output
def to_file(list_, outfile):
out = open(outfile, 'w')
for line in list_:
out.write("".join(line))
out.write("\n")
out.close()
'''
the disarm codes are under their very noses
to be rather than to seem
'''
<file_sep>/pygame/microgames-tester/games_compressed/evadeFull/README.md
Evade: A Game by <NAME> and <NAME>
Music: Main Song From Skywire by Nitrome, Musician: <NAME>
Character Art: Inspired by Thin Ice from Nitrome
Background Art: Based on nitrome.com’s Winter Skin<file_sep>/pygame/microgames/engine.py
from pygame.font import Font
from pygame.locals import *
from pygame.time import get_ticks
import pygame, pygame.image, pygame.mixer, pygame.time
from random import randint
from locals import *
from scene import Scene
from transition import Transition
FONT_SIZE = 36
TIMER_POS = (10, 10)
LIVES_POS = (20, HEIGHT - 70)
SCORE_POS = (WIDTH - 150, HEIGHT - 70)
class Engine(Scene):
"""
Manages the playthrough of a collection of microgames.
The engine is the main game scene. It is responsible for managing the
playthrough of a collection of microgames. The player has a number of lives
and must complete as many microgames as possible before they run out of
lives.
Attributes:
game - the Game object this engine operates under.
screen - the screen associated with the engine.
lives - the number of lives the player has left
completed - the number of games the player completed so far
microgames - the list of microgame modules this engine randomly plays
next_index - the index of the next game to play in the microgames list
mg - the current microgame this engine is playing
randpick - True if games are randomly picked, else they are rotated in-order
in_transition - True if the engine is in transition mode
base_time - The base time when the last microgame was selected (in ms)
"""
def _select_next_game(self):
""" Updates next_index with the next microgame to play """
if self.randpick:
self.next_index = randint(0, len(self.microgames) - 1)
else:
self.next_index += 1
if self.next_index >= len(self.microgames) - 1:
self.lives = -1
def _switch_to_transition(self):
""" Switches to a transition screen """
if self.mg:
self.mg.stop()
next_game = self.microgames[self.next_index]
self.mg = Transition(next_game.hint(), next_game.thumbnail())
self.mg.start()
self.time_since_start = pygame.time.get_ticks()
self.in_transition = True
def _switch_to_microgame(self):
""" Switches to the next microgame """
if self.mg:
self.mg.stop()
self.mg = self.microgames[self.next_index].make_game()
self.mg.start()
self.time_since_start = pygame.time.get_ticks()
self.in_transition = False
def __init__(self, game, lives, microgames, prevscene, randpick = True):
Scene.__init__(self, game)
self.font = Font(GAME_FONT_FILENAME, FONT_SIZE)
self.lives = lives
self.completed = 0
self.in_transition = False
self.microgames = microgames
self.prevscene = prevscene
self.mg = None
self.time_since_start = None
self.randpick = randpick
self.next_index = -1
def start(self):
self._select_next_game()
self._switch_to_transition()
def stop(self):
# In addition to myself, unload my current microgame as well
self.mg.stop()
def update(self):
events = pygame.event.get()
for event in events:
if event.type == KEYUP and event.key == K_ESCAPE:
self.game.change(self.prevscene)
limit = self.mg.get_timelimit()
if self.mg.finished:
if self.in_transition:
self._switch_to_microgame()
else:
if self.mg.winner:
self.completed += 1
else:
self.lives -= 1
if self.lives < 0:
self.game.change(self.prevscene)
else:
self._select_next_game()
self._switch_to_transition()
elif limit and pygame.time.get_ticks() - self.time_since_start > limit * 1000:
self.mg.finished = True
else:
self.mg.update(events)
def render(self, surface):
self.mg.render(surface)
surface.blit(self.font.render('Lives: {0}'.format(self.lives), True,
C_WHITE), LIVES_POS)
surface.blit(self.font.render('Score: {0}'.format(self.completed), True,
C_WHITE), SCORE_POS)
if not isinstance(self.mg, Transition):
elapsed = self.mg.get_timelimit() - \
(pygame.time.get_ticks() - self.time_since_start) / 1000.0
surface.blit(self.font.render('{0:.2f}'.format(elapsed), True,
C_WHITE), TIMER_POS)
<file_sep>/sierpinskiTriangle.py
def upTriangle(x, y)<file_sep>/hw3ec2.py
'''
input a list, return with a list of all the permutations of the list
'''
#ORIGINAL VERSION
"""
from random import shuffle
from math import factorial
debugTest = 0
def safe_permutations(listt,debugTest):
def contains(op, l):
i = 0
for ls in op:
if(l == ls):
factorial(3)
else:
i+=1
if(i == len(op)):
op += [l]
return op
output = [listt]
#print output
while len(output) < factorial(len(listt)):
x = [s for s in listt]
shuffle(x)
debugTest += 1
#print x
output = contains(output,x)
#print output
print debugTest
return output
return debugTests
#print safe_permutations([1,2,3,4,5,6],debugTest)
"""
"""
GOAL OF FINAL VERSION:
[1,2,3] = input
output = []
1 2 3
[1,2,3][0] -> [2,3][0] -> [3][0] -> None therefore add combination to the list... and back track
<-cant iterate
1 3 2
[1,2,3][0] -> [2,3][1] -> [2][0] -> None therefore add combination to the list... and back track
<- cant iterate <- cant iterate
2 1 3
[1,2,3][1] -> [1,3][0] -> [3][0] -> None therefore add combination to the list... and back track
.....
<- cant iterate <- cant iterate <- cant iterate NO1 can iterate therefore return output list
return [[1,2,3],[1,3,2]...[3,2,1]]
"""
#FINAL VERSION
def permutate(inputt):
output = []
def iterate(listBuiltSoFar, leftoverInput):
if len(leftoverInput) == 1:
listBuiltSoFar.append(leftoverInput[0])
output.append(listBuiltSoFar)
else:
for i in range(len(leftoverInput)):
tempLeftover = [x for x in leftoverInput]
tempLeftover.pop(i)
tempListBuilt = [x for x in listBuiltSoFar]
tempListBuilt.append(leftoverInput[i])
iterate(tempListBuilt, tempLeftover)
iterate([], inputt)
return output
print permutate(range(3))<file_sep>/pygame/microgames/games/evadeFull/game.py
# Pygame imports
import os.path
import pygame, pygame.mixer
from pygame import Surface
from pygame.image import load
from pygame.locals import *
from pygame.mixer import music
from pygame.rect import Rect
from pygame.sprite import Group, Sprite
# Random imports
from random import randint, choice
# Microgame-specific imports
import locals
from microgame import Microgame
##### LOADER-REQUIRED FUNCTIONS ################################################
def make_game():
return evade()
pass
def title():
return "Eskimo Game"
pass
def thumbnail():
return os.path.join("games", "evadeFull", "snowguy.png")
pass
def hint():
return "Evade the icicles!"
pass
################################################################################
def _load_image(name, x, y):
'''
Loads an image file, returning the surface and rectangle corresponding to
that image at the given location.
'''
try:
image = load(name)
if image.get_alpha is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, msg:
print 'Cannot load image: {}'.format(name)
raise SystemExit, msg
rect = image.get_rect().move(x, y)
return image, rect
##### MODEL CLASSES ###########################################################
ICICLE_WIDTH = 50
class e_icicle(Sprite):
def __init__(self, y):
Sprite.__init__(self)
imgpath = os.path.join("games", "evadeFull", "damage.png")
self.image, self.rect = _load_image(imgpath, 0, 0)
self.rect.bottom = y
self.rect.left = randint(0, locals.WIDTH - ICICLE_WIDTH)
self.velocity = 1
def update(self):
self.rect.y += self.velocity
self.velocity += 2
if self.rect.top > locals.HEIGHT:
asdf = randint(1, 20)
if asdf == 1:
self.rect.top = 0
self.rect.left = randint(0, locals.WIDTH - ICICLE_WIDTH)
self.velocity = 0
class eskimo(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = os.path.join("games", "evadeFull", "snowguy.png")
self.image, self.rect = _load_image(imgpath, 60, 60)
self.rect.bottom = 700
self.rect.left = locals.WIDTH/2
#self.velocity = 0
def update(self):
#self.rect.x += self.velocity
pass
##### MICROGAME CLASS #########################################################
class evade(Microgame):
def __init__(self):
Microgame.__init__(self)
self.e_icicles = [e_icicle(0), e_icicle(locals.HEIGHT + 70),e_icicle(locals.HEIGHT+100),e_icicle(locals.HEIGHT+10),e_icicle(100),
e_icicle(100),e_icicle(700),e_icicle(300),e_icicle(500)]
self.e_eskimo = eskimo()
self.sprites = Group(self.e_eskimo, *self.e_icicles)
def start(self):
music.load(os.path.join("games", "evadeFull", "alt_song.wav"))
music.play()
def stop(self):
music.stop()
self.lose()
def update(self, events):
self.sprites.update()
keys = pygame.key.get_pressed()
if keys[K_q]:
self.win()
elif (keys[K_RIGHT] or keys[K_d]) and (keys[K_LEFT] or keys[K_a]):
pass
elif keys[K_LEFT] or keys[K_a]:
self.e_eskimo.rect.x = max(self.e_eskimo.rect.x - 15, 0)
elif keys[K_RIGHT] or keys[K_d]:
self.e_eskimo.rect.x = min(locals.WIDTH -57, self.e_eskimo.rect.x + 15)
for icicle in self.e_icicles:
if self.e_eskimo.rect.colliderect(icicle.rect):
music.stop()
self.lose()
def render(self, surface):
surface.fill((0, 0, 0))
imgpathh = os.path.join("games", "evadeFull", "tile.png")
test_image = pygame.image.load(imgpathh)
surface.blit(test_image,(0,0))
self.sprites.draw(surface)
def get_timelimit(self):
return 15
<file_sep>/pygame/microgames-tester/evade/README.md
Evade: A Game by <NAME> and <NAME>
Music: Main Song From Skywire by Nitrome, Musician: <NAME>
Character Art: Inspired by Thin Ice from Nitrome
<file_sep>/speed-read/test2.py
#IMPORTS
import random
#VARIBLE DEFININTIONS
class deck:
"""Deck of Cards"""
def __init__(self, length=0):
self.length = length
self.cards = []
self.lastAccess = 0
self.value = [0,0]
self.aceH = True
for i in range (length):
self.cards.append(i+1)
def shuffle(self):
print("Shuffling the deck...")
#None -> None
random.shuffle(self.cards)
self.lastAccess = 0
def hit(self,stack):
#Deck -> None
self.cards.append(stack.cards[stack.lastAccess])
self.score(stack.cards[stack.lastAccess])
stack.lastAccess += 1
def clear(self):
self.cards = []
self.value = [0,0]
def score(self,card):
if((card%13)<=10 and ((card%13) > 1)):
if(not(self.value[1])):
self.value[0] += card%13
else:
self.value[0] += card%13
self.value[1] += card%13
elif((card%13 == 0) or (card%13 == 11) or (card%13 == 12)):
if(not(self.value[1])):
self.value[0] += 10
else:
self.value[0] += 10
self.value[1] += 10
else:
if(self.aceH):
self.value[1] = self.value[0] + 1
self.value[0] += 11
self.aceH = False
else:
self.value[1] += 1
self.value[0] += 1
class Bank:
"""Bank"""
def __init__(self, total):
self.total = total
self.current = 0
self.ibet = 0
def bet(self):
while True:
while True:
try:
self.current = int(raw_input("Current Total: " + str(self.total) + " \n Place your bets! "))
break
except ValueError:
print "Oops! That was not a valid number.\nYour value must be greater than zero.\nTry again..."
if(self.current > 0 and self.current <= self.total):
self.total -= self.current
break
def lose(self):
self.current = 0
self.total += 2*self.ibet
self.ibet = 0
print "You lost!\nDealer is laughing at you.\nTry again and take him down a notch."
fold()
def win(self):
self.total += 2*self.current
self.current = 0
self.ibet = 0
print "VICTORY!!!!\nDealer ain't got nothing on you."
fold()
def push(self):
self.total += self.current
self.current = 0
self.ibet = 0
print "Push!\nDealer got lucky. Let\'s get him next time."
fold()
def insurance(self):
while True:
while True:
try:
self.ibet = int(raw_input("The dealer is showing an ace.\nHow much insurance would you like?\nCurrent Bet: " + str(self.current) + "\nCurrent Total:" + str(self.total) + "\n"))
break
except ValueError:
print "Oops! That was not a valid number.\nYour value must be either nonnegative integer.\nTry again..."
if(self.ibet >= 0 and self.ibet < self.total and self.ibet <= self.current/2):
break
else:
print "Insurance must be either zero or up to half your current bet."
def blackjack():
self.total += 3*self.current
self.current = 0
self.ibet = 0
print "BLACKJACK!!!!!!!!!!!\nWe got a high-roller over here!"
fold()
mainDeck = deck(52)
hand = deck()
dealer = deck()
bank = Bank(10000)
#GLOBAL VARIABLES
convertor = [" K", "n A", " 2", " 3", " 4", " 5"," 6"," 7","n 8"," 9"," 10"," J"," Q"]
converter = ["Spades","Hearts","Clubs","Diamonds"]
#FUNCTION DEFINITIONS
def fold():
if(bank.total<=0):
print "GAME OVER YOU LAZY BROKE"
return False
else:
mainDeck.shuffle()
hand.clear()
dealer.clear()
bank.bet()
hand.hit(mainDeck)
hand.hit(mainDeck)
dealer.hit(mainDeck)
dealer.hit(mainDeck)
iblackjack()
def stay(val1=0,index=0):
if(index==0):
if(dealer.value[0]>=17):
if(dealer.value[0]>21):
stay(val1,1)
else:
compare(val1,0)
else:
dealer.hit(mainDeck)
a = []
b = []
for card in dealer.cards:
a.append(convertor[card%13])
b.append(converter[card%4])
print "The dealer now has:\na%s of %s" % (a[0],b[0])
if(len(a)>1):
for i in range(1,len(a)):
print "and a%s of %s" % (a[i],b[i])
stay(val1,0)
elif(index==1):
if(dealer.value[1]>=17 or dealer.value[1] == 0):
if(dealer.value[1]>21 or dealer.value[1] == 0):
bank.win()
else:
compare(val1,1)
else:
dealer.hit(mainDeck)
stay(val1,1)
def compare(val1=0,val2=0):
if(hand.value[val1]>dealer.value[val2]):
bank.win()
elif(hand.value[val1]<dealer.value[val2]):
bank.lose()
else:
bank.push()
def iblackjack():
if(hand.value[0]==21):
if(dealer.value[0]==21):
bank.push()
else:
bank.blackjack()
if(dealer.cards[1]%13 == 1):
bank.insurance()
if(dealer.value[0] == 21):
bank.lose()
else:
bank.ibet=0
hit_stay(0)
else:
hit_stay(0)
def hitFlow():
hand.hit(mainDeck)
if(hand.value[0] > 21):
if(hand.value[1] > 21 or hand.value[1] <= 0):
bank.lose()
else:
hit_stay(1)
else:
hit_stay(0)
def hit_stay(index=0):
a = []
b = []
for card in hand.cards:
a.append(convertor[card%13])
b.append(converter[card%4])
print "You now have:\na%s of %s" % (a[0],b[0])
if(len(a)>1):
for i in range(1,len(a)):
print "and a%s of %s" % (a[i],b[i])
print "The dealer has a%s of %s." % (convertor[dealer.cards[1]%13],converter[dealer.cards[1]%4])
while True:
ans = str(raw_input("Would you like to hit or stay?: "))
if (ans.lower() == "hit" or ans.lower() == "h" or ans.lower() == "stay" or ans.lower() == "s"):
break
if (ans.lower() == "hit" or ans.lower() == "h"):
print "Hit me brah!"
hitFlow()
if (ans.lower() == "stay" or ans.lower() == "s"):
print "I'm g with what I got."
a = []
b = []
for card in dealer.cards:
a.append(convertor[card%13])
b.append(converter[card%4])
print "The dealer now has:\na%s of %s" % (a[0],b[0])
if(len(a)>1):
for i in range(1,len(a)):
print "and a%s of %s" % (a[i],b[i])
stay()
#MAIN CODE
fold()
<file_sep>/encryption/pruner.py
with open("manualList.txt") as f:
f = f.readlines()
f = [x.replace("\n","") for x in f]
f = [x.lower() for x in f if len(x)== 11]
f = [x for x in f if x.count("a")<3]
f = [x for x in f if x.count("b")<2]
f = [x for x in f if x.count("c")==0]
f = [x for x in f if x.count("d")<4]
f = [x for x in f if x.count("e")<6]
f = [x for x in f if x.count("f")==0]
f = [x for x in f if x.count("g")<5]
f = [x for x in f if x.count("h")==0]
f = [x for x in f if x.count("i")<7]
f = [x for x in f if x.count("j")==0]
f = [x for x in f if x.count("k")<2]
f = [x for x in f if x.count("l")<3]
f = [x for x in f if x.count("m")==0]
f = [x for x in f if x.count("n")<3]
f = [x for x in f if x.count("o")==0]
f = [x for x in f if x.count("p")<2]
f = [x for x in f if x.count("q")==0]
f = [x for x in f if x.count("r")<3]
f = [x for x in f if x.count("s")<4]
f = [x for x in f if x.count("t")<3]
f = [x for x in f if x.count("u")==0]
f = [x for x in f if x.count("v")==0]
f = [x for x in f if x.count("w")<3]
f = [x for x in f if x.count("x")==0]
f = [x for x in f if x.count("y")==0]
f = [x for x in f if x.count("z")==0]
f = [x+"\n" for x in f]
with open("manualList2.txt", "w") as g:
g.writelines(f)
with open("manualList2.txt") as ww:
w = ww.readlines()
print len(w)
#aabdddeeeeeeggggiiiiiikllnnprrsssttwwwww<file_sep>/speed-read/wordGen.py
#IMPORTS
import random
#VARIBLE DEFININTIONS
class WordGenerator:
"""Deck of Cards"""
def __init__(self, files):
self.lastAccess = 0
with open(files) as f:
temp = []
for line in f.readlines():
temp.extend(line.split())
self.words = temp
def next_word(self):
if(self.lastAccess<len(self.words)):
output = self.words[self.lastAccess]
self.lastAccess += 1
return output
else:
raise ValueError("End of File")
def is_empty(self):
return True if self.lastAccess >= len(self.words) else False<file_sep>/pygame/microgames/chooser.py
import math
from pygame.font import Font
from pygame.locals import *
from locals import *
from scene import Scene
import pygame, pygame.draw, pygame.event, pygame.mixer
GAME_FONT_SIZE = 32
GAMES_PER_PAGE = 5
PADDING_X = 250
PADDING_Y = 20
TITLE_FIXUP = 4
BORDER_OFFSET = 7
THUMBNAIL_WIDTH = 128
THUMBNAIL_HEIGHT = 128
def _is_numeric(k):
return k == K_0 or k == K_1 or k == K_2 or k == K_3 or k == K_4 \
or k == K_5 or k == K_6 or k == K_7 or k == K_8 or k == K_9
def _get_numeric_value(k):
if k == K_0: return 0
elif k == K_1: return 1
elif k == K_2: return 2
elif k == K_3: return 3
elif k == K_4: return 4
elif k == K_5: return 5
elif k == K_6: return 6
elif k == K_7: return 7
elif k == K_8: return 8
elif k == K_9: return 9
else: return None
class Chooser(Scene):
"""
Microgame chooser.
The microgame choosers allows the user to preview and select which
microgames are active.
Attributes
microgames - the game's list of pairs of microgame modules and booleans
that determine if they are enabled
nextscene - the next scene object that should play after this chooser is
done
index - the current multiple (of NUM_GAMES_PER_PAGE) that we are
currently viewing
"""
def __init__(self, game, microgames, nextscene):
Scene.__init__(self, game)
self.game_font = Font(GAME_FONT_FILENAME, GAME_FONT_SIZE)
self.microgames = microgames
self.nextscene = nextscene
self.index = 0
def start(self):
pygame.mixer.music.load('chooser.ogg')
pygame.mixer.music.set_volume(1.0)
pygame.mixer.music.play(-1, 0)
def stop(self):
pygame.mixer.music.stop()
def update(self):
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.game.change(self.nextscene)
elif event.key == K_LEFT:
self.index -= 1
if self.index < 0:
self.index = 0
elif event.key == K_RIGHT:
if (self.index + 1) * GAMES_PER_PAGE < len(self.microgames):
self.index += 1
elif _is_numeric(event.key):
value = _get_numeric_value(event.key)
if 1 <= value <= GAMES_PER_PAGE:
index = self.index * GAMES_PER_PAGE + value - 1
if index < len(self.microgames):
self.microgames[index] = \
(self.microgames[index][0],
not self.microgames[index][1])
def render(self, surface):
surface.fill(C_BLACK)
y = PADDING_Y
offset = 0
start_index = self.index * GAMES_PER_PAGE
end_index = start_index + GAMES_PER_PAGE
surface.blit(
self.game_font.render('Page {0}/{1}'.format(self.index+1,
int(math.ceil(len(self.microgames) / float(GAMES_PER_PAGE)))),
True, C_WHITE), (10, 0))
for game, enabled in self.microgames[start_index:end_index]:
title = game.title()
filename = game.thumbnail()
filename = filename if filename else 'default.png'
image, irect = load_image(filename, 0, 0)
image = pygame.transform.scale(image, (128, 128))
irect.width, irect.height = (THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)
text_height = y + 0.25 * THUMBNAIL_HEIGHT + TITLE_FIXUP
surface.blit(
self.game_font.render('({0})'.format(offset+1), True, C_WHITE),
(PADDING_X, text_height))
surface.blit(
self.game_font.render(title, True, C_WHITE),
(PADDING_X + GAME_FONT_SIZE + 10, text_height))
if enabled:
surface.fill(
C_GOLD,
Rect(WIDTH - PADDING_X - THUMBNAIL_WIDTH - BORDER_OFFSET,
y - BORDER_OFFSET,
THUMBNAIL_WIDTH + BORDER_OFFSET * 2,
THUMBNAIL_WIDTH + BORDER_OFFSET * 2))
surface.blit(image, (WIDTH - PADDING_X - THUMBNAIL_WIDTH, y))
y += PADDING_Y + THUMBNAIL_HEIGHT
offset += 1
<file_sep>/encryption/toolkit.py
from string import ascii_lowercase
def caesar(plaintext, key, recc = 0):
print "".join([chr((ord(i) - ord("a") + key) % 26 + 97) for i in list(plaintext)])
while getInput("Would you like to run again? (y or n):", lambda ans: len([i for i in list(ans) if i not in list(ascii_lowercase)]))=="y" and recc == 0: (caesar(plaintext, key + 1,1))
#(caesar(plaintext, key + 1))
#(caesar(plaintext, key + 1))
#lambda ans: len([i for i in list(ans) if i not in list(ascii_lowercase)])
#Lambda x: x == "y" or x == "n")=="y"
def main():
print caesar(getInput("All lowercases and no spaces please: ", lambda ans: len([i for i in list(ans) if i not in list(ascii_lowercase)])), int(getInput("Numerical key: ", lambda key: not key.isdigit())))
def getInput(prompt, condition, output = "False"):
while condition(output): output = str(raw_input(prompt))
return output
main()<file_sep>/pygame/microgames-tester/games/lineMathCombo/maths/game.py
# Pygame imports
import pygame, pygame.mixer
from pygame import Surface
from pygame.image import load
from pygame.locals import *
from pygame.mixer import music
from pygame.rect import Rect
from pygame.sprite import Group, Sprite
#os import
import os
# Random imports
from random import randint, choice
# Microgame-specific imports
import locals
from microgame import Microgame
##### LOADER-REQUIRED FUNCTIONS ################################################
def make_game():
return MATHS()
pass
def title():
return "Maths"
pass
def thumbnail():
return os.path.join("games","maths","thumbnail.png")
# TODO: Return a(relative path) to the thumbnail image file for your game.
def hint():
return "Solve the problems"
# TODO: Return the hint string for your game.
################################################################################
def _load_image(name, x, y):
'''
Loads an image file, returning the surface and rectangle corresponding to
that image at the given location.
'''
try:
image = load(name)
if image.get_alpha is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, msg:
print 'Cannot load image: {}'.format(name)
raise SystemExit, msg
rect = image.get_rect().move(x, y)
return image, rect
##### MODEL CLASSES ###########################################################
# TODO: put your Sprite classes here
class rotatingNumber(Sprite):
def __init__(self, x, num):
Sprite.__init__(self)
self.num = num
imgpath = os.path.join("games","maths",str(str(num)+".png"))
self.image, self.rect = _load_image(imgpath,300,100)
self.rect.centerx, self.rect.centery = int(x * locals.WIDTH), int(3.0 * locals.HEIGHT / 4)
def update(self):
pass
class rotatingOperation(Sprite):
def __init__(self, x, operation):
Sprite.__init__(self)
self.operation = operation
imgpath = os.path.join("games","maths",self.operation + ".png")
self.image, self.rect = _load_image(imgpath,300,100)
self.rect.centerx, self.rect.centery = x, int(3.0 * locals.HEIGHT / 4)
def update(self):
pass
##### MICROGAME CLASS #########################################################
# TODO: rename this class to your game's name
# (and change "MyMicrogame" instances throughout)
class MATHS(Microgame):
def __init__(self):
Microgame.__init__(self)
self.addans = randint(3, 9)
self.add1 = rotatingNumber(0.5, randint(0, self.addans))
self.add2 = rotatingNumber(5.0 / 6.0, self.addans - self.add1.num)
self.sub1 = rotatingNumber(0.5, randint(3, 9))
self.sub2 = rotatingNumber(5.0 / 6.0, randint(0, self.sub1.num))
self.subans = self.sub1.num - self.sub2.num
self.mod2 = rotatingNumber(5.0 / 6.0, randint(2, 4))
self.mod1 = rotatingNumber(0.5, randint(self.mod2.num + 1, 9))
self.modans = self.mod1.num % self.mod2.num
self.add = rotatingOperation(int(2.0 * locals.WIDTH / 3), "add")
self.sub = rotatingOperation(int(2.0 * locals.WIDTH / 3), "sub")
self.mod = rotatingOperation(int(2.0 * locals.WIDTH / 3), "mod")
self.stage = 0
self.sprites1 = Group(self.add1, self.add2, self.add)
self.sprites2 = Group(self.sub1, self.sub2, self.sub)
self.sprites3 = Group(self.mod1, self.mod2, self.mod)
def start(self):
self.answer = self.addans
print self.answer, self.stage
pass
def stop(self):
pass
def update(self, events):
for event in events:
if event.type == KEYDOWN and event.key == K_q:
self.lose()
if event.type == KEYDOWN and event.key in (K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9):
dictt = {K_0 : 0, K_1 : 1, K_2 : 2, K_3 : 3, K_4 : 4, K_5 : 5, K_6 : 6, K_7 : 7, K_8 : 8, K_9 : 9}
if dictt[event.key] == self.answer:
if self.stage == 0:
self.answer = self.subans
self.stage = 1
print self.answer, self.stage
elif self.stage == 1:
self.answer = self.modans
self.stage = 2
print self.answer, self.stage
elif self.stage == 2:
self.stage = 3
self.answer = -1
time = -10
else:
self.lose()
def render(self, surface):
surface.fill((0, 0, 0))
imgpathhhh = os.path.join("games", "maths", "mathBG.png")
test_imageee = pygame.image.load(imgpathhhh)
surface.blit(test_imageee,(377,768 / 2))
if self.stage == 0:
self.sprites1.draw(surface)
elif self.stage == 1:
self.sprites2.draw(surface)
elif self.stage == 2:
self.sprites3.draw(surface)
def get_timelimit(self):
return 15<file_sep>/hw1.py
#MASTER FUNCTION
def song():
#none -> none
#colors go here
verse1()
print ""
verse2()
verse3()
verse4()
verse5()
verse6()
verse7()
verse8()
verse9()
#VERSE FUNCTIONS
def verse1():
print "I like you, Fred, I like you!"
print "You're just saying those words to be kind."
print "No, I mean it. I like... I mean I love you, Fred!"
print "He is out of his medieval mind!"
print "I'm perfectly sane and sound! I never felt better in my life!"
print "Everybody... everybody, everybody! Come on! And meet my incipient wife!"
def verse2():
yellow()
print "My reasons must be clear."
print "When she shows you all how strong she is you'll stand right up and cheer!"
redBlue()
def verse3():
yellow()
print "She drinks just like a lord!"
print "So sing a merry drinking song and let the wine be poured!"
orange()
def verse4():
yellow()
print "She sings just like a bird!"
print "You\'ll be left completely speechless when her gentle voice is heard!"
green()
def verse5():
yellow()
print "She wrestles like a Greek!"
print "You will clap your hands in wonder at her fabulous technique!"
magenta()
def verse6():
yellow()
print "She dances with such grace!"
print "You are bound to sing her praises \'til you're purple in the face!"
darkPurple()
def verse7():
yellow()
print "She\'s musical to boot!"
print "She will set your feet a-tapping when she plays upon her lute!"
darkGreen()
def verse8():
yellow()
print "A clever, clownish wit!"
print "When she does her funny pantomime your sides are sure to split!"
print "Ha ha ha ha, ho ho ho ho, ha ha ha ha ho!"
darkGreen()
def verse9():
print "I\'m in love with a girl."
print "He\'s in love with a girl named \"F-R-E-D\" Fred!"
#COLOR FUNCTIONS
def yellow():
#none -> none
print "I\'m in love with a girl named Fred."
def redBlue():
#none -> none
print "With a \"F\" and a \"R\" and an \"E\" and a \"D\""
print "And a \"F-R-E-D\" Fred! Yeah!"
print ""
def green():
#none -> none
print "La la la la, la la la la, la la la la la!"
orange()
def magenta():
#none -> none
print "Clap clap, clap clap, clap clap clap clap, clap, clap clap!"
green()
def orange():
#none -> none
print "Fill the bowl to overflowing. Raise the goblet high!"
redBlue();
def darkGreen():
#none -> none
print "Strum strum, strum strum, strum strum strum strum strum, strum."
darkPurple()
def darkPurple():
#none -> none
print "Bravo! Bravo! Bravissimo bravo! Bravissimo!"
magenta()
song()
#function call
<file_sep>/speed-read/main.py
import sys
import time
from drawingpanel import *
class WordGenerator:
def __init__(self, files):
self.lastAccess = 0
self.in_quotes = False
with open(files) as f:
temp = []
for line in f.readlines():
temp.extend(line.split())
self.words = temp
def next_word(self):
if not self.is_empty():
output = self.words[self.lastAccess]
a = len(output)
if a <= 1:
index = output[0]
elif a <= 5:
index = " " * (a - 2) + output[1] + " " * (a - 2)
if a == 2:
output = output[0] + " "
else:
output = " " * (a - 3) + output[0] + " " + output[2:]
elif a <= 9:
index = " " * (a - 3) + output[2] + " " * (a - 3)
output = " " * (a - 5) + output[:2] + " " + output[3:]
elif a <= 13:
index = " " * (a - 4) + output[3] + " " * (a - 4)
output = " " * (a - 7) + output[:3] + " " + output[4:]
else:
index = " " * (a - 5) + output[4] + " " * (a - 5)
output = " " * (a - 9) + output[:4] + " " + output[5:]
self.lastAccess += 1
if '"' in output:
if(self.in_quotes):
self.in_quotes = False
return (output, True, index)
else:
self.in_quotes = True
return (output, True, index)
else:
return (output, self.in_quotes, index)
else:
raise ValueError("End of File")
def is_empty(self):
return self.lastAccess >= len(self.words)
def main(args):
if len(args) == 6:
arg2, arg3, arg4 = int(args[2]), int(args[3]), int(args[4])
arg1 = WordGenerator(args[1])
arg5 = 60 * 1000 / int(args[5])
animate(arg1, arg2, arg3, arg4, arg5)
else:
print "fuck off"
def animate(generator, height=500,width=500,fontt=16,timeout=200):
def create_textt(canvas,fontr,textt,texttt,colorr="#000"):
canvas.create_text(height/2,width/2,text=textt,font=fontr,fill=colorr)
canvas.create_text(height/2,width/2,text=texttt,font=fontr,fill="orange")
def sleep(obj,timee):
obj.update()
time.sleep(timee / 1000.0)
obj.update()
fonter = ("Courier", fontt)
while True:
try:
canvas.create_rectangle(0, 0, height, width, fill = "white")
word = generator.next_word()
if(word[1]):
if(word[0][len(word[0])-1] == "." or word[0][len(word[0])-1] == "," or word[0][len(word[0])-1] == ":" or word[0][len(word[0])-1] == ";" or word[0][len(word[0])-1] == "!" or word[0][len(word[0])-1] == "?"):
create_textt(canvas,fonter,word[0],word[2],"#00b")
sleep(canvas,timeout*1.3)
else:
create_textt(canvas,fonter,word[0],word[2],"#00b")
sleep(canvas,timeout)
else:
if(word[0][len(word[0])-1] == "." or word[0][len(word[0])-1] == "," or word[0][len(word[0])-1] == ":" or word[0][len(word[0])-1] == ";" or word[0][len(word[0])-1] == "!" or word[0][len(word[0])-1] == "?"):
create_textt(canvas,fonter,word[0],word[2])
sleep(canvas,timeout*1.3)
else:
create_textt(canvas,fonter,word[0],word[2])
sleep(canvas,timeout)
except ValueError:
print "End of File"
break
if __name__ == "__main__":
main(sys.argv)<file_sep>/pygame/keyboardTest.py
#importing modules
import pygame
from pygame.locals import *
from sys import exit
#initializing variables
pygame.init()
screen=pygame.display.set_mode((640,480),0,24)
pygame.display.set_caption("Key Press Test")
f1=pygame.font.SysFont("comicsansms",24)
#main loop which displays the pressed keys on the screen
while True:
for i in pygame.event.get():
if i.type==QUIT:
exit()
a=100
screen.fill((255,255,255))
if pygame.key.get_focused():
press=pygame.key.get_pressed()
for i in xrange(0,len(press)):
if press[i]==1:
print i
name=pygame.key.name(i)
text=f1.render(name,True,(0,0,0))
screen.blit(text,(100,a))
a=a+100
pygame.display.update()
rt ctrl 305
winodws 311
menu 319
home 278
page up 280
oage down 281
end 279
scoll 302
pause 19
insert 277
del 127
<file_sep>/loot/small/main.py
import random
from random import randint
def loot_generator():
monster = genMonster()
item = TC(monster[3])
defense = armor(item)
preSufData = preSuf(randint(0, 3))
print "Fighting " + monster[0] + " (Level " + monster[1] + " " + monster[2] + ")..."
print "You have slain " + monster[0]
print monster[0] + " dropped:"
print ""
print preSufData[0] + item + preSufData[2]
print "Defense: " + str(defense)
if preSufData[1] != "": print preSufData[1]
if preSufData[3] != "": print preSufData[3]
def TC(inputTC):
def generate(classes, tok):
if tok not in classes:
return tok
else:
return generate(classes, random.choice(classes[tok].split(",")))
with open("TreasureClassEx.txt") as f:
lines = f.readlines()[1:]
classes = {}
for line in lines:
a, b = line.split(",", 1)
classes[a] = b.strip()
return generate(classes, inputTC)
def preSuf(a):
roll = a
#print roll
if(roll == 0):
return ("","","","")
elif(roll == 1):
f = open("MagicPrefix.txt").readlines()
f = [item.replace("\n", "").split(",") for item in f[1:len(f)]]
selector = randint(0,len(f)-1)
attibute = str(randint(int(f[selector][2]),int((f[selector][3])))) + " " + str(f[selector][1])
return (f[selector][0]+ " ", attibute,"","")
elif(roll == 2):
f = open("MagicSuffix.txt").readlines()
f = [item.replace("\n", "").split(",") for item in f[1:len(f)]]
selector = randint(0,len(f)-1)
attibute = str(randint(int(f[selector][2]),int((f[selector][3])))) + " " + str(f[selector][1])
return ("",""," "+f[selector][0], attibute)
else:
pref = preSuf(1)
suff = preSuf(2)
return (pref[0],pref[1],suff[2],suff[3])
def genMonster():
with open("monstats.txt") as f:
lines = [x.replace("\n", "") for x in f.readlines()[1:]]
g = [item.split(",") for item in lines]
monster = g[random.randint(0,len(g)-1)]
return monster
def armor(item):
with open("armor.txt") as f:
lines = [n.replace("\n", "").split(",") for n in f.readlines()[1:]]
for i in lines:
if i[0] == item:
a = int(i[1])
b = int(i[2])
return random.randint(a, b)
loot_generator()<file_sep>/pygame/microgames-tester/skeleton/game.py
# Pygame imports
import pygame, pygame.mixer
from pygame import Surface
from pygame.image import load
from pygame.locals import *
from pygame.mixer import music
from pygame.rect import Rect
from pygame.sprite import Group, Sprite
# Path imports
from os.path import join
# Random imports
from random import randint, choice
# Microgame-specific imports
import locals
from microgame import Microgame
##### LOADER-REQUIRED FUNCTIONS ################################################
def make_game():
# TODO: Return a new instance of your Microgame class.
raise NotImplementedError("make_game")
def title():
# TODO: Return the title of the game.
raise NotImplementedError("title")
def thumbnail():
# TODO: Return a (relative path) to the thumbnail image file for your game.
raise NotImplementedError("thumbnail")
def hint():
# TODO: Return the hint string for your game.
raise NotImplementedError("hint")
################################################################################
def _load_image(name, x, y):
'''
Loads an image file, returning the surface and rectangle corresponding to
that image at the given location.
'''
try:
image = load(name)
if image.get_alpha is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, msg:
print 'Cannot load image: {}'.format(name)
raise SystemExit, msg
rect = image.get_rect().move(x, y)
return image, rect
##### MODEL CLASSES ############################################################
# TODO: put your Sprite classes here
##### MICROGAME CLASS ##########################################################
# TODO: rename this class to your game's name...
class MyMicrogame(Microgame):
def __init__(self):
Microgame.__init__(self)
# TODO: Initialization code here
def start(self):
# TODO: Startup code here
pass
def stop(self):
# TODO: Clean-up code here
pass
def update(self, events):
# TODO: Update code here
pass
def render(self, surface):
# TODO: Rendering code here
pass
def get_timelimit(self):
# TODO: Return the time limit of this game (in seconds, 0 <= s <= 15)
raise NotImplementedError("get_timelimit")
<file_sep>/encryption/passfind_func.py
def create_inventory(s):
letter_list = [chr(c) for c in range(ord('a'), ord('z') + 1)]
counts = [s.count(chr(c)) for c in range(ord('a'), ord('z') + 1)]
z = zip(letter_list, counts)
return {k : v for k, v in z}
def subtract(li1, li2):
result = {}
diffs = []
for i in range(0, len(li1.values())):
diffs.append(abs(li1[chr( ord('a') + i )] - li2[chr( ord('a') + i)]))
z = zip([chr(c) for c in range(ord('a'), ord('z') + 1)], diffs)
return {k : v for k,v in z}
def is_in(li1, li2):
v1 = li1.values()
v2 = li2.values()
bools = []
for i in range(0, len((v1)) - 1):
if (v1[i] > 0):
bools.append(v2[i] > 0)
return False not in bools
def to_str(li):
values = li.values()
keys = li.keys()
result = ""
for i in range(0, len(keys) - 1):
result += values[i] * str(keys[i])
return ''.join(sorted(result))
print to_str(create_inventory('helloworld'))<file_sep>/day7.py
def permutate(inputt):
output = []
def iterate(listBuiltSoFar, leftoverInput):
if len(leftoverInput) == 1:
listBuiltSoFar.append(leftoverInput[0])
output.append(listBuiltSoFar)
else:
for i in range(len(leftoverInput)):
tempLeftover = [x for x in leftoverInput]
tempLeftover.pop(i)
tempListBuilt = [x for x in listBuiltSoFar]
tempListBuilt.append(leftoverInput[i])
iterate(tempListBuilt, tempLeftover)
iterate([], inputt)
return output
def nub(listt):
output = []
for i in listt:
if i not in output:
output.append(i)
return output
def intersect(right,down):
a = ["r" for item in range(0,down-1)]
b = ["d" for itme in range(0,right-1)]
a += b
c = nub(permutate(a))
print len(c)
return c
#permutate()\
print intersect(3,3)
<file_sep>/speed-read/mainext2.py
import sys
import time
from drawingpanel import *
class WordGenerator:
def __init__(self, files):
self.lastAccess = 0
self.in_quotes = False
with open(files) as f:
temp = []
for line in f.readlines():
temp.extend(line.split())
self.words = temp
def next_word(self):
if(self.lastAccess<len(self.words)):
temp = self.in_quotes
output = self.words[self.lastAccess]
if self.in_quotes == False and "\"" in self.words[self.lastAccess]:
temp = True
self.in_quotes = True
if self.in_quotes == True and "\"" in self.words[self.lastAccess]:
self.in_quotes = False
self.lastAccess += 1
return (output, temp)
else:
raise ValueError("End of File")
def is_empty(self):
return True if self.lastAccess >= len(self.words) else False
def main(args):
if len(args) == 6:
arg2, arg3, arg4 = int(args[2]), int(args[3]), int(args[4])
arg1 = WordGenerator(args[1])
arg5 = 60 * 1000 / int(args[5])
animate(arg1, arg2, arg3, arg4, arg5)
else:
print "fuck off"
def animate(generator, files="text.txt", height=500,width=500,fontt=16,timeout=200):
def create_textt(canvas,fontr,textt):
canvas.create_text(height/2,width/2,text=textt,font=fontr)
def sleep(obj,timee):
obj.update()
time.sleep(timee / 1000.0)
obj.update()
fonter = ("Helvetica", fontt)
panal = DrawingPanel(height,width)
canvas = panal.canvas
while True:
try:
canvas.create_rectangle(0, 0, height, width, fill = "white")
word = generator.next_word()
create_textt(canvas,fonter,word)
sleep(canvas,timeout)
except ValueError:
print "End of File"
break
if __name__ == "__main__":
main(sys.argv)<file_sep>/pygame/microgames/menu.py
from pygame.font import Font
from pygame.locals import *
from locals import *
from menuopts import options
from scene import Scene
import pygame, pygame.event, pygame.mixer
OPTIONS_INIT_X = 175
OPTIONS_INIT_Y = 300
OPTIONS_FONT_SIZE = 48
OPTIONS_Y_DIST = 67
class Menu(Scene):
"""
The Menu scene
The main menu of the Microgames game. From here, you can start a new game,
change various options, or quit.
"""
def __init__(self, game):
Scene.__init__(self, game)
self.options = options()
self.options_font = Font(GAME_FONT_FILENAME, OPTIONS_FONT_SIZE)
self.background, self.rectbg = load_image('title.jpg', 0, 0)
self.index = 0
def start(self):
self.index = 0
pygame.mixer.music.load('theme.ogg')
pygame.mixer.music.play(-1, 0)
def stop(self):
pygame.mixer.music.stop()
pass
def update(self):
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_RETURN:
self.options[self.index][1](self)
elif event.key == K_UP:
self.index -= 0 if self.index == 0 else 1
elif event.key == K_DOWN:
self.index += 0 if self.index == len(self.options)-1 else 1
def _render_options(self, surface):
surface.blit(self.options_font.render('>', True, C_WHITE),
(OPTIONS_INIT_X, OPTIONS_INIT_Y + self.index * OPTIONS_Y_DIST))
def render(self, surface):
surface.fill(C_BLACK)
surface.blit(self.background, (self.rectbg.x, self.rectbg.y))
self._render_options(surface)
<file_sep>/pygame/microgames-tester/moms_spaghetti/game.py
# Pygame imports
import pygame, pygame.mixer
from pygame import Surface
from pygame.image import load
from pygame.locals import *
from pygame.mixer import music
from pygame.rect import Rect
from pygame.sprite import Group, Sprite
# Path imports
from os.path import join
# Random imports
from random import randint, choice
# Microgame-specific imports
import locals
from microgame import Microgame
##### LOADER-REQUIRED FUNCTIONS ################################################
def make_game():
return MomsSpaghettiGame()
def title():
return "Mom's Spaghetti"
def thumbnail():
return join('games', 'moms_spaghetti', 'thumbnail.jpg')
def hint():
return "Feed Eminem"
################################################################################
def _load_image(name, x, y):
'''
Loads an image file, returning the surface and rectangle corresponding to
that image at the given location.
'''
try:
image = load(name)
if image.get_alpha is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, msg:
print 'Cannot load image: {}'.format(name)
raise SystemExit, msg
rect = image.get_rect().move(x, y)
return image, rect
##### MODEL CLASSES ############################################################
INITIAL_X = 300
INITIAL_Y = 100
MIN_VELOCITY = -25
MAX_VELOCITY = 35
VELOCITY_INJ = 50
DECAY = 2
class EminemSprite(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = join('games', 'moms_spaghetti', 'flappy.png')
self.image, self.rect = _load_image(imgpath, INITIAL_X, INITIAL_Y)
self.velocity = MAX_VELOCITY / 2
def _update_velocity(self):
new_velocity = self.velocity + DECAY
if new_velocity > MAX_VELOCITY:
self.velocity = MAX_VELOCITY
elif new_velocity < MIN_VELOCITY:
self.velocity = MIN_VELOCITY
else:
self.velocity = new_velocity
def update(self):
# Update velocity
self._update_velocity()
# Updat
self.rect = self.rect.move(0, self.velocity)
##### MICROGAME CLASS #########################################################
class MomsSpaghettiGame(Microgame):
def __init__(self):
Microgame.__init__(self)
self.eminem = EminemSprite()
self.sprites = Group(self.eminem)
def start(self):
pass
def stop(self):
pass
def update(self, events):
# Update all our sprites
self.sprites.update()
# Check to see if we hit the bottom or top of the screen
_, y_bot = self.eminem.rect.bottomleft
if self.eminem.rect.y <= 0 or y_bot >= locals.HEIGHT:
self.lose()
# Process user input
for event in events:
if event.type == KEYUP and event.key == K_SPACE:
self.eminem.velocity -= VELOCITY_INJ
def render(self, surface):
surface.fill(Color(0, 0, 0))
self.sprites.draw(surface)
def get_timelimit(self):
return 10
<file_sep>/hw2.py
def is_isbn(ISBN):
"""TAKE ISBN RETURN TRUE IF VALID"""
if not(isinstance(ISBN, basestring)):
raise ValueError("Invalid Format")
else:
if(len(ISBN)!=10):
raise ValueError("Invalid String Format")
else:
checkDigit = calculate_check(ISBN)
if(checkDigit == 10):
checkDigit = "X"
return str(checkDigit) == ISBN[9]
def calculate_check(ISBN):
"""CALCULATE THE CHECK DIGIT"""
if not(isinstance(ISBN, basestring)):
raise ValueError("Invalid Format")
else:
if(len(ISBN)<=8 or len(ISBN)>=11):
raise ValueError("Invalid String Format")
else:
return sum([int(a)*b for a,b in zip(list(ISBN[:9]),range(1,10))])%11
#TO DO:
#ERROR PREVENT IS_ISBN FOR 10 DIGIT String
#BUG FIX<file_sep>/pygame/microgames/menuopts.py
from chooser import Chooser
from engine import Engine
from locals import *
def _opt_Start_Game(menu):
''' Callback for the "Start Game" menu option '''
games = [game for game,enabled in menu.game.microgames if enabled]
if len(games) > 0:
menu.game.change(Engine(menu.game, LIVES, games, menu))
def _opt_Tour(menu):
''' Callback for the "Tour" menu option '''
games = [game for game,enabled in menu.game.microgames if enabled]
menu.game.change(
Engine(menu.game, 50, games, menu, False))
def _opt_Microgames(menu):
menu.game.change(
Chooser(menu.game, menu.game.microgames, menu))
def _opt_Quit(menu):
''' Callback for the "Quit" menu option '''
menu.game.finished = True
def options():
return [ ('Start Game', _opt_Start_Game)
, ('Tour', _opt_Tour)
, ('Microgames', _opt_Microgames)
, ('Quit', _opt_Quit) ]
<file_sep>/hw3.py
###FILE FOR HW 3
###PARTNER = VIVIAN
""" <s>
<np> <vp>
<dp><adjp><n> | <pn> <tv><np> | <iv>
2 2
2 2 8
<dp> <adjp> <n>
"the" | "a" <adj> | <adj><adjp> "dog" | "cat" | "man" | "university" | "father" | "mother" | "child" | "television"
6 7
<pn> <adj>
"John" | "Jane" | "Sally" | "Spot" | "Fred" | "Elmo" "big" | "fat" | "green" | "wonderful" | "faulty" | "subliminal" | "pretentious"
4 4
<tv> <iv>
"hit" | "honored" | "kissed" | "helped" "died" | "collased" | "laughed" | "wept"
"""
from random import randint
def s():
return np().capitalize() + " " + vp() + "."
def np():
if(randint(0,1)):
return pn()
else:
return dp() + " " + adjp() + " " + n()
def vp():
if(randint(0,1)):
return tv() + " " + np()
else:
return iv()
def dp():
return ["the","a"][randint(0,1)]
def adjp():
if(randint(0,1)):
return adj() + " " + adjp()
else:
return adj()
def adj():
return ["big" , "fat" , "green" , "wonderful" , "faulty" , "subliminal" , "pretentious"][randint(0,6)]
def n():
return ["dog", "cat", "man", "university", "father", "mother", "child", "television"][randint(0,7)]
def pn():
return ["John", "Jane", "Sally", "Spot", "Fred", "Elmo"][randint(0,5)]
def tv():
return ["hit", "honored", "kissed", "helped"][randint(0,3)]
def iv():
return ["died", "collased", "laughed", "wept"][randint(0,3)]
print s()<file_sep>/pygame/microgames/games/lineMathCombo/game.py
# Pygame imports
import os.path
import pygame, pygame.mixer
from pygame import Surface
from pygame.image import load
from pygame.locals import *
from pygame.mixer import music
from pygame.rect import Rect
from pygame.sprite import Group, Sprite
# Random imports
from random import randint, choice
# Microgame-specific imports
import locals
from microgame import Microgame
##### LOADER-REQUIRED FUNCTIONS ################################################
def make_game():
return evade()
pass
def title():
return "Sensory Overload"
pass
def thumbnail():
return os.path.join("games", "lineMathCombo", "logoHD.png")
pass
def hint():
return "Don't get overloaded!"
pass
################################################################################
def _load_image(name, x, y):
'''
Loads an image file, returning the surface and rectangle corresponding to
that image at the given location.
'''
try:
image = load(name)
if image.get_alpha is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, msg:
print 'Cannot load image: {}'.format(name)
raise SystemExit, msg
rect = image.get_rect().move(x, y)
return image, rect
##### MODEL CLASSES ###########################################################
#evade
ICICLE_WIDTH = 50
class ee_icicle(Sprite):
def __init__(self, y):
Sprite.__init__(self)
imgpath = os.path.join("games", "lineMathCombo", "damage.png")
self.image, self.rect = _load_image(imgpath, 0, 0)
self.rect.bottom = y
self.rect.left = randint(0, locals.WIDTH / 3 - ICICLE_WIDTH)
self.velocity = 1
def update(self):
self.rect.y += self.velocity
self.velocity += 2
if self.rect.top > locals.HEIGHT:
asdf = randint(1, 20)
if asdf == 1:
self.rect.top = 0
self.rect.left = randint(0, locals.WIDTH / 3 - ICICLE_WIDTH)
self.velocity = 0
class eeskimo(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = os.path.join("games", "lineMathCombo", "snowguy.png")
self.image, self.rect = _load_image(imgpath, 60, 60)
self.rect.bottom = 700
self.rect.left = 120
#self.velocity = 0
def update(self):
#self.rect.x += self.velocity
pass
#line
class e_icicle(Sprite):
def __init__(self):
Sprite.__init__(self)
imgRand = randint(0,1)
if(imgRand):
imgpath = os.path.join("games", "lineMathCombo", "retro.png")
else:
imgpath = os.path.join("games","lineMathCombo","syspref.png")
self.image, self.rect = _load_image(imgpath, 0, 0)
#self.rect.bottom = y
#self.rect.left = randint(0, locals.WIDTH / 3 - ICICLE_WIDTH)
self.rect.left = 0
posRand = randint(0,2)
if posRand == 0:
self.rect.centery = locals.HEIGHT/8
elif posRand == 1:
self.rect.centery = 2*locals.HEIGHT/8
else:
self.rect.centery = 3*locals.HEIGHT/8
self.velocity = 1
def update(self):
#self.rect.y += self.velocity
self.rect.x += self.velocity
self.velocity += 1
if self.rect.right > locals.WIDTH:
asdf = randint(1, 20)
if asdf == 1:
#self.rect.top = 0
#self.rect.left = randint(0, locals.WIDTH / 3 - ICICLE_WIDTH)
imgRand = randint(0,1)
if(imgRand):
imgpath = os.path.join("games", "lineMathCombo", "retro.png")
else:
imgpath = os.path.join("games","lineMathCombo","syspref.png")
self.image, self.rect = _load_image(imgpath, 0, 0)
self.rect.left = 0
posRand = randint(0,2)
if posRand == 0:
self.rect.centery = locals.HEIGHT/8
elif posRand == 1:
self.rect.centery = 2*locals.HEIGHT/8
else:
self.rect.centery = 3*locals.HEIGHT/8
self.velocity = 0
class eskimo(Sprite):
def __init__(self):
Sprite.__init__(self)
imgpath = os.path.join("games", "lineMathCombo", "fireguy.png")
self.image, self.rect = _load_image(imgpath, 60, 60)
self.rect.centery = 2*(locals.HEIGHT/8)
self.rect.left = 2*locals.WIDTH/3
#self.velocity = 0
def update(self):
#self.rect.x += self.velocity
pass
#maths
class rotatingNumber(Sprite):
def __init__(self, x, num):
Sprite.__init__(self)
self.num = num
imgpath = os.path.join("games","lineMathCombo",str(str(num)+".png"))
self.image, self.rect = _load_image(imgpath,300,100)
self.rect.centerx, self.rect.centery = int(x * locals.WIDTH), int(3.0 * locals.HEIGHT / 4)
def update(self):
pass
class rotatingOperation(Sprite):
def __init__(self, x, operation):
Sprite.__init__(self)
self.operation = operation
imgpath = os.path.join("games","lineMathCombo",self.operation + ".png")
self.image, self.rect = _load_image(imgpath,300,100)
self.rect.centerx, self.rect.centery = x, int(3.0 * locals.HEIGHT / 4)
def update(self):
pass
##### MICROGAME CLASS #########################################################
class evade(Microgame):
def __init__(self):
Microgame.__init__(self)
#line
self.e_icicles = [e_icicle(), e_icicle()]
self.e_eskimo = eskimo()
self.sprites = Group(self.e_eskimo, *self.e_icicles)
#maths
self.addans = randint(3, 9)
self.add1 = rotatingNumber(0.5, randint(0, self.addans))
self.add2 = rotatingNumber(5.0 / 6.0, self.addans - self.add1.num)
self.sub1 = rotatingNumber(0.5, randint(3, 9))
self.sub2 = rotatingNumber(5.0 / 6.0, randint(0, self.sub1.num))
self.subans = self.sub1.num - self.sub2.num
self.mod2 = rotatingNumber(5.0 / 6.0, randint(2, 4))
self.mod1 = rotatingNumber(0.5, randint(self.mod2.num + 1, 9))
self.modans = self.mod1.num % self.mod2.num
self.mod_2 = rotatingNumber(5.0 / 6.0, randint(2, 4))
self.mod_1 = rotatingNumber(0.5, randint(self.mod_2.num + 1, 9))
self.mod_ans = self.mod_1.num % self.mod_2.num
self.mod__2 = rotatingNumber(5.0 / 6.0, randint(2, 4))
self.mod__1 = rotatingNumber(0.5, randint(self.mod_2.num + 1, 9))
self.mod__ans = self.mod__1.num % self.mod__2.num
self.add = rotatingOperation(int(2.0 * locals.WIDTH / 3), "add")
self.sub = rotatingOperation(int(2.0 * locals.WIDTH / 3), "sub")
self.mod = rotatingOperation(int(2.0 * locals.WIDTH / 3), "mod")
self.stage = 0
self.i = 0
self.sprites1 = Group(self.add1, self.add2, self.add)
self.sprites2 = Group(self.sub1, self.sub2, self.sub)
self.sprites3 = Group(self.mod1, self.mod2, self.mod)
self.sprites4 = Group(self.mod_1, self.mod_2, self.mod)
self.sprites5 = Group(self.mod__1, self.mod__2, self.mod)
#evade
self.ee_icicles = [ee_icicle(0) ,ee_icicle(locals.HEIGHT + 70), ee_icicle(100)]
self.ee_eskimo = eeskimo()
self.esprites = Group(self.ee_eskimo, *self.ee_icicles)
def start(self):
#line
music.load(os.path.join("games", "lineMathCombo", "finalSound.wav"))
music.play()
#maths
self.answer = self.addans
self.winner = False
self.losing = 0
def stop(self):
#line
music.stop()
def update(self, events):
if self.losing == 0:
#evade
self.esprites.update()
keys = pygame.key.get_pressed()
if keys[K_q]:
self.win()
elif (keys[K_RIGHT] or keys[K_d]) and (keys[K_LEFT] or keys[K_a]):
pass
elif keys[K_LEFT] or keys[K_a]:
self.ee_eskimo.rect.x = max(self.ee_eskimo.rect.x - 15, 0)
elif keys[K_RIGHT] or keys[K_d]:
self.ee_eskimo.rect.x = min((locals.WIDTH / 3)-24, self.ee_eskimo.rect.x + 15)
for icicle in self.ee_icicles:
if self.ee_eskimo.rect.colliderect(icicle.rect):
self.winner = False
self.losing = 1
#line
self.sprites.update()
for event in events:
if event.type == KEYDOWN and (event.key == K_UP or event.key == K_w) and (event.key == K_DOWN or event.key == K_s):
pass
elif event.type == KEYDOWN and event.key == K_q:
self.win()
elif event.type == KEYDOWN and (event.key == K_UP or event.key == K_w):
if(self.e_eskimo.rect.centery == 2*locals.HEIGHT/8):
self.e_eskimo.rect.centery = locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == locals.HEIGHT/8):
self.e_eskimo.rect.centery = locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == 3*locals.HEIGHT/8):
self.e_eskimo.rect.centery = 2*locals.HEIGHT/8
elif event.type == KEYDOWN and (event.key == K_DOWN or event.key == K_s):
if(self.e_eskimo.rect.centery == 2*locals.HEIGHT/8):
self.e_eskimo.rect.centery = 3*locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == locals.HEIGHT/8):
self.e_eskimo.rect.centery = 2*locals.HEIGHT/8
elif(self.e_eskimo.rect.centery == 3*locals.HEIGHT/8):
self.e_eskimo.rect.centery = 3*locals.HEIGHT/8
for icicle in self.e_icicles:
if self.e_eskimo.rect.colliderect(icicle.rect):
self.winner = False
self.losing = 2
#maths
for event in events:
if event.type == KEYDOWN and event.key == K_q:
self.lose()
if event.type == KEYDOWN and event.key in (K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9):
dictt = {K_0 : 0, K_1 : 1, K_2 : 2, K_3 : 3, K_4 : 4, K_5 : 5, K_6 : 6, K_7 : 7, K_8 : 8, K_9 : 9}
if dictt[event.key] == self.answer:
if self.stage == 0:
self.answer = self.subans
self.stage = 1
elif self.stage == 1:
self.answer = self.modans
self.stage = 2
elif self.stage == 2:
self.stage = 3
self.answer = self.mod_ans
elif self.stage == 3:
self.stage = 4
self.answer = self.mod__ans
elif self.stage == 4:
self.stage = 5
self.winner = True
else:
self.winner = False
self.losing = 3
else:
self.i += 1
if self.i > 60:
self.lose()
def render(self, surface):
surface.fill((0, 0, 0))
if self.losing == 1:
#evade lose
imgpathhhhhhh = os.path.join("games", "lineMathCombo", "classicFail.png")
test_imageeeeee = pygame.image.load(imgpathhhhhhh)
surface.blit(test_imageeeeee,(locals.WIDTH / 2 - 323 , locals.HEIGHT / 2 - 38))
elif self.losing == 2:
#line lose
imgpathhhhhhhh = os.path.join("games", "lineMathCombo", "minimalistFail.png")
test_imageeeeeee = pygame.image.load(imgpathhhhhhhh)
surface.blit(test_imageeeeeee,(locals.WIDTH / 2 - 350, locals.HEIGHT / 2 - 346))
elif self.losing == 3:
imgpathhhhhhhhh = os.path.join("games", "lineMathCombo", "mathFail.png")
test_imageeeeeeee = pygame.image.load(imgpathhhhhhhhh)
surface.blit(test_imageeeeeeee,(locals.WIDTH / 2 -341, locals.HEIGHT / 2 - 118))
#maths lose
else:
#line
imgpathh = os.path.join("games", "lineMathCombo", "tile.png")
test_image = pygame.image.load(imgpathh)
surface.blit(test_image,(0,0))
imgpathhh = os.path.join("games", "lineMathCombo", "linesBG.png")
test_imagee = pygame.image.load(imgpathhh)
surface.blit(test_imagee,(377,0))
self.sprites.draw(surface)
#maths
imgpathhhh = os.path.join("games", "lineMathCombo", "mathBG.png")
test_imageee = pygame.image.load(imgpathhhh)
surface.blit(test_imageee,(377,768 / 2))
if self.stage == 0:
self.sprites1.draw(surface)
elif self.stage == 1:
self.sprites2.draw(surface)
elif self.stage == 2:
self.sprites3.draw(surface)
elif self.stage == 3:
self.sprites4.draw(surface)
elif self.stage == 4:
self.sprites5.draw(surface)
elif self.stage == 5:
imgpathhhhhh = os.path.join("games", "lineMathCombo", "finshed.png")
test_imageeeee = pygame.image.load(imgpathhhhhh)
surface.blit(test_imageeeee,(int(2.0 * locals.WIDTH / 3) - 213, int(3.0 * locals.HEIGHT / 4) - 27))
#evade
imgpathhhhh = os.path.join("games", "lineMathCombo", "tile.png")
test_imageeee = pygame.image.load(imgpathhhhh)
surface.blit(test_imageeee,(0,0))
self.esprites.draw(surface)
def get_timelimit(self):
return 15<file_sep>/loot/small/monster.py
'''
def monsterDiction(filename):
monsterNames = []
monsterLevels = []
monsterTypes = []
treasures = []
monsterDict = {}
f = open(filename).readlines()
f = [x.replace("\n", "") for x in f]
f.remove("Class,Type,Level,TreasureClass")
g = [item.split(",") for item in f]
for i in range(0, len(g)):
monsterNames.append(g[i][0])
monsterLevels.append(g[i][2])
monsterTypes.append(g[i][1])
treasures.append(g[i][3])
for i in range(0, len(g)):
monsterDict[monsterNames[i]] = [monsterLevels[i], monsterTypes[i], treasures[i]]
return monsterDict
print monsterDiction("monstats_copy.txt")
'''
import random
def monster(filename):
f = open(filename).readlines()
f = [x.replace("\n", "") for x in f]
f.remove("Class,Type,Level,TreasureClass")
g = [item.split(",") for item in f]
tc = g[random.randint(0,len(g)-1)][3]
return tc
print monster("monstats.txt")
'''
def armor(argument_from_previous):
armorDict = {}
armorNames = []
armorStats = []
f = open(filename).readlines()
f = [item.replace("\n", "") for item in f]
f.remove("name,minac,maxac")
g = [item.split(",") for item in f]
for i in range(0, len(g)):
armorNames.append(g[i][0])
for i in range(0, len(g)):
armorStats.append(g[i][0])
return diction
'''
def armor(item, filename):
with open(filename) as f:
lines = [n.replace("\n", "").split(",") for n in f.readlines()[1:]]
"""for i in range(0, len(g)):
if g[i][0] == item:
x = random.randint(int(g[i][1]), int(g[i][2]+1))
return x
"""
for i in lines:
if i[0] == item:
a = int(i[1])
b = int(i[2])
rand = random.randint(a, b)
return rand
print armor("Leather Armor", "armor.txt")
<file_sep>/hw5.py
'''
grammar = { "<s>" : ["<np> <vp"]
,"<np>" : ["<dp> <adjp> <n>","np>"]
, "<dp>" : ["<dp> <adjp> <n>", "<np>"]
, "<adjp>" : ["<adj>","<adj> <adjp>"]
, "<adj>" : ["big,""fat","green|wonderful|faulty|subliminal|pretentious"]
,"<n>" : ["dog","cat","man","university","father","mother","child","television"]
,"<pn>" : ["John|Jane|Sally|Spot|Fred|Elmo"]
,"<vp>" : ["<tv> <np>","<iv>"]
,"<tv>" : ["hit","honored","kissed","helped"]
,"<iv>" : "died","collapsed","laughed","wept"]
}
'''
def make_grammar(filename):
#string -> map(string
diction = {}
f = open(filename).readlines()
f = [item.replace("\n", "") for item in f]
g = [item.split("::=") for item in f]
for i in range(0, len(g)):
g[i][1] = g[i][1].split("|")
for i in range(0, len(g)):
diction[g[i][0]] = g[i][1]
return diction
def generate(grammer, tok):
#0. Determine if tok is a terminal or non-terminal
#1. Figure out the alternatives for the non-termal
#2. Choose one at random
#3. Return the string formed by concatenating all the terinals and results of expanding the non-terminals together.
if tok not in grammar:
return tok
else:
rules = grammar[tok]
alt = rules[random.randint(0,len(rules)-1)]
toks = alt.split()
return " ".join([generate(grammar, tok) for tok in toks])
print make_grammar("sentence_grammar.txt")
print make_grammar("operations.txt") | 01f1f68eaa74bf89838de50d48dde2b856270f37 | [
"Markdown",
"Python"
] | 49 | Markdown | oneski/SAAST-Summer-Program-Project | 1c544a6fe177f899ccb8e84e6897a430a43fff2c | 2826179d49440a8e2a9081ffd3dc73568cf5ef6c |
refs/heads/main | <file_sep>window.addEventListener("load", () => {
let blabla = document.querySelector(".location-city");
let long;
let lat;
let temperatureDescription = document.querySelector(
".temperature-description"
);
let tempDegree = document.querySelector(".temperature-degree");
let iconApp = document.querySelector(".iconApp");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
long = position.coords.longitude;
lat = position.coords.latitude;
let api = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=ec4ab7779202ce64d3fa01434baab683`;
console.log(api);
fetch(api)
.then((data) => {
return data.json();
})
.then((data) => {
console.log(data);
const temperature = Math.ceil(data.main.temp - 273.15);
const description = data.weather[0].description;
const city = data.name;
console.log(city);
// var currentdate = new Date();
// var datetime = "Last Sync: " + currentdate.getTimezoneOffset();
const icon = data.weather[0].icon;
//SET DOM ELEMEMTS
tempDegree.textContent = temperature;
temperatureDescription.textContent = description;
blabla.textContent = city;
iconApp.innerHTML = `<img src="http://openweathermap.org/img/wn/${icon}@4x.png" alt="" width="200" height="200" />`;
function currentTime() {
let date = new Date();
let hh = date.getHours();
let mm = date.getMinutes();
let ss = date.getSeconds();
let session = "AM";
if (hh == 0) {
hh = 12;
}
if (hh > 12) {
hh = hh - 12;
session = "PM";
}
hh = hh < 10 ? "0" + hh : hh;
mm = mm < 10 ? "0" + mm : mm;
ss = ss < 10 ? "0" + ss : ss;
let time = hh + ":" + mm + ":" + ss + " " + session;
document.getElementById("clock").innerText = time;
let t = setTimeout(function () {
currentTime();
}, 1000);
}
currentTime();
});
});
}
});
<file_sep># Weather-App
A simple weather app that has full functionality. However the CSS is messy and I will update it in the near future.
LINK : https://laportfolio.github.io/Weather-App/
| 815c0d69f94b9b2e2684d71c7f9df431c91e6034 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | LAPortfolio/Weather-App | dedb8ee24d0276495bcef2331ad840ae9995babb | 97c4207f6be118c627cf873bdc32730ae923f579 |
refs/heads/master | <repo_name>Faihope/Delani_studio<file_sep>/js/script.js
$(document).ready(function () {
$("#design").click(function () {
$("#describe-design").show();
$("#design").hide();
});
$("#describe-design").click(function () {
$("#design").show();
$("#describe-design").hide();
});
$("#develop").click(function () {
$("#describe-develop").show();
$("#develop").hide();
});
$("#describe-develop").click(function () {
$("#develop").show();
$("#describe-develop").hide();
});
$("#product").click(function () {
$("#describe-product").show();
$("#product").hide();
});
$("#describe-product").click(function () {
$("#product").show();
$("#describe-product").hide();
});
// hover effects on portfolio image one
$(".one").mouseenter(function () {
$("#one").show();
});
$(".one").mouseleave(function () {
$("#one").hide();
});
// hover effect on image two
$(".two").mouseenter(function () {
$("#two").show();
});
$(".two").mouseleave(function () {
$("#two").hide();
});
// hover effect on image three
$(".three").mouseenter(function () {
$("#three").show();
});
$(".three").mouseleave(function () {
$("#three").hide();
});
// hover effect on image four
$(".four").mouseenter(function () {
$("#four").show();
});
$(".four").mouseleave(function () {
$("#four").hide();
});
// hover effect on image five
$(".five").mouseenter(function () {
$("#five").show();
});
$(".five").mouseleave(function () {
$("#five").hide();
});
// hover effect on image six
$(".six").mouseenter(function () {
$("#six").show();
});
$(".six").mouseleave(function () {
$("#six").hide();
});
// hover effect on image seven
$(".seven").mouseenter(function () {
$("#seven").show();
});
$(".seven").mouseleave(function () {
$("#seven").hide();
});
// hover effect on image eight
$(".eight").mouseenter(function () {
$("#eight").show();
});
$(".eight").mouseleave(function () {
$("#eight").hide();
});
})
function submit() {
var enteredName = validName();
enteredName = document.getElementById("user").value;
validEmail()
message();
alert("Hey " + enteredName + " ,We have received your message. Thank you for reaching out to us.");
}
function validName() {
var name = document.getElementById("user").value;
if (name == "") {
alert("please provide your name");
document.getElementById("user").focus();
return false;
}
}
function validEmail() {
var email = document.getElementById("email").value;
if (email == "") {
alert("please provide your email");
document.email.email.focus();
return false;
}
}
function message() {
var message = document.getElementById("message").value;
if (message == "") {
alert("please input your message");
document.message.message.focus();
return true;
}
}
| e9f1a622ffd83e8a212d606ef4b0c9748edeb968 | [
"JavaScript"
] | 1 | JavaScript | Faihope/Delani_studio | 88380debedc71ecba23b0f2a016f0d8489d94602 | aa5ef26e8ec595868bc6e04a5423eaaf2113e3eb |
refs/heads/master | <repo_name>mdraganov/Telerik-Academy<file_sep>/C#/OOP/OOPPrinciplesPart1/AnimalHierarchy/Animals.cs
namespace AnimalHierarchy
{
using System;
using System.Linq;
class Animals
{
static void Main()
{
Animal[] animals =
{
new Dog("Rex", GEnder.Male, 3, "Pomiqr"),
new Dog("Jorko", GEnder.Male, 1, "Poodle"),
new Dog("Pepa", GEnder.Female, 5, "<NAME>"),
new Dog("Pesho", GEnder.Male, 2, "Pekingese"),
new Frog("Jabko", GEnder.Male, 1),
new Frog("Kikerica", GEnder.Female, 3),
new Cat("Maca", GEnder.Female, 5, "<NAME>"),
new Tomcat("Tom", 5),
new Tomcat("Gosho", 3),
new Kitten("Puhcho", 1, "Sphynx"),
};
double averageDogsAge = animals.Where(x => x is Dog).Average(x => x.Age);
double averageFrogsAge = animals.Where(x => x is Frog).Average(x => x.Age);
double averageCatsAge = animals.Where(x => x is Cat).Average(x => x.Age);
Console.WriteLine("Average age of the dogs: {0}", averageDogsAge);
Console.WriteLine("Average age of the frogs: {0}", averageFrogsAge);
Console.WriteLine("Average age of the cats: {0}", averageCatsAge);
}
}
}
<file_sep>/C#/OOP/DefiningClassesPartTwo/Structure/PathStorage.cs
namespace Structure
{
using System;
using System.IO;
using System.Linq;
public static class PathStorage
{
public static void Save(Path pathToSave)
{
using (StreamWriter writer = new StreamWriter(@"..\..\Paths.txt"))
{
writer.Write(pathToSave);
}
}
public static Path Load()
{
Path pathToLoad = new Path();
string[] pointsRead;
using (StreamReader reader = new StreamReader(@"..\..\Paths.txt"))
{
pointsRead = reader.ReadToEnd().Split();
}
foreach (string point in pointsRead)
{
double[] points = point.Split(',').Select(double.Parse).ToArray();
pathToLoad.AddPoint(new Point3D(points[0], points[1], points[2]));
}
return pathToLoad;
}
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Conditional statements/Conditional statements/07.The biggest of five numbers.js
function greatest() {
var a = document.getElementById('first-num7').value * 1,
b = document.getElementById('second-num7').value * 1,
c = document.getElementById('third-num7').value * 1,
d = document.getElementById('fourth-num7').value * 1,
e = document.getElementById('fifth-num7').value * 1,
greatest = a;
if (b > greatest) greatest = b;
if (c > greatest) greatest = c;
if (d > greatest) greatest = d;
if (e > greatest) greatest = e;
document.getElementById('answer7').innerHTML = greatest;
}<file_sep>/C#/OOP/DefiningClassesPartOne/DefineClass/Display.cs
namespace GSMInfo
{
using System;
public class Display
{
private float size;
private long colors;
public Display()
{
this.size = 2;
this.colors = 2;
}
public Display(float size)
: this()
{
this.Size = size;
}
public Display(float size, long colors)
: this(size)
{
this.Colors = colors;
}
public float Size
{
get { return this.size; }
set
{
if (value > 20)
{
throw new ArgumentException("Display size too big for a phone!");
}
if (value <= 0)
{
throw new ArgumentException("Display size should be positive!");
}
this.size = value;
}
}
public long Colors
{
get { return this.colors; }
set
{
if (value > long.MaxValue)
{
throw new ArgumentException("This display is too colorful!");
}
if (value <= 1)
{
throw new ArgumentException("Colors should be more than one!");
}
this.colors = value;
}
}
}
}
<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/DivideBy7And5/DivisionBy7And5.cs
//Write a Boolean expression that checks for given integer if it can be divided (without remainder) by 7 and 5 at the same time.
using System;
class DivisionBy7And5
{
static void Main()
{
Console.Write("Enter your number: ");
int number = int.Parse(Console.ReadLine());
bool result = number % 35 == 0;
Console.WriteLine(result);
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Using Objects/Using Objects/02.Remove elements.js
console.log('\nTask 2: Write a function that removes all elements with a given value. Attach it to the array type. Read about prototype and how to attach methods.');
function Arr(arr) {
this.arr = arr;
this.remove = function (element) {
var i,
len = this.arr.length;
for (i = 0; i < len; i += 1) {
if (this.arr[i] === element) this.arr.splice(i, 1);
}
}
this.toString = function () {
var result = this.arr.join(', ');
return result;
}
}
console.log('var arr = 1, 2, 1, 4, 1, 3, 4, 1, 111, 3, 2, 1, \'1\'');
var arr = new Arr([1, 2, 1, 4, 1, 3, 4, 1, 111, 3, 2, 1, '1']);
arr.remove(1);
console.log('arr.remove(1)');
console.log(arr.toString());<file_sep>/C#/OOP/DefiningClassesPartOne/DefineClass/Call.cs
namespace GSMInfo
{
using System;
using System.Collections.Generic;
public class Call
{
private DateTime date;
private long dialedNumber;
private long duration;
public Call(DateTime date, long dialedNumber, long duration)
{
this.Date = date;
this.DialedNumber = dialedNumber;
this.Duration = duration;
}
public DateTime Date
{
get { return date; }
set { this.date = value; }
}
public long DialedNumber
{
get { return dialedNumber; }
set { this.dialedNumber = value; }
}
public long Duration
{
get { return duration; }
set { this.duration = value; }
}
public override string ToString()
{
return string.Format("Call date: {0}\nDialed number: {1}\nCall duration (sec): {2}", this.Date, this.DialedNumber, this.Duration);
}
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart2/RangeExceptions/InvalidRangeException.cs
namespace RangeExceptions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class InvalidRangeException<T> : ApplicationException
{
public T StartValue { get; set; }
public T EndValue { get; set; }
public InvalidRangeException(string message, T start, T end, Exception e)
: base("Parameters out of range.")
{
this.StartValue = start;
this.EndValue = end;
}
public InvalidRangeException(string message, T start, T end)
: this(message, start, end, null)
{
}
public InvalidRangeException(T start, T end)
: this(null, start, end, null)
{
}
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Using Objects/Using Objects/01.Planar coordinates.js
console.log('Task 1: Write functions for working with shapes in standard Planar coordinate system. Points are represented by coordinates P(X, Y) Lines are represented by two points, marking their beginning and ending L(P1(X1,Y1), P2(X2,Y2)) Calculate the distance between two points. Check if three segment lines can form a triangle.');
function Line(p1, p2) {
this.p1 = p1;
this.p2 = p2;
}
function Point(x, y) {
this.x = x;
this.y = y;
this.distanceToOtherPoint = function (otherPoint) {
var distX = this.x - otherPoint.x,
distY = this.y - otherPoint.y,
distance = Math.sqrt(distX * distX + distY * distY);
return distance;
}
}
function isTriangle(line1, line2, line3) {
var line1Length = line1.p1.distanceToOtherPoint(line1.p2),
line2Length = line2.p1.distanceToOtherPoint(line2.p2),
line3Length = line3.p1.distanceToOtherPoint(line3.p2);
return line1Length + line2Length > line3Length &&
line1Length + line3Length > line2Length &&
line2Length + line3Length > line1Length;
}
var a = new Point(2, 1),
b = new Point(14, 1),
c = new Point(7, 8),
ab = new Line(a, b),
bc = new Line(b, c),
ac = new Line(c, a);
console.log('AB length is: ' + a.distanceToOtherPoint(b));
console.log('BC length is: ' + b.distanceToOtherPoint(c));
console.log('AC length is: ' + a.distanceToOtherPoint(c));
console.log('Triangle AB BC CA exists? - ' + isTriangle(ab, bc, ac));<file_sep>/C#/OOP/CommonTypeSystem/Student/Enumarations/University.cs
namespace Student.Enumarations
{
public enum University
{
Harvad,
Cambridge,
LSE
}
}<file_sep>/Java Script/JavaScript OOP/Modules and Patterns/tasks/task-1.js
/* Task Description */
/*
* Create a module for a Telerik Academy course
* The course has a title and presentations
* Each presentation also has a title
* There is a homework for each presentation
* There is a set of students listed for the course
* Each student has firstname, lastname and an ID
* IDs must be unique integer numbers which are at least 1
* Each student can submit a homework for each presentation in the course
* Create method init
* Accepts a string - course title
* Accepts an array of strings - presentation titles
* Throws if there is an invalid title
* Titles do not start or end with spaces
* Titles do not have consecutive spaces
* Titles have at least one character
* Throws if there are no presentations
* Create method addStudent which lists a student for the course
* Accepts a string in the format 'Firstname Lastname'
* Throws if any of the names are not valid
* Names start with an upper case letter
* All other symbols in the name (if any) are lowercase letters
* Generates a unique student ID and returns it
* Create method getAllStudents that returns an array of students in the format:
* {firstname: 'string', lastname: 'string', id: StudentID}
* Create method submitHomework
* Accepts studentID and homeworkID
* homeworkID 1 is for the first presentation
* homeworkID 2 is for the second one
* ...
* Throws if any of the IDs are invalid
* Create method pushExamResults
* Accepts an array of items in the format {StudentID: ..., Score: ...}
* StudentIDs which are not listed get 0 points
* Throw if there is an invalid StudentID
* Throw if same StudentID is given more than once ( he tried to cheat (: )
* Throw if Score is not a number
* Create method getTopStudents which returns an array of the top 10 performing students
* Array must be sorted from best to worst
* If there are less than 10, return them all
* The final score that is used to calculate the top performing students is done as follows:
* 75% of the exam result
* 25% the submitted homework (count of submitted homeworks / count of all homeworks) for the course
*/
function solve() {
function validateCourse(title, presentations) {
var index,
length;
if (/^ .*|.* $| /.test(title) || title.length < 1) {
throw new Error('Course title does not match criterea!');
}
if (typeof presentations === 'undefined' || !presentations[0]) {
throw new Error('Enter presentations!');
}
length = presentations.length;
for (index = 0; index < length; index += 1) {
if (/^ .*|.* $| /.test(presentations[index]) || presentations[index].length < 1) {
throw new Error('Presentation ' + (index + 1) + ' title does not match criterea!');
}
}
}
function validateStudent(names) {
if (names.length !== 2) {
throw new Error('Enter two names!');
}
if (!/^[A-Z][a-z]*/.test(names[0]) || !/^[A-Z][a-z]*/.test(names[1])) {
throw new Error('Invalid student name!');
}
}
var Course = {
init: function (title, presentations) {
this.presentations = presentations;
this.students = [];
validateCourse(title, presentations);
return this;
},
addStudent: function (name) {
var names = name.split(' '),
student = {
firstname: names[0],
lastname: names[1],
id: this.students.length + 1,
homeworks: [],
score: 0,
finalScore: 0
};
validateStudent(names);
this.students.push(student);
return student.id;
},
getAllStudents: function () {
var index,
result = [],
length = this.students.length;
for (index = 0; index < length; index += 1) {
result.push({
firstname: this.students[index].firstname,
lastname: this.students[index].lastname,
id: this.students[index].id
});
}
return result;
},
submitHomework: function (studentID, homeworkID) {
if (homeworkID > this.presentations.length ||
studentID > this.students.length ||
homeworkID < 1 ||
studentID < 1) {
throw new Error('Invalid ID!');
}
this.students[studentID - 1].homeworks.push(homeworkID);
return this;
},
pushExamResults: function (results) {
var index,
studentFound,
lengthSt = this.students.length;
if (!results || !results[0]) {
throw new Error('No arguments error!');
}
for (var res in results) {
studentFound = false;
if (isNaN(results[res].score)) {
throw new Error('Score is not a number!');
}
for (index = 0; index < lengthSt; index += 1) {
if (this.students[index].id === results[res].StudentID) {
if (this.students[index].score !== 0) {
throw new Error('Cheating student!');
}
this.students[index].score = results[res].score;
this.students[index].finalScore = this.students[index].score * 0.75 + this.students[index].homeworks.length * 0.25;
studentFound = true;
break;
}
}
if (!studentFound) {
throw new Error('Invalid student ID!');
}
}
},
getTopStudents: function () {
var index,
result = [],
sortedStudents = this.students.sort(function (s1, s2) {
return s2.finalScore - s1.finalScore;
});
for (index = 0; index < 10; index += 1) {
if (sortedStudents[index]) {
result[index] = sortedStudents[index];
} else {
break;
}
}
return result;
}
};
return Course;
}
// var test = Object.create(solve()).init('some course', ['first ppt', 'second ppt']);
// test.addStudent('<NAME>');
// test.addStudent('<NAME>');
// test.addStudent('<NAME>');
// test.submitHomework(1, 2).submitHomework(2, 1).pushExamResults([{StudentID: 1, score: 3}, {StudentID: 2, score: 5}]);
// console.log(test.getTopStudents());
module.exports = solve;
<file_sep>/C#/C# Programming Part I/Loops/CatalanNumbers/CalculateCatalanNumbers.cs
//In combinatorics, the Catalan numbers are calculated by the following formula: catalan-formula
//Write a program to calculate the nth Catalan number by given n (1 <= n <= 100).
using System;
class CalculateCatalanNumbers
{
static void Main()
{
Console.Write("Enter n (1 <= n <= 100)\nn: ");
int n = int.Parse(Console.ReadLine());
decimal nFactorial = 1m;
decimal kFactorial = 1m;
for (int i = n + 1; i <= n * 2; i++)
{
nFactorial *= i;
}
for (int i = 1; i <= n + 1; i++)
{
kFactorial *= i;
}
decimal result = nFactorial / kFactorial;
Console.WriteLine(result);
}
}
<file_sep>/C#/C# Programming Part II/StringsAndTextProcessing/StringLength/PrintAStringOf20.cs
//Write a program that reads from the console a string of maximum 20 characters.
//If the length of the string is less than 20, the rest of the characters should be filled with *.
//Print the result string into the console.
using System;
using System.Text;
class PrintAStringOf20
{
static void Main()
{
string input = Console.ReadLine();
StringBuilder result = new StringBuilder(20);
for (int i = 0; i < 20; i++)
{
if (i >= input.Length)
{
result.Append('*');
}
else
{
result.Append(input[i]);
}
}
Console.WriteLine(result);
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart2/BankAccounts/Customers/Customer.cs
namespace BankAccounts.Customers
{
public abstract class Customer : IClient
{
public string Name { get; set; }
public string Address { get; set; }
}
}
<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/PointInACircle/CheckPointLocation.cs
//Write an expression that checks if given point (x, y) is inside a circle K({0, 0}, 2).
using System;
class CheckPointLocation
{
static void Main()
{
Console.Write("Enter x coordinate: ");
double x = double.Parse(Console.ReadLine());
Console.Write("Enter y coordinate: ");
double y = double.Parse(Console.ReadLine());
Console.WriteLine(Math.Sqrt(x * x + y * y) <= 2);
}
}
<file_sep>/C#/C# Programming Part II/UsingClassesAndObjects/LeapYear/LeapYearChecker.cs
//Write a program that reads a year from the console and checks whether it is a leap one.
//Use System.DateTime.
using System;
class LeapYearChecker
{
static void Main()
{
Console.Write("Enter an year: ");
int input = int.Parse(Console.ReadLine());
Console.WriteLine("Is leap: {0}", DateTime.IsLeapYear(input));
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart1/SchoolClasses/People.cs
namespace SchoolClasses
{
using System;
public abstract class People
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Comment { get; set; }
}
}
<file_sep>/C#/C# Programming Part II/Methods/NumberAsArray/Sum.cs
//Write a method that adds two positive integer numbers represented as arrays of digits (each array element arr[i] contains a digit; the last digit is kept in arr[0]).
//Each of the numbers that will be added could have up to 10 000 digits.
using System;
using System.Collections.Generic;
class Sum
{
static void Main()
{
Console.Write("Enter a number: ");
char[] firstNum = Console.ReadLine().ToCharArray();
Console.Write("Enter a second number: ");
char[] secondNum = Console.ReadLine().ToCharArray();
Array.Reverse(firstNum);
Array.Reverse(secondNum);
List<int> result = new List<int>();
bool residual = false;
for (int i = 0; i < Math.Max(firstNum.Length, secondNum.Length) + 1; i++)
{
int firstArrayDigit = i < firstNum.Length ? firstNum[i] - '0' : 0;
int secondArrayDigit = i < secondNum.Length ? secondNum[i] - '0' : 0;
int digitsSum = firstArrayDigit + secondArrayDigit;
bool isThereResidual = false;
if (digitsSum > 9)
{
digitsSum %= 10;
isThereResidual = true;
}
if (residual)
{
result.Add(digitsSum + 1);
residual = false;
}
else result.Add(digitsSum);
if (isThereResidual) residual = true;
}
result.Reverse();
if (result[0] == 0) result.Remove(0);
for (int i = 0; i < result.Count; i++)
{
Console.Write(result[i]);
}
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart2/BankAccounts/Accounts/BankAccount.cs
namespace BankAccounts.Accounts
{
using System;
using BankAccounts.Customers;
public abstract class BankAccount
{
public IClient Client { get; set; }
public decimal Balance { get; set; }
public decimal InterestRate { get; set; }
public DateTime AccountStartDate { get; set; }
public virtual decimal CalculateInterest(int months)
{
return this.InterestRate * months;
}
public void DepositMoney(decimal sum)
{
this.Balance += sum;
}
}
}
<file_sep>/C#/C# Programming Part II/Methods/AddingPolynomials/PolynomialsSumator.cs
//Write a method that adds two polynomials.
//Represent them as arrays of their coefficients.
//Example:
//x2 + 5 = 1x2 + 0x + 5 => {5, 0, 1}
using System;
class PolynomialsSumator
{
static void Main()
{
int[] firstPolynomial = { 5, 0, 2, 6 };
int[] secondPolynomial = { 5, 2, 3 };
Console.Write("The sum of the two polynomials is: ");
SumPolynomials(firstPolynomial, secondPolynomial);
}
private static void SumPolynomials(int[] firstPoly, int[] secondPoly)
{
int[] polySum = new int[Math.Max(firstPoly.Length, secondPoly.Length)];
for (int i = polySum.Length - 1; i >= 0; i--)
{
int firstPolyCoeff = i < firstPoly.Length ? firstPoly[i] : 0;
int secondPolyCoeff = i < secondPoly.Length ? secondPoly[i] : 0;
polySum[i] = firstPolyCoeff + secondPolyCoeff;
if (i > 1)
{
Console.Write("{0}x^{1} + ", polySum[i], i);
}
else if (i == 1)
{
Console.Write("{0}x + ", polySum[i]);
}
else
{
Console.WriteLine(polySum[i]);
}
}
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart2/BankAccounts/Accounts/Mortgage.cs
namespace BankAccounts.Accounts
{
using BankAccounts.Customers;
class Mortgage : BankAccount
{
public override decimal CalculateInterest(int months)
{
if (this.Client is Individual)
{
if (months <= 6)
{
return 0;
}
else
{
months -= 6;
}
}
else
{
if (months <= 12)
{
return base.CalculateInterest(months) / 2;
}
else
{
return base.CalculateInterest(12) / 2 + base.CalculateInterest(months - 12);
}
}
return base.CalculateInterest(months);
}
}
}<file_sep>/C#/OOP/DefiningClassesPartTwo/VersionAttribute/Test.cs
namespace VersionAttribute
{
using System;
[VersionAttribute("2.10")]
class Test
{
static void Main()
{
Type type = typeof(Test);
var attribute = type.GetCustomAttributes(false);
foreach (VersionAttribute item in attribute)
{
Console.WriteLine(item.GetType().Name);
Console.WriteLine("Version[{0}.{1}]", item.Major, item.Minor);
}
}
}
}
<file_sep>/C#/C# Programming Part II/StringsAndTextProcessing/DateDifference/Days.cs
//Write a program that reads two dates in the format: day.month.year and calculates the number of days between them.
using System;
class Days
{
static void Main()
{
DateTime firstDate = DateTime.Parse(Console.ReadLine());
DateTime secondDate = DateTime.Parse(Console.ReadLine());
Console.WriteLine(Math.Abs(secondDate.Subtract(firstDate).Days));
}
}
<file_sep>/C#/C# Programming Part I/ConditionalStatements/NumberAsWords/ConvertNumbersToWords.cs
//Write a program that converts a number in the range [0…999] to words, corresponding to the English pronunciation.
using System;
class ConvertNumbersToWords // a little longer than it has to be but at least it works
{
static void Main()
{
while (true)
{
Console.Write("Enter a 3 digit number: ");
string input = Console.ReadLine();
int number = int.Parse(input);
if (input.Length == 1)
{
string theNumber = "";
if (number == 0)
{
theNumber = "Zero";
}
else if (number == 1)
{
theNumber = "One";
}
else if (number == 2)
{
theNumber = "Two";
}
else if (number == 3)
{
theNumber = "Three";
}
else if (number == 4)
{
theNumber = "Four";
}
else if (number == 5)
{
theNumber = "Five";
}
else if (number == 6)
{
theNumber = "Six";
}
else if (number == 7)
{
theNumber = "Seven";
}
else if (number == 8)
{
theNumber = "Eight";
}
else if (number == 9)
{
theNumber = "Nine";
}
Console.WriteLine(theNumber);
}
else if (input.Length == 2)
{
int digit1 = Convert.ToInt32(input[0].ToString());
int digit2 = Convert.ToInt32(input[1].ToString());
if (digit1 == 1)
{
switch (number)
{
case 10:
Console.WriteLine("Ten");
break;
case 11:
Console.WriteLine("Eleven");
break;
case 12:
Console.WriteLine("Twelve");
break;
case 13:
Console.WriteLine("Thirteen");
break;
case 14:
Console.WriteLine("Fourteen");
break;
case 15:
Console.WriteLine("Fifteen");
break;
case 16:
Console.WriteLine("Sixteen");
break;
case 17:
Console.WriteLine("Seventeen");
break;
case 18:
Console.WriteLine("Eighteen");
break;
case 19:
Console.WriteLine("Nineteen");
break;
default:
break;
}
}
else
{
string firstDigit = "";
string secondDigit = "";
if (digit1 == 2)
{
firstDigit = "Twenty";
}
else if (digit1 == 3)
{
firstDigit = "Thirty";
}
else if (digit1 == 4)
{
firstDigit = "Fourty";
}
else if (digit1 == 5)
{
firstDigit = "Fifty";
}
else if (digit1 == 6)
{
firstDigit = "Sixty";
}
else if (digit1 == 7)
{
firstDigit = "Seventy";
}
else if (digit1 == 8)
{
firstDigit = "Eighty";
}
else if (digit1 == 9)
{
firstDigit = "Ninety";
}
if (digit2 == 1)
{
secondDigit = "one";
}
else if (digit2 == 2)
{
secondDigit = "two";
}
else if (digit2 == 3)
{
secondDigit = "three";
}
else if (digit2 == 4)
{
secondDigit = "four";
}
else if (digit2 == 5)
{
secondDigit = "five";
}
else if (digit2 == 6)
{
secondDigit = "six";
}
else if (digit2 == 7)
{
secondDigit = "seven";
}
else if (digit2 == 8)
{
secondDigit = "eight";
}
else if (digit2 == 9)
{
secondDigit = "nine";
}
if (digit2 == 0)
{
Console.WriteLine(firstDigit);
}
else
{
Console.WriteLine(firstDigit + " " + secondDigit);
}
}
}
else
{
int digit1 = Convert.ToInt32(input[0].ToString());
int digit2 = Convert.ToInt32(input[1].ToString());
int digit3 = Convert.ToInt32(input[2].ToString());
string firstDigit = "";
string secondDigit = "";
string thirdDigit = "";
if (digit1 == 1)
{
firstDigit = "One hundred";
}
else if (digit1 == 2)
{
firstDigit = "Two hundred";
}
else if (digit1 == 3)
{
firstDigit = "Three hundred";
}
else if (digit1 == 4)
{
firstDigit = "Four hundred";
}
else if (digit1 == 5)
{
firstDigit = "Five hundred";
}
else if (digit1 == 6)
{
firstDigit = "Six hundred";
}
else if (digit1 == 7)
{
firstDigit = "Seven hundred";
}
else if (digit1 == 8)
{
firstDigit = "Eight hundred";
}
else if (digit1 == 9)
{
firstDigit = "Nine hundred";
}
if (digit2 == 2)
{
secondDigit = "Twenty";
}
else if (digit2 == 3)
{
secondDigit = "Thirty";
}
else if (digit2 == 4)
{
secondDigit = "Fourty";
}
else if (digit2 == 5)
{
secondDigit = "Fifty";
}
else if (digit2 == 6)
{
secondDigit = "Sixty";
}
else if (digit2 == 7)
{
secondDigit = "Seveny";
}
else if (digit2 == 8)
{
secondDigit = "Eighty";
}
else if (digit2 == 9)
{
secondDigit = "Ninety";
}
if (digit3 == 1)
{
thirdDigit = "one";
}
else if (digit3 == 2)
{
thirdDigit = "two";
}
else if (digit3 == 3)
{
thirdDigit = "three";
}
else if (digit3 == 4)
{
thirdDigit = "four";
}
else if (digit3 == 5)
{
thirdDigit = "five";
}
else if (digit3 == 6)
{
thirdDigit = "six";
}
else if (digit3 == 7)
{
thirdDigit = "seven";
}
else if (digit3 == 8)
{
thirdDigit = "eight";
}
else if (digit3 == 9)
{
thirdDigit = "nine";
}
if (digit2 == 0 && digit3 == 0)
{
Console.WriteLine(firstDigit);
}
else if (digit2 == 1)
{
switch (digit3)
{
case 0:
Console.WriteLine(firstDigit + " and ten");
break;
case 1:
Console.WriteLine(firstDigit + " and eleven");
break;
case 2:
Console.WriteLine(firstDigit + " and twelve");
break;
case 3:
Console.WriteLine(firstDigit + " and thirteen");
break;
case 4:
Console.WriteLine(firstDigit + " and fourteen");
break;
case 5:
Console.WriteLine(firstDigit + " and fifteen");
break;
case 6:
Console.WriteLine(firstDigit + " and sixteen");
break;
case 7:
Console.WriteLine(firstDigit + " and seventeen");
break;
case 8:
Console.WriteLine(firstDigit + " and eighteen");
break;
case 9:
Console.WriteLine(firstDigit + " and nineteen");
break;
default:
break;
}
}
else if (digit3 == 0)
{
Console.WriteLine(firstDigit + " and " + secondDigit.ToLower());
}
else if (digit2 == 0)
{
Console.WriteLine(firstDigit + " and " + thirdDigit);
}
else
{
Console.WriteLine(firstDigit + " and " + secondDigit.ToLower() + " " + thirdDigit);
}
}
}
}
}<file_sep>/C#/C# Programming Part I/ConsoleInputOutput/PrintCompanyInformation/CompanyInfo.cs
//A company has name, address, phone number, fax number, web site and manager. The manager has first name, last name, age and a phone number.
//Write a program that reads the information about a company and its manager and prints it back on the console.
using System;
class CompanyInfo
{
static void Main()
{
Console.WriteLine("Please enter the company info below.");
Console.Write("Company name: ");
string companyName = Console.ReadLine();
Console.Write("Company address: ");
string companyAddress = Console.ReadLine();
Console.Write("Phone number: ");
string phoneNumber = Console.ReadLine();
Console.Write("Fax number: ");
string faxNumber = Console.ReadLine();
Console.Write("Web site: ");
string webSite = Console.ReadLine();
Console.Write("Manager firs name: ");
string managerFirstName = Console.ReadLine();
Console.Write("Manager last name: ");
string managerLastName = Console.ReadLine();
Console.Write("Manager age: ");
string managerAge = Console.ReadLine();
Console.Write("Manager phone: ");
string managerPhone = Console.ReadLine();
Console.WriteLine("{0}\nAddress: {1}\nTel. {2}\nFax: {3}\nWeb Site: {4}\nManager: {5} {6} (age: {7}, tel. {8})", companyName, companyAddress, phoneNumber, faxNumber, webSite, managerFirstName, managerLastName, managerAge, managerPhone);
}
}
<file_sep>/C#/C# Programming Part II/MultidimensionalArrays/SortByStringLength/StringSorter.cs
//You are given an array of strings. Write a method that sorts
//the array by the length of its elements (the number of characters composing them).
using System;
class StringSorter
{
static void Main()
{
Console.Write("Please enter a few words separated by space: ");
string[] stringArray = Console.ReadLine().Split();
Array.Sort(stringArray, (x, y) => x.Length.CompareTo(y.Length)); ;
Console.WriteLine(string.Join(" ", stringArray));
}
}
<file_sep>/HTML Basics/HTMLFundamentals/SocialSite/Friends.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Doge Social Network - Home</title>
</head>
<body bgcolor="#B5DAFF">
<h1>Doge Social Network</h1>
<ul>
<li><a href="Home.html">Home</a></li>
<li><a href="Profile.html">Profile</a></li>
<li><a href="Friends.html">Friends</a></li>
</ul>
<hr />
<h2>Friends of Doge</h2>
<hr />
<i>Such Friend</i>
<br />
best friend
<br />
<i>Many Friends</i>
<br />
unknown
<br />
<i>Wow</i>
<br />
yeah, right
</body>
</html>
<file_sep>/C#/OOP/OOPPrinciplesPart1/People/Test.cs
namespace People
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
List<Student> classOfStudents = new List<Student>();
classOfStudents.Add(new Student("Svetla", "Draganova", 3));
classOfStudents.Add(new Student("Georgi", "Ivanov", 9));
classOfStudents.Add(new Student("Ivan", "Petrov", 3));
classOfStudents.Add(new Student("Chavdar", "Kamenov", 10));
classOfStudents.Add(new Student("Ivan", "Kozhuharov", 10));
classOfStudents.Add(new Student("Georgi", "Stoyanov", 1));
classOfStudents.Add(new Student("Ivan", "Kovachev", 6));
classOfStudents.Add(new Student("Stefan", "Petrov", 6));
classOfStudents.Add(new Student("Martin", "Atanasov", 12));
classOfStudents.Add(new Student("Veronika", "Govedarova", 2));
foreach (var student in classOfStudents)
{
Console.WriteLine(student);
}
Console.WriteLine();
var orderedStudents = classOfStudents.OrderBy(gr => gr.Grade);
foreach (var student in orderedStudents)
{
Console.WriteLine(student);
}
Console.WriteLine();
List<Worker> someWorkers = new List<Worker>();
someWorkers.Add(new Worker("Simeon", "Petrov", 993, 12));
someWorkers.Add(new Worker("Severin", "Lakov", 809, 15));
someWorkers.Add(new Worker("Kliment", "Evgeniev", 384, 3));
someWorkers.Add(new Worker("Aleksandar", "Simeonov", 828, 1));
someWorkers.Add(new Worker("Teodor", "Hristov", 675, 4));
someWorkers.Add(new Worker("Andrey", "Sotirov", 688, 17));
someWorkers.Add(new Worker("Eleonora", "Viktorova", 589, 8));
someWorkers.Add(new Worker("Zafir", "Kaloyanov", 904, 18));
someWorkers.Add(new Worker("Plamen", "Antonov", 947, 8));
someWorkers.Add(new Worker("Fabian", "Kornelov", 970, 15));
foreach (var worker in someWorkers)
{
Console.WriteLine(worker);
}
Console.WriteLine();
var sortedWorkers =
from workers in someWorkers
orderby workers.MoneyPerHour()
select workers;
foreach (var worker in sortedWorkers)
{
Console.WriteLine(worker);
}
Console.WriteLine();
List<Human> people = new List<Human>();
people.AddRange(classOfStudents);
people.AddRange(someWorkers);
var sortedPeople = people.OrderBy(l => l.LastName).OrderBy(f => f.FirstName);
foreach (var person in sortedPeople)
{
Console.WriteLine(person.FirstName + " " + person.LastName);
}
}
}
}
<file_sep>/C#/C# Programming Part I/ConditionalStatements/BeerTime/IsItTimeForBeer.cs
//A beer time is after 1:00 PM and before 3:00 AM.
//Write a program that enters a time in format “hh:mm tt” (an hour in range [01...12], a minute in range [00…59] and AM / PM designator) and prints beer time or non-beer time
//according to the definition above or invalid time if the time cannot be parsed. Note: You may need to learn how to parse dates and times.
using System;
class IsItTimeForBeer
{
static void Main()
{
while (true)
{
Console.Write("Enter time in hh:mm tt format: ");
string timeInput = Console.ReadLine();
DateTime beerTimeStart = DateTime.Parse("1:00 PM");
DateTime beerTimeEnd = DateTime.Parse("3:00 AM");
DateTime time;
if (DateTime.TryParse(timeInput, out time))
{
if (time >= beerTimeStart && time < beerTimeEnd.AddDays(1) || time < beerTimeEnd)
{
Console.WriteLine("beer time");
}
else
{
Console.WriteLine("non-beer time");
}
}
else
{
Console.WriteLine("invalid time");
}
}
}
}<file_sep>/C#/OOP/OOPPrinciplesPart2/BankAccounts/Customers/IClient.cs
namespace BankAccounts.Customers
{
public interface IClient
{
string Name { get; set; }
string Address { get; set; }
}
}
<file_sep>/C#/C# Programming Part II/Arrays/BinarySearch/BinarySearch.cs
//Write a program that finds the index of given element in a sorted array of integers by using the Binary search algorithm.
using System;
class BinarySearch
{
static void Main()
{
Console.Write("Please enter a row of sorted integers separated by space: ");
string[] inputArray = Console.ReadLine().Split();
int[] sortedArray = new int[inputArray.Length];
for (int i = 0; i < inputArray.Length; i++)
{
sortedArray[i] = int.Parse(inputArray[i]);
}
Console.Write("Please enter the number you want the index of: ");
int n = int.Parse(Console.ReadLine());
bool indexFound = false;
int index = 0;
int devisor = 2;
int subsetMiddle = sortedArray.Length / 2;
while (!indexFound)
{
if (sortedArray[subsetMiddle] == n)
{
indexFound = true;
index = subsetMiddle;
}
else if (sortedArray[subsetMiddle] > n)
{
if (devisor > sortedArray.Length)
{
subsetMiddle -= 1;
}
else
{
devisor *= 2;
subsetMiddle -= sortedArray.Length / devisor;
}
}
else
{
if (devisor > sortedArray.Length)
{
subsetMiddle += 1;
}
else
{
devisor *= 2;
subsetMiddle += sortedArray.Length / devisor;
}
}
}
Console.WriteLine("The index of the chosen element is: " + index);
}
}
<file_sep>/Java Script/JavaScript UI and DOM/Canvas/Canvas/script.js
var context = document.getElementById('theCanvas').getContext('2d');
context.beginPath();
context.fillStyle = 'rgb(156, 83, 83)';
context.strokeStyle = 'rgb(0, 0, 0)';
context.lineWidth = 3;
context.rect(500, 300, 400, 300);
context.lineTo(700, 100);
context.lineTo(900, 300);
context.fill();
context.stroke();
context.translate(500, 300);
context.fillStyle = 'rgb(0, 0, 0)';
context.fillRect(25, 30, 70, 45);
context.fillRect(25, 78, 70, 45);
context.fillRect(98, 30, 70, 45);
context.fillRect(98, 78, 70, 45);
context.translate(207, 0);
context.fillRect(25, 30, 70, 45);
context.fillRect(25, 78, 70, 45);
context.fillRect(98, 30, 70, 45);
context.fillRect(98, 78, 70, 45);
context.translate(0, 130);
context.fillRect(25, 30, 70, 45);
context.fillRect(25, 78, 70, 45);
context.fillRect(98, 30, 70, 45);
context.fillRect(98, 78, 70, 45);
context.translate(-207, -130);
//context.lineCap = "round";
context.moveTo(45, 300);
context.lineTo(45, 190);
context.bezierCurveTo(45, 175, 75, 163, 96.5, 163);
context.bezierCurveTo(118, 163, 148, 175, 148, 190);
context.lineTo(148, 300);
context.moveTo(96.5, 300);
context.lineTo(96.5, 163);
context.stroke();
context.beginPath();
context.arc(113, 258, 6, 0, 360 * Math.PI / 180);
context.stroke();
context.beginPath();
context.arc(80, 258, 6, 0, 360 * Math.PI / 180);
context.stroke();
context.beginPath();
context.fillStyle = 'rgb(156, 83, 83)';
context.moveTo(280, -40);
context.lineTo(280, -150);
context.lineTo(320, -150);
context.lineTo(320, -40);
context.fill();
context.stroke();
context.beginPath();
context.scale(1, 0.3);
context.arc(300, -500, 20, 0, 360 * Math.PI / 180);
context.fill();
context.stroke();
context.restore();
<file_sep>/C#/C# Programming Part I/ConditionalStatements/PlayWithIntDoubleAndString/VariableTypes.cs
//Write a program that, depending on the user’s choice, inputs an int, double or string variable.
//If the variable is int or double, the program increases it by one.
//If the variable is a string, the program appends * at the end.
//Print the result at the console. Use switch statement.
using System;
class VariableTypes
{
static void Main()
{
Console.WriteLine(@"Please choose a type:
1 --> int
2 --> double
3 --> string");
int type = int.Parse(Console.ReadLine());
switch (type)
{
case 1:
Console.Write("Please enter an int: ");
int intInput = int.Parse(Console.ReadLine());
Console.WriteLine(intInput++);
break;
case 2:
Console.Write("Please enter a double: ");
double doubleInput = double.Parse(Console.ReadLine());
Console.WriteLine(doubleInput + 1);
break;
case 3:
Console.WriteLine("Please enter a string: ");
string stringInput = Console.ReadLine();
Console.WriteLine(stringInput + '*');
break;
default:
Console.WriteLine("You didn't choose from the three available.");
break;
}
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart2/BankAccounts/Accounts/Deposit.cs
namespace BankAccounts.Accounts
{
public class Deposit : BankAccount
{
public void WithdrawMoney(decimal sum)
{
this.Balance -= sum;
}
public override decimal CalculateInterest(int months)
{
if (this.Balance > 0 && this.Balance < 1000)
{
return 0;
}
return base.CalculateInterest(months);
}
}
}
<file_sep>/C#/OOP/CommonTypeSystem/Student/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Student
{
class Program
{
static void Main(string[] args)
{
Student newStudent = new Student();
Type type = newStudent.GetType();
foreach (var item in type.GetProperties())
{
Console.WriteLine(item);
}
}
}
}
<file_sep>/C#/OOP/CommonTypeSystem/Student/Student.cs
namespace Student
{
using System;
using Enumarations;
public class Student : ICloneable, IComparable<Student>
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public long SSN { get; set; }
public string PermanentAddress { get; set; }
public string MobilePhone { get; set; }
public string EMail { get; set; }
public string Course { get; set; }
public Specialty Specialty { get; set; }
public University Univesity { get; set; }
public Faculty Faculty { get; set; }
public override bool Equals(object obj)
{
Student comparedStudent = obj as Student;
if (comparedStudent == null)
{
return false;
}
if (this.FirstName != comparedStudent.FirstName) return false;
if (this.MiddleName != comparedStudent.MiddleName) return false;
if (this.LastName != comparedStudent.LastName) return false;
if (this.SSN != comparedStudent.SSN) return false;
if (this.PermanentAddress != comparedStudent.PermanentAddress) return false;
if (this.EMail != comparedStudent.EMail) return false;
if (this.Course != comparedStudent.Course) return false;
if (this.Specialty != comparedStudent.Specialty) return false;
if (this.Specialty != comparedStudent.Specialty) return false;
if (this.Univesity != comparedStudent.Univesity) return false;
if (this.Faculty != comparedStudent.Faculty) return false;
return true;
}
public override string ToString()
{
return string.Format("{0} {1} from {2} University. Specialty: {3}", this.FirstName, this.LastName, this.Univesity, this.Specialty);
}
public override int GetHashCode()
{
return this.LastName.GetHashCode() ^ this.Specialty.GetHashCode() ^ this.Univesity.GetHashCode();
}
public static bool operator == (Student first, Student second)
{
return first.Equals(second);
}
public static bool operator != (Student first, Student second)
{
return !first.Equals(second);
}
public object Clone()
{
Student newStudent = new Student {
FirstName = this.FirstName, MiddleName = this.MiddleName ,
LastName = this.LastName, SSN = this.SSN, Univesity = this.Univesity,
PermanentAddress = this.PermanentAddress, EMail =this.EMail,
MobilePhone = this.MobilePhone, Course = this.Course,
Specialty = this.Specialty , Faculty = this.Faculty
};
return newStudent;
}
public int CompareTo(Student other)
{
if (this.FirstName.CompareTo(other.FirstName) < 0)
{
return -1;
}
else if (this.FirstName.CompareTo(other.FirstName) > 0)
{
return 1;
}
else
{
if (this.SSN < other.SSN)
{
return -1;
}
else if (this.SSN > other.SSN)
{
return 1;
}
else
{
return 0;
}
}
}
}
}
<file_sep>/C#/C# Programming Part II/NumeralSystems/HexadecimalToBinary/BinToHexConverter.cs
//Write a program to convert binary numbers to hexadecimal numbers (directly).
using System;
class BinToHexConverter
{
static void Main()
{
string input = Console.ReadLine();
string result = string.Empty;
for (int i = input.Length - 1; i >= 0; i -= 4)
{
string fourBits = string.Empty;
for (int j = i; j >= i - 3; j--)
{
char currentDigit = j < 0 ? '0' : input[j];
fourBits = currentDigit + fourBits;
}
switch (fourBits)
{
case "0000":
result = '0' + result;
break;
case "0001":
result = '1' + result;
break;
case "0010":
result = '2' + result;
break;
case "0011":
result = '3' + result;
break;
case "0100":
result = '4' + result;
break;
case "0101":
result = '5' + result;
break;
case "0110":
result = '6' + result;
break;
case "0111":
result = '7' + result;
break;
case "1000":
result = '8' + result;
break;
case "1001":
result = '9' + result;
break;
case "1010":
result = 'A' + result;
break;
case "1011":
result = 'B' + result;
break;
case "1100":
result = 'C' + result;
break;
case "1101":
result = 'D' + result;
break;
case "1110":
result = 'E' + result;
break;
case "1111":
result = 'F' + result;
break;
default:
break;
}
}
Console.WriteLine(result);
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Conditional statements/Conditional statements/03.The biggest of Three.js
function biggest() {
var a = document.getElementById('first-num3').value * 1,
b = document.getElementById('second-num3').value * 1,
c = document.getElementById('third-num3').value * 1,
biggest = a;
if (b > biggest) biggest = b;
if (c > biggest) biggest = c;
document.getElementById('answer3').innerHTML = biggest;
//document.getElementById('first-num3').value = '';
//document.getElementById('second-num3').value = '';
//document.getElementById('third-num3').value = '';
}<file_sep>/C#/OOP/ExtensionMethodsDelegatesLambdaLINQ/StringBuilderSubstring/SubstringExtention.cs
namespace StringBuilderSubstring
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public static class SubstringExtention
{
static StringBuilder Substring(this StringBuilder value, int startIndex, int length)
{
string result = value.ToString(startIndex, length);
return new StringBuilder(result);
}
static void Main()
{
string str = "Test of extention.";
StringBuilder sb = new StringBuilder(str);
sb = sb.Substring(1, 10);
Console.WriteLine(sb);
}
}
}
<file_sep>/C#/C# Programming Part II/Arrays/MaximalSequence/FindMaxSequence.cs
//Write a program that finds the maximal sequence of equal elements in an array.
using System;
class FindMaxSequence
{
static void Main()
{
Console.Write("Please enter a row of integers separated by space: ");
string[] inputArray = Console.ReadLine().Split();
int maxSequenceCount = 1;
int sequenceStart = 0;
for (int i = 0; i < inputArray.Length; i++)
{
int currSequenceCount = 1;
for (int j = i; j < inputArray.Length - 1; j++)
{
if (inputArray[j] == inputArray[j + 1])
{
currSequenceCount++;
}
else
{
break;
}
}
if (currSequenceCount > maxSequenceCount)
{
maxSequenceCount = currSequenceCount;
sequenceStart = i;
i += maxSequenceCount - 2; //skips the rest of the current sequence
}
}
for (int i = sequenceStart; i < sequenceStart + maxSequenceCount; i++)
{
Console.Write(inputArray[i] + " ");
}
Console.WriteLine();
}
}
<file_sep>/C#/C# Programming Part II/Methods/NFactorial/Factorials.cs
//Write a program to calculate n! for each n in the range [1..100].
using System;
using System.Numerics;
class Factorials
{
static void Main()
{
Print100Factorials();
}
private static void Print100Factorials()
{
BigInteger currentProduct = 1;
for (int i = 1; i < 101; i++)
{
Console.Write("{0}! is: ", i);
currentProduct *= i;
Console.WriteLine(currentProduct);
Console.WriteLine();
}
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart2/Shapes/TestShapes.cs
namespace Shapes
{
using System;
class TestShapes
{
static void Main()
{
Shape[] shapesArray = new Shape[]
{
new Rectangle() {Height = 1, Width = 2},
new Square(2.45),
new Triangle() {Width = 5.5, Height = 6.5}
};
foreach (Shape shape in shapesArray)
{
Console.WriteLine(shape.CalculateSurface());
}
}
}
}
<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/OddOrEvenIntegers/OddOrEven.cs
//Write an expression that checks if given integer is odd.
using System;
class OddOrEven
{
static void Main()
{
Console.Write("Enter an integer: ");
int number = int.Parse(Console.ReadLine());
bool result = number % 2 != 0;
Console.WriteLine(result);
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Strings/Strings/04.Parse tags.js
console.log('\nTask 4: You are given a text. Write a function that changes the text in all regions: \n<upcase>text</upcase> to uppercase.\n<lowcase>text</lowcase> to lowercase\n<mixcase>text</mixcase> to mix casing(random)');
var text = 'We are <mixcase>living</mixcase> in a <upcase>yellow submarine</upcase>. We <mixcase>don\'t</mixcase> have <lowcase>anything</lowcase> else.',
result = text;
function parseTags(input) {
var i,
length;
for (i = 0, length = input.length; i < length; i += 1) {
if (input[i] === '<') {
switch (input[i + 1].toLowerCase()) {
case 'u': upcase(input, i); break;
case 'l': lowcase(input, i); break;
case 'm': mixcase(input, i); break;
default:
}
}
}
}
function upcase(textinput, ind) {
var closingTagIndex = textinput.indexOf('</u', ind + 1),
toReplace = '<upcase>' + textinput.substring(ind + 8, closingTagIndex) + '</upcase>',
replacement = textinput.substring(ind + 8, closingTagIndex).toUpperCase();
result = result.replace(toReplace, replacement);
}
function lowcase(textinput, ind) {
var closingTagIndex = textinput.indexOf('</l', ind + 1),
toReplace = '<lowcase>' + textinput.substring(ind + 9, closingTagIndex) + '</lowcase>',
replacement = textinput.substring(ind + 9, closingTagIndex).toLowerCase();
result = result.replace(toReplace, replacement);
}
function mixcase(textinput, ind) {
var i,
length,
replacement,
closingTagIndex = textinput.indexOf('</m', ind + 1),
toReplace = '<mixcase>' + textinput.substring(ind + 9, closingTagIndex) + '</mixcase>',
replacementArr = textinput.substring(ind + 9, closingTagIndex).split('');
for (i = 0, length = replacementArr.length; i < length; i += 1) {
if (Math.round(Math.random())) replacementArr[i] = replacementArr[i].toUpperCase();
}
replacement = replacementArr.join('');
result = result.replace(toReplace, replacement);
}
console.log('\n' + text);
parseTags(text);
console.log('result: ');
console.log(result);
<file_sep>/C#/C# Programming Part II/StringsAndTextProcessing/EncodeDecode/Encryptor.cs
//Write a program that encodes and decodes a string using given encryption key (cipher).
//The key consists of a sequence of characters.
//The encoding/decoding is done by performing XOR (exclusive or)
//operation over the first letter of the string with the first of the key, the second – with the second, etc. When the last key character is reached, the next is the first.
using System;
using System.Text;
class Encryptor
{
static void Main()
{
Console.Write("Enter the text you want do encode: ");
StringBuilder toEncode = new StringBuilder(Console.ReadLine());
Console.Write("Enter the key: ");
StringBuilder key = new StringBuilder(Console.ReadLine());
StringBuilder encoded = new StringBuilder();
int keyIndexCounter = 0;
//Encode
for (int i = 0; i < toEncode.Length; i++)
{
encoded.Append((char)(toEncode[i] ^ key[keyIndexCounter]));
if (keyIndexCounter < key.Length - 1) keyIndexCounter++;
else keyIndexCounter = 0;
}
Console.WriteLine("The encoded message is: {0}", encoded);
//Decode
StringBuilder decoded = new StringBuilder();
keyIndexCounter = 0;
for (int i = 0; i < encoded.Length; i++)
{
decoded.Append((char)(encoded[i] ^ key[keyIndexCounter]));
if (keyIndexCounter < key.Length - 1) keyIndexCounter++;
else keyIndexCounter = 0;
}
Console.WriteLine("The decoded message is: {0}", decoded);
}
}
<file_sep>/C#/OOP/DefiningClassesPartTwo/GenericList/ProgramStart.cs
namespace GenericList
{
using System;
class ProgramStart
{
static void Main()
{
}
}
}<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/Trapezoids/TrapezoidArea.cs
//Write an expression that calculates trapezoid's area by given sides a and b and height h.
using System;
class TrapezoidArea
{
static void Main()
{
Console.WriteLine("Enter sides and height of the trapezoid.");
Console.Write("Side a: ");
double a = double.Parse(Console.ReadLine());
Console.Write("Side b: ");
double b = double.Parse(Console.ReadLine());
Console.Write("Height: ");
double h = double.Parse(Console.ReadLine());
Console.WriteLine("The area is " + (a + b) / 2 * h);
}
}
<file_sep>/C#/C# Programming Part I/Loops/BinaryToDecimalNumber/BinaryToDecimal.cs
//Using loops write a program that converts a binary integer number to its decimal form.
//The input is entered as string. The output should be a variable of type long.
//Do not use the built-in .NET functionality.
using System;
class BinaryToDecimal
{
static void Main()
{
string input = Console.ReadLine();
double sum = new int();
int position = input.Length - 1;
for (int i = 0; i < input.Length; i++)
{
if (input[position] == '1')
{
sum += Math.Pow(2, i);
}
position--;
}
Console.WriteLine(sum);
}
}
<file_sep>/Latest Exams/ExamDSA/OfficeSpace/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OfficeSpace
{
class Program
{
static List<Task> tasks;
static int numberOfTasks;
static int[] times;
static bool hasCycle;
static void MockInput()
{
var input = @"3
4 8 16
3
1
2";
Console.SetIn(new StringReader(input));
}
static void Main()
{
//MockInput();
hasCycle = false;
numberOfTasks = int.Parse(Console.ReadLine());
times = Console.ReadLine().Split().Select(t => int.Parse(t)).ToArray();
tasks = new List<Task>();
for (int i = 0; i < numberOfTasks; i++)
{
var newTask = new Task(i);
tasks.Add(newTask);
}
for (int i = 0; i < numberOfTasks; i++)
{
var dependencyIds = Console.ReadLine().Split().Select(t => int.Parse(t) - 1).ToArray();
if (dependencyIds[0] > -1)
{
foreach (var depId in dependencyIds)
{
tasks[i].Dependencies.Add(tasks[depId]);
}
}
else
{
tasks[i].Time = times[i];
}
}
//var SortedNodes = new List<Node>();
//var nodeWithoutOutgoingEdges = tasks.FirstOrDefault(n => n.Visited == false && (n.Dependencies.Count == 0 || n.Dependencies.All(node => node.Visited)));
//while (nodeWithoutOutgoingEdges != null)
//{
// nodeWithoutOutgoingEdges.Visited = true;
// SortedNodes.Add(nodeWithoutOutgoingEdges);
// nodeWithoutOutgoingEdges = tasks.FirstOrDefault(n => n.Visited == false && (n.Dependencies.Count == 0 || n.Dependencies.All(node => node.Visited)));
//}
foreach (var task in tasks)
{
CalculateTime(task.Id, task.Id);
}
if (!hasCycle)
{
Console.WriteLine(tasks.Max(t => t.Time));
}
else
{
Console.WriteLine(-1);
}
}
public static void CalculateTime(int taskId, int cycleCheckId)
{
if (tasks[taskId].Time != 0)
{
return;
}
tasks[taskId].Time += times[taskId];
foreach (var task in tasks[taskId].Dependencies)
{
if (task.Dependencies.Any(d => d.Id == cycleCheckId))
{
hasCycle = true;
}
CalculateTime(task.Id, cycleCheckId);
}
var maxTime = tasks[taskId].Dependencies.Max(d => d.Time);
tasks[taskId].Time += maxTime;
}
}
public class Task
{
public Task(int id)
{
this.Id = id;
this.Dependencies = new List<Task>();
this.Time = 0;
}
public int Id { get; private set; }
public int Time { get; set; }
public bool Visited { get; set; }
public List<Task> Dependencies { get; set; }
}
}
<file_sep>/C#/OOP/DefiningClassesPartOne/DefineClass/GSM.cs
namespace GSMInfo
{
using System;
using System.Collections.Generic;
public class GSM
{
private string model;
private string manufacturer;
private double price;
private string owner;
private Battery batteryInfo;
private Display displayInfo;
private List<Call> calls = new List<Call>();
private static GSM iPhone4S = new GSM("IPhone4S", "Apple");
public GSM(string model, string manufacturer)
{
this.Model = model;
this.Manufacturer = manufacturer;
this.price = 0;
this.owner = null;
this.batteryInfo = new Battery();
this.displayInfo = new Display();
}
public GSM(string model, string manufacturer, double price)
: this(model, manufacturer)
{
this.Price = price;
}
public GSM(string model, string manufacturer, double price, string owner)
: this(model, manufacturer, price)
{
this.Owner = owner;
}
public GSM(string model, string manufacturer, string owner)
: this(model, manufacturer)
{
this.Owner = owner;
}
public void AddCall(DateTime date, long dialedNumber, long duration)
{
Call currentCall = new Call(date, dialedNumber, duration);
this.CallHistory.Add(currentCall);
}
public void DeleteCall(int callIndex)
{
if (this.CallHistory.Count > 0)
{
calls.RemoveAt(callIndex);
}
else
{
throw new IndexOutOfRangeException("There are no calls in this call history");
}
}
public void ClearCallHistory()
{
if (this.CallHistory.Count > 0)
{
calls.RemoveRange(0, calls.Count);
}
else
{
throw new IndexOutOfRangeException("There are no calls in this call history");
}
}
public double TotalCallsPrice(double pricePerMin)
{
double totalCost = 0;
foreach (Call call in calls)
{
double currentCallCost = call.Duration * (pricePerMin / 60);
totalCost += currentCallCost;
}
return totalCost;
}
public string Model
{
get { return this.model; }
set
{
if (value.Length < 2 || string.IsNullOrEmpty(value))
{
throw new ArgumentException("Manufacturer's name should be longer!");
}
this.model = value;
}
}
public string Manufacturer
{
get { return this.manufacturer; }
set
{
if (value.Length < 2 || string.IsNullOrEmpty(value))
{
throw new ArgumentException("Manufacturer's name should be longer!");
}
this.manufacturer = value;
}
}
public double Price
{
get { return this.price; }
set
{
if (value < 0)
{
throw new ArgumentException("Price should be zero or more!");
}
this.price = value;
}
}
public string Owner
{
get { return this.owner; }
set
{
if (value.Length < 2 || string.IsNullOrEmpty(value))
{
throw new ArgumentException("Owner's name should be longer!");
}
this.owner = value;
}
}
public Battery BatteryInfo
{
get { return this.batteryInfo; }
set { this.batteryInfo = value; }
}
public Display DisplayInfo
{
get { return displayInfo; }
set { displayInfo = value; }
}
public static GSM IPhone4S
{
get { return iPhone4S; }
set { iPhone4S = value; }
}
public List<Call> CallHistory
{
get { return calls; }
}
public override string ToString()
{
return string.Format("The phone is {0} {1}. It's owner is {2} and the price is {3}. The display is {4} inches big and has {5} colors. The battery is {6} with {7} mAh of capacity and {8} hours of idle time and {9} hours of talk time.",
this.Manufacturer, this.Model, this.Owner, this.Price, this.DisplayInfo.Size, this.DisplayInfo.Colors, this.BatteryInfo.TypeOfBattery, this.BatteryInfo.MAhCapacity, this.BatteryInfo.HoursIdle, this.BatteryInfo.HoursTalk);
}
static void Main()
{
}
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart2/BankAccounts/Accounts/Loan.cs
namespace BankAccounts.Accounts
{
using BankAccounts.Customers;
class Loan : BankAccount
{
public override decimal CalculateInterest(int months)
{
if (this.Client is Individual)
{
if (months <= 3)
{
return 0;
}
else
{
months -= 3;
}
}
else
{
if (months <= 2)
{
return 0;
}
else
{
months -= 3;
}
}
return base.CalculateInterest(months);
}
}
}
<file_sep>/C#/OOP/DefiningClassesPartTwo/Structure/Distance.cs
namespace Structure
{
using System;
public static class Distance
{
public static double Calculate(Point3D fisrt, Point3D second)
{
return Math.Sqrt(Math.Pow(fisrt.X - second.X, 2) + Math.Pow(fisrt.Y - second.Y, 2) + Math.Pow(fisrt.Z - second.Z, 2));
}
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Conditional statements/Conditional statements/02.MultiplicationSign.js
function sign() {
var a = document.getElementById('first-num2').value * 1,
b = document.getElementById('second-num2').value * 1,
c = document.getElementById('third-num2').value * 1,
tempSign;
if ((a < 0 && b < 0) || (a > 0 && b > 0)) tempSign = 1;
else if (a == 0 || b == 0) tempSign = 0;
else tempSign = -1;
if ((tempSign < 0 && c < 0) || (tempSign > 0 && c > 0)) document.getElementById('answer2').innerHTML = '+';
else if (tempSign == 0 || c == 0) document.getElementById('answer2').innerHTML = '0';
else document.getElementById('answer2').innerHTML = '-';
//document.getElementById('first-num2').value = '';
//document.getElementById('second-num2').value = '';
//document.getElementById('third-num2').value = '';
}<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/BitsExchange/SwitchBits.cs
//Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer.
using System;
class SwitchBits
{
static void Main()
{
Console.Write("Enter number: ");
long number = long.Parse(Console.ReadLine());
int a;
int b;
for (a = 3, b = 24; a <= 5; a++, b++)
{
long getBitA = (number >> a) & 1; //Gets the value of the bit at the current position
long getBitB = (number >> b) & 1;
if ((getBitA == 1) && (getBitB == 1))
{
number = number | (1 << b); //Switches the original bits with 1s and 0s depending on the case
number = number | (1 << a); //In this case both are ones
}
else if ((getBitA == 1) && (getBitB == 0))
{
number = number | (1 << b);
number = number & ~(1 << a);
}
else if ((getBitA == 0) && (getBitB == 1))
{
number = number & ~(1 << b);
number = number | (1 << a);
}
else
{
number = number & ~(1 << b);
number = number & ~(1 << a);
}
}
Console.WriteLine(number);
}
}
<file_sep>/Java Script/JavaScript OOP/Functions and Function Expressions/Functions and Function Expressions/task-1.js
(function () {
function sumArr(arr) {
var i,
currentElement,
length,
sum = 0;
if (arguments.length === 0) throw 'No Arguments Error';
if (arr.length === 0) return null;
length = arr.length;
for (i = 0; i < length; i += 1) {
currentElement = +arr[i];
if (isNaN(currentElement)) throw 'Element NaN Error';
sum += currentElement;
}
return sum;
}
console.log(sumArr([1, 2, '2']));
}());
<file_sep>/C#/OOP/CommonTypeSystem/Student/Enumarations/Specialty.cs
namespace Student.Enumarations
{
public enum Specialty
{
Economics,
CorporateFinance,
PortfolioManagement,
Statistics
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart1/SchoolClasses/SchoolClass.cs
namespace SchoolClasses
{
using System;
using System.Collections.Generic;
public class SchoolClass
{
private List<Student> students;
private List<Teacher> teachers;
public SchoolClass(string name)
{
this.ClassIdentifier = name;
this.students = new List<Student>();
this.teachers = new List<Teacher>();
}
public string ClassIdentifier { get; set; }
public string Comment { get; set; }
public List<Student> Students
{
get
{
return this.students;
}
set
{
this.students = value;
}
}
public List<Teacher> Teachers
{
get
{
return this.teachers;
}
set
{
this.teachers = value;
}
}
}
}
<file_sep>/C#/C# Programming Part I/Loops/DecimalToBinaryNumber/DecimalToBinary.cs
//Using loops write a program that converts an integer number to its binary representation.
//The input is entered as long. The output should be a variable of type string.
//Do not use the built-in .NET functionality.
using System;
class DecimalToBinary
{
static void Main()
{
int someInt = int.Parse(Console.ReadLine());
string result = string.Empty;
do
{
if (someInt % 2 != 0)
{
result = 1 + result;
}
else if (someInt % 2 == 0)
{
result = 0 + result;
}
someInt /= 2;
} while (someInt != 0);
Console.WriteLine(result);
}
}
<file_sep>/C#/C# Programming Part I/ConsoleInputOutput/NumbersINIntervalDividableByGivenNumber/FindNumbersInINterval.cs
//Write a program that reads two positive integer numbers and prints how many numbers p exist between them such that the reminder of the division by 5 is 0.
using System;
class FindNumbersInINterval
{
static void Main()
{
Console.Write("Enter Start number: ");
int start = int.Parse(Console.ReadLine());
Console.Write("Enter End number: ");
int end = int.Parse(Console.ReadLine());
int count = 0;
for (int i = start; i <= end; i++)
{
if (i % 5 == 0)
{
count++;
}
}
Console.WriteLine(count);
}
}
<file_sep>/C#/C# Programming Part I/PrimitiveDataTypesAndVariables/StringsAndObjects/CoupleOFStrings.cs
//Declare two string variables and assign them with Hello and World.
//Declare an object variable and assign it with the concatenation of the first two variables (mind adding an interval between).
//Declare a third string variable and initialize it with the value of the object variable (you should perform type casting).
using System;
class CoupleOFStrings
{
static void Main()
{
string someString = "Hello";
string someOtherString = "World";
object someObject = someString + " " + someOtherString;
string anotherString = (string)someObject;
}
}
<file_sep>/C#/C# Programming Part I/Loops/RandomizeNumbers1ToN/NumbersRandomizer.cs
//Write a program that enters in integer n and prints the numbers 1, 2, …, n in random order.
using System;
class NumbersRandomizer
{
static void Main()
{
Console.Write("Enter n: ");
int n = int.Parse(Console.ReadLine());
int[] numbers = new int[n];
bool[] checkPosition = new bool[n + 1];
Random rndm = new Random();
int random = new int();
for (int i = 0; i < n; i++)
{
random = rndm.Next(1, n + 1);
if (checkPosition[random] == false)
{
numbers[i] = random;
checkPosition[random] = true;
}
else
{
i--;
}
}
foreach (int i in numbers)
{
Console.Write(i);
}
Console.WriteLine();
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart2/RangeExceptions/Test.cs
namespace RangeExceptions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Test
{
static void Main()
{
Console.Write("Enter a number in the range 1..100: ");
int input = int.Parse(Console.ReadLine());
if (input < 1 ||
input > 100)
{
throw new InvalidRangeException<int>("Invalid input!", 1, 100);
}
Console.WriteLine("Enter a date in the range 1.1.1980 ... 12.31.2013 (Format: MM/DD/YYYY): ");
DateTime inputDate = DateTime.Parse(Console.ReadLine());
if (inputDate < new DateTime(1981, 1, 1) ||
inputDate > new DateTime(2013, 12, 31))
{
throw new InvalidRangeException<DateTime>("Invalid input!", new DateTime(1981, 1, 1), new DateTime(2013, 12, 31));
}
Console.WriteLine("Input was correct.");
}
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Using Objects/Using Objects/05.Youngest person.js
console.log('\nTask 5: Write a function that finds the youngest person in a given array of people and prints his/hers full name. Each person has properties firstname, lastname and age.');
function findYoungest(personsArr) {
var person,
result = personsArr[0],
minAge = +Infinity;
for (person in personsArr) {
if (personsArr[person].age < minAge) {
minAge = personsArr[person].age;
result = personsArr[person];
}
}
return result.firstname + ' ' + result.lastname;
}
var people = [
{ firstname : 'Gosho', lastname: 'Petrov', age: 82 },
{ firstname: 'Bay', lastname: 'Ivan', age: 91 },
{ firstname: 'Pesho', lastname: 'Peshev', age: 50 }
];
console.log('var people = [{ firstname : \'Gosho\', lastname: \'Petrov\', age: 82 },\n{ firstname: \'Bay\', lastname: \'Ivan\', age: 91 },\n{ firstname: \'Pesho\', lastname: \'Peshev\', age: 50 }];')
console.log('Youngest: ' + findYoungest(people));<file_sep>/C#/C# Programming Part II/Methods/FirstLargerThanNeighbours/FindLarger.cs
//Write a method that returns the index of the first element in array that is larger than its neighbours, or -1, if there’s no such element.
//Use the method from the previous exercise.
using System;
class FindLarger
{
static void Main()
{
int[] intArray = new int[] { 1, 2, 5, 6, 4, 8, 2, 4, 2, 6, 2, 4 };
Console.WriteLine(CheckNeighbours(intArray));
}
static int CheckNeighbours(int[] inputArray)
{
int index = -1;
for (int i = 1; i < inputArray.Length - 1; i++)
{
if (inputArray[i] > inputArray[i - 1] && inputArray[i] > inputArray[i + 1])
{
index = i;
break;
}
}
return index;
}
}
<file_sep>/C#/OOP/CommonTypeSystem/Person/Person.cs
namespace Person
{
public class Person
{
public Person(string name)
{
this.Name = name;
}
public double? Age { get; set; }
public string Name { get; set; }
public override string ToString()
{
return string.Format("Name: {0}\nAge: {1}", this.Name, (object)this.Age ?? "N/A, no age entered");
}
}
}
<file_sep>/C#/C# Programming Part II/Arrays/SelectionSort/SortArray.cs
//Sorting an array means to arrange its elements in increasing order. Write a program to sort an array.
//Use the Selection sort algorithm: Find the smallest element, move it at the first position, find the
//smallest from the rest, move it at the second position, etc.
using System;
class SortArray
{
static void Main()
{
Console.Write("Please enter a row of integers separated by space: ");
string[] inputArray = Console.ReadLine().Split();
int[] intArray = new int[inputArray.Length];
for (int i = 0; i < inputArray.Length; i++)
{
intArray[i] = int.Parse(inputArray[i]);
}
int smallest = 0;
for (int i = 0; i < intArray.Length; i++)
{
smallest = intArray[i];
int position = 0;
for (int j = i + 1; j < intArray.Length; j++)
{
if (intArray[j] < smallest)
{
smallest = intArray[j];
position = j;
}
}
if (position == 0)
{
continue;
}
intArray[position] = intArray[i];
intArray[i] = smallest;
}
foreach (var item in intArray)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
}
<file_sep>/C#/C# Programming Part II/Arrays/MaximalKSum/FindMaxKSum.cs
//Write a program that reads two integer numbers N and K and an array of N elements from the console.
//Find in the array those K elements that have maximal sum.
using System;
class FindMaxKSum
{
static void Main()
{
Console.Write("Enter N, the number of elements in the array: ");
int n = int.Parse(Console.ReadLine());
Console.Write("Enter K, the number of elements with max sum: ");
int k = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter N integers: ");
int[] intArray = new int[n];
for (int i = 0; i < intArray.Length; i++)
{
Console.Write("Element {0}: ", i);
intArray[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine();
Array.Sort(intArray);
int sum = 0;
Console.Write("Elements with maximum sum: ");
for (int i = intArray.Length - 1; i > intArray.Length - 1 - k; i--)
{
sum += intArray[i];
Console.Write(intArray[i] + " ");
}
Console.WriteLine();
Console.WriteLine("Max sum is {0}", sum);
}
}
<file_sep>/C#/C# Programming Part II/Methods/IntegerCalculations/Calculator.cs
//Write methods to calculate minimum, maximum, average, sum and product of given set of integer numbers.
//Use variable number of arguments.
using System;
class Calculator
{
static void Main()
{
Console.WriteLine("Min: {0}", Min(4, 2, 1, 3));
Console.WriteLine("Max: {0}", Max(4, 2, 1, 3));
Console.WriteLine("Average: {0}", Average(4, 2, 1, 3));
Console.WriteLine("Sum: {0}", Sum(4, 2, 1, 3));
Console.WriteLine("Product: {0}", Product(4, 2, 1, 3));
}
static int Product(params int[] sequence)
{
int product = 1;
for (int i = 0; i < sequence.Length; i++)
{
product *= sequence[i];
}
return product;
}
static int Sum(params int[] sequence)
{
int sum = 0;
for (int i = 0; i < sequence.Length; i++)
{
sum += sequence[i];
}
return sum;
}
static double Average(params int[] sequence)
{
double sum = 0;
for (int i = 0; i < sequence.Length; i++)
{
sum += sequence[i];
}
return sum / sequence.Length;
}
static int Max(params int[] sequence)
{
int max = int.MinValue;
for (int i = 0; i < sequence.Length; i++)
{
if (sequence[i] > max)
{
max = sequence[i];
}
}
return max;
}
static int Min(params int[] sequence)
{
int min = int.MaxValue;
for (int i = 0; i < sequence.Length; i++)
{
if (sequence[i] < min)
{
min = sequence[i];
}
}
return min;
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Functions/Functions/04.Number of elements.js
function countDivs() {
var divs = document.getElementsByTagName('div'),
count = divs.length;
document.getElementById('result4').innerHTML = 'The div count is: ' + count;
}<file_sep>/Java Script/JavaScript Fundmentals/Functions/Functions/05.Appearance count.js
function countAppearances() {
var i,
count = 0,
inputArray = document.getElementById('numbersArray').value.split(' '),
number = document.getElementById('num5').value,
len = inputArray.length;
for (i = 0; i < len; i += 1) {
if (inputArray[i] == number) count += 1;
}
document.getElementById('result5').innerHTML = count;
return count;
}
function testFunc() {
var result;
document.getElementById('numbersArray').value = '1 5 6 7 5 6 8 1 7 9 7';
document.getElementById('num5').value = '1';
result = countAppearances();
if (result == 2) document.getElementById('result5').innerHTML = result + ' - It works!';
}<file_sep>/Java Script/JavaScript Fundmentals/Array Methods/Array Methods/02.People of age.js
console.log('\nTask 2: Write a function that checks if an array of person contains only people of age (with age 18 or greater) Use only array methods and no regular loops (for, while)');
var arr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
fnames = ['Joy', 'Nicky', 'Aleks', 'Grui', 'Jay', 'Zoy', 'Nelli', 'Pol', 'Gol', 'Sol'],
lnames = ['Peterson', 'Johnson', 'Bolton', 'Clapton', 'Pikachu', 'Winfrey', 'Spencer', 'Cloppenburg', 'Heisenburg', 'West'];
var people = arr.map(function (_, i) {
return { fname: fnames[i], lname: lnames[i], age: Math.random() * 100 | 0, gender: !(Math.round(Math.random())) };
});
var result = people.every(function (person) {
return person.age >= 18;
});
console.log(people);
console.log(result);<file_sep>/C#/OOP/OOPPrinciplesPart1/SchoolClasses/School.cs
namespace SchoolClasses
{
using System;
using System.Collections.Generic;
public class School
{
private List<People> allPeopleInSchool;
private List<SchoolClass> classes;
public School(string name)
{
this.Name = name;
this.classes = new List<SchoolClass>();
this.allPeopleInSchool = new List<People>();
}
public List<People> AllPeopleInSchool
{
get
{
foreach (var schoolClass in this.Classes)
{
foreach (var teacher in schoolClass.Teachers)
{
allPeopleInSchool.Add(teacher);
}
foreach (var student in schoolClass.Students)
{
allPeopleInSchool.Add(student);
}
}
return this.allPeopleInSchool;
}
}
public List<SchoolClass> Classes
{
get
{
return this.classes;
}
set
{
this.classes = value;
}
}
public string Name { get; set; }
}
}
<file_sep>/C#/OOP/ExtensionMethodsDelegatesLambdaLINQ/IEnumerable extensions/IEnumerableMathExtentions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IEnumerableExtensions
{
public class IEnumerableMathExtentions
{
public static T Sum<T>(this IEnumerable<T> collection)
{
dynamic sum = 0;
foreach (var item in collection)
{
sum += item;
}
return sum;
}
public static T Product<T>(this IEnumerable<T> collection)
{
dynamic product = 1;
foreach (var item in collection)
{
product *= item;
}
return product;
}
public static T Min<T>(this IEnumerable<T> collection)
where T : IComparable<T>
{
T result = collection.First();
foreach (var item in collection)
{
if (item.CompareTo(result) < 0)
{
result = item;
}
}
return result;
}
public static T Max<T>(this IEnumerable<T> collection)
where T : IComparable<T>
{
T result = collection.First();
foreach (var item in collection)
{
if (item.CompareTo(result) > 0)
{
result = item;
}
}
return result;
}
public static T Average<T>(this IEnumerable<T> collection)
{
dynamic product = 1;
foreach (var item in collection)
{
product *= item;
}
return product / collection.Count();
}
static void Main()
{
}
}
}
<file_sep>/C#/C# Programming Part II/Arrays/CompareCharArrays/CharArrayComparer.cs
//Write a program that compares two char arrays lexicographically (letter by letter).
using System;
class CharArrayComparer
{
static void Main()
{
Console.Write("Please enter first row of letters separated by space: ");
string[] firstArray = Console.ReadLine().Split();
Console.Write("Please enter second row of letters separated by space: ");
string[] secondArray = Console.ReadLine().Split();
Console.WriteLine("First Array: | Second Array:");
for (int i = 0; i < Math.Max(firstArray.Length, secondArray.Length); i++)
{
if (firstArray.Length - 1 < i) //If one array is longer tha the other returns no letter
{
Console.WriteLine(" No Letter |{0,8}", secondArray[i]);
}
else if (secondArray.Length - 1 < i)
{
Console.WriteLine("{0,6} | No Letter", firstArray[i]);
}
else
{
Console.Write("{0,6} |{1,8} - ", firstArray[i], secondArray[i]);
if (firstArray[i] == secondArray[i] //Also checks if capital letter is compared to the same letter in lower case
|| Convert.ToChar(firstArray[i]) == Convert.ToChar(secondArray[i]) - 32
|| Convert.ToChar(firstArray[i]) == Convert.ToChar(secondArray[i]) + 32)
{
Console.WriteLine("equal");
}
else
{
Console.WriteLine("different");
}
}
}
}
}
<file_sep>/C#/C# Programming Part II/NumeralSystems/DecimalToBinary/DecToBinConverter.cs
//Write a program to convert decimal numbers to their binary representation.
using System;
class DecToBinConverter
{
static void Main()
{
long input = long.Parse(Console.ReadLine());
string result = string.Empty;
do
{
if (input % 2 != 0)
{
result = 1 + result;
}
else if (input % 2 == 0)
{
result = 0 + result;
}
input /= 2;
} while (input != 0);
Console.WriteLine(result);
}
}
<file_sep>/C#/C# Programming Part II/Methods/AppearanceCount/ElementsCounter.cs
//Write a method that counts how many times given number appears in given array.
//Write a test program to check if the method is workings correctly.
using System;
class ElementsCounter
{
static void Main()
{
Console.Write("Enter a row of numbers separated by space: ");
string[] arrayInput = Console.ReadLine().Split();
Console.Write("Enter the number you want to count: ");
string numberInput = Console.ReadLine();
Counter(arrayInput, numberInput);
}
static void Counter(string[] inputArray, string inputNum)
{
int count = 0;
for (int i = 0; i < inputArray.Length; i++)
{
if (inputArray[i] == inputNum) count++;
}
if (count == 0) Console.WriteLine("This number is not in the array.");
else Console.WriteLine("The number appears {0} times.", count);
}
}
<file_sep>/C#/C# Programming Part I/PrimitiveDataTypesAndVariables/IsoscelesTriangle/Triangle.cs
//Write a program that prints an isosceles triangle of 9 copyright symbols ©
using System;
using System.Text;
class Triangle
{
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine(@" ©
© ©
© ©
© © © ©");
}
}
<file_sep>/C#/C# Programming Part II/NumeralSystems/HexadecimalToDecimal/HexToDecConverter.cs
//Write a program to convert hexadecimal numbers to their decimal representation.
using System;
class HexToDecConverter
{
static void Main()
{
string input = Console.ReadLine();
long result = new long();
int currentDigit = new int();
int powersOf16 = 1;
for (int i = input.Length - 1; i >= 0; i--)
{
switch (input[i])
{
case 'A':
currentDigit = 10;
break;
case 'B':
currentDigit = 11;
break;
case 'C':
currentDigit = 12;
break;
case 'D':
currentDigit = 13;
break;
case 'E':
currentDigit = 14;
break;
case 'F':
currentDigit = 15;
break;
default:
currentDigit = input[i] - '0';
break;
}
result += currentDigit * powersOf16;
powersOf16 *= 16;
}
Console.WriteLine(result);
}
}
<file_sep>/C#/OOP/DefiningClassesPartOne/DefineClass/Battery.cs
namespace GSMInfo
{
using System;
public enum BatteryType
{
LiIon, NiMH, NiCd
}
public class Battery
{
private float hoursIdle;
private float hoursTalk;
private int mAhCapacity;
private BatteryType typeOfBattery;
public Battery()
{
this.hoursIdle = 5;
this.hoursTalk = 2;
this.mAhCapacity = 100;
}
public Battery(float hoursIdle)
: this()
{
this.HoursIdle = hoursIdle;
}
public Battery(float hoursTalk, float hoursIdle)
: this(hoursIdle)
{
this.HoursTalk = hoursTalk;
}
public Battery(float hoursTalk, float hoursIdle, int mAhCapacity)
: this(hoursTalk, hoursIdle)
{
this.MAhCapacity = mAhCapacity;
}
public float HoursIdle
{
get { return this.hoursIdle; }
set
{
if (value <= 0)
{
throw new ArgumentException("Idle time should be positive!");
}
this.hoursIdle = value;
}
}
public float HoursTalk
{
get { return this.hoursTalk; }
set
{
if (value <= 0)
{
throw new ArgumentException("Talk time should be positive!");
}
this.hoursTalk = value;
}
}
public int MAhCapacity
{
get { return this.mAhCapacity; }
set
{
if (value <= 0)
{
throw new ArgumentException("Talk time should be positive!");
}
this.mAhCapacity = value;
}
}
public BatteryType TypeOfBattery
{
get { return this.typeOfBattery; }
set { this.typeOfBattery = value; }
}
}
}
<file_sep>/C#/C# Programming Part I/Loops/HexadecimalToDecimalNumber/HexToDec.cs
//Using loops write a program that converts a hexadecimal integer number to its decimal form.
//The input is entered as string. The output should be a variable of type long.
//Do not use the built-in .NET functionality.
using System;
class HexToDec
{
static void Main()
{
string input = Console.ReadLine();
int[] intArray = new int[input.Length];
long decimalNumber = 0;
for (int i = 0; i < input.Length; i++)
{
char inputChar = input[i];
switch (inputChar)
{
case 'A':
intArray[i] = 10;
break;
case 'B':
intArray[i] = 11;
break;
case 'C':
intArray[i] = 12;
break;
case 'D':
intArray[i] = 13;
break;
case 'E':
intArray[i] = 14;
break;
case 'F':
intArray[i] = 15;
break;
default:
intArray[i] = int.Parse(input[i].ToString());
break;
}
}
for (int i = 0; i < input.Length; i++)
{
int power = input.Length - 1 - i;
decimalNumber += (long)(intArray[i] * Math.Pow(16, power));
}
Console.WriteLine(decimalNumber);
}
}
<file_sep>/C#/C# Programming Part II/Methods/GetLargestNumber/FindMax.cs
//Write a method GetMax() with two parameters that returns the larger of two integers.
//Write a program that reads 3 integers from the console and prints the largest of them using the method GetMax().
using System;
class FindMax
{
static void Main(string[] args)
{
Console.Write("Enter int 1: ");
int a = int.Parse(Console.ReadLine());
Console.Write("Enter int 2: ");
int b = int.Parse(Console.ReadLine());
Console.Write("Enter int 3: ");
int c = int.Parse(Console.ReadLine());
int greaterAB = GetMax(a, b);
int biggest = GetMax(c, greaterAB);
Console.WriteLine(biggest);
}
static int GetMax(int first, int second)
{
if (first > second) return first;
else return second;
}
}
<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/Rectangles/RectangleParameters.cs
//Write an expression that calculates rectangle’s perimeter and area by given width and height.
using System;
class RectangleParameters
{
static void Main()
{
Console.Write("Please enter the rectangle's widht: ");
double width = double.Parse(Console.ReadLine());
Console.Write("Please enter the rectangle's height: ");
double height = double.Parse(Console.ReadLine());
double perimeter = width * 2 + height * 2;
double area = width * height;
Console.WriteLine("The perimeter ie {0} and the area is {1}.", perimeter, area);
}
}
<file_sep>/C#/C# Programming Part II/NumeralSystems/DecimalToHexadecimal/DecToHexConverter.cs
//Write a program to convert decimal numbers to their hexadecimal representation.
using System;
class DecToHexConverter
{
static void Main()
{
long input = long.Parse(Console.ReadLine());
string result = string.Empty;
while (input != 0)
{
long reminder = input % 16;
switch (reminder)
{
case 10:
result = 'A' + result;
break;
case 11:
result = 'B' + result;
break;
case 12:
result = 'C' + result;
break;
case 13:
result = 'D' + result;
break;
case 14:
result = 'E' + result;
break;
case 15:
result = 'F' + result;
break;
default:
result = reminder.ToString() + result;
break;
}
input /= 16;
}
Console.WriteLine(result);
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart1/SchoolClasses/Discipline.cs
namespace SchoolClasses
{
using System;
public class Discipline
{
public Discipline()
{
}
public Discipline(string name)
{
this.Name = name;
}
public string Name { get; set; }
public int NumberOfLectures { get; set; }
public int NumberOfExercises { get; set; }
public string Comment { get; set; }
}
}<file_sep>/C#/C# Programming Part II/MultidimensionalArrays/BinarySearch/FindKOrSmaller.cs
//Write a program, that reads from the console an array of N integers and an integer K, sorts the array
//and using the method Array.BinSearch() finds the largest number in the array which is ≤ K.
using System;
class FindKOrSmaller
{
static void Main()
{
Console.Write("Please enter N: ");
int n = int.Parse(Console.ReadLine());
Console.Write("Please enter K: ");
int k = int.Parse(Console.ReadLine());
int indexInArray = 0;
bool found = false;
int[] inputArray = new int[n];
for (int i = 0; i < inputArray.Length; i++)
{
Console.Write("Enter element {0}: ", i);
inputArray[i] = int.Parse(Console.ReadLine());
}
Array.Sort(inputArray);
while (!found)
{
indexInArray = Array.BinarySearch(inputArray, k);
if (indexInArray < 0)
{
k--;
}
else
{
found = true;
}
}
Console.WriteLine("Largest number <= K: {0}", inputArray[indexInArray]);
}
}
<file_sep>/Latest Exams/ExamDSA/ConsoleApplication1/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void MockInput()
{
var input = @"word
worldfullwithwordsandwords";
Console.SetIn(new StringReader(input));
}
static void Main()
{
MockInput();
var word = Console.ReadLine();
var text = Console.ReadLine();
var prefixesValues = new HashSet<ulong>();
var suffixesValues = new HashSet<ulong>();
var prefixesHitCounts = new Dictionary<int, ulong>();
var suffixesHitCounts = new Dictionary<int, ulong>();
ulong combinations = 0;
var wordHash = new Hash(word);
for (int i = 1; i < word.Length; i++)
{
var prefix = word.Substring(0, i);
var suffix = word.Substring(i, word.Length - i);
var prefixHash = new Hash(prefix);
var suffixHash = new Hash(suffix);
prefixesValues.Add(prefixHash.Value1);
prefixesValues.Add(prefixHash.Value2);
suffixesValues.Add(suffixHash.Value1);
suffixesValues.Add(suffixHash.Value2);
}
Hash.ComputePowers(word.Length);
for (int length = 1; length <= word.Length; length++)
{
var textHash = new Hash(text.Substring(0, length));
for (int j = 0; j < text.Length - length; j++)
{
if (length == word.Length)
{
if (textHash.Value1 == wordHash.Value1 &&
textHash.Value2 == wordHash.Value2)
{
combinations++;
//Console.WriteLine(text.Substring(j, i));
}
textHash.Add(text[j + length]);
textHash.Remove(text[j], length);
continue;
}
if (prefixesValues.Contains(textHash.Value1) && prefixesValues.Contains(textHash.Value2))
{
//Console.WriteLine(text.Substring(j, i));
if (!prefixesHitCounts.ContainsKey(length))
{
prefixesHitCounts[length] = 0;
}
prefixesHitCounts[length]++;
}
if (suffixesValues.Contains(textHash.Value1) && suffixesValues.Contains(textHash.Value2))
{
//Console.WriteLine(text.Substring(j, i));
if (!suffixesHitCounts.ContainsKey(length))
{
suffixesHitCounts[length] = 0;
}
suffixesHitCounts[length]++;
}
textHash.Add(text[j + length]);
textHash.Remove(text[j], length);
}
}
foreach (var count in prefixesHitCounts)
{
combinations += count.Value * suffixesHitCounts[word.Length - count.Key];
//Console.WriteLine(combinations);
}
//Console.ReadLine();
Console.WriteLine(combinations);
}
}
class Hash
{
private const ulong BASE1 = 257;
private const ulong MOD = 1000000033;
private const ulong BASE2 = 307;
private static ulong[] powers1;
private static ulong[] powers2;
public static void ComputePowers(int n)
{
powers1 = new ulong[n + 1];
powers2 = new ulong[n + 1];
powers1[0] = 1;
powers2[0] = 1;
for (int i = 0; i < n; i++)
{
powers1[i + 1] = powers1[i] * BASE1 % MOD;
powers2[i + 1] = powers2[i] * BASE2 % MOD;
}
}
public ulong Value1 { get; private set; }
public ulong Value2 { get; private set; }
public Hash(string str)
{
this.Value1 = 0;
this.Value2 = 0;
foreach (char c in str)
{
this.Add(c);
}
}
public void Add(char c)
{
this.Value1 = (this.Value1 * BASE1 + c) % MOD;
this.Value2 = (this.Value2 * BASE2 + c) % MOD;
}
public void Remove(char c, int n)
{
this.Value1 = (MOD + this.Value1 - powers1[n] * c % MOD) % MOD;
this.Value2 = (MOD + this.Value2 - powers2[n] * c % MOD) % MOD;
}
}
}
<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/CheckABitAtGivenPosition/CheckBit.cs
//Write a Boolean expression that returns if the bit at position p (counting from 0, starting from the right)
//in given integer number n, has value of 1.
using System;
class CheckBit
{
static void Main()
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
Console.Write("Enter index p: ");
int index = int.Parse(Console.ReadLine());
int getBit = number >> index & 1;
bool result = getBit == 1;
Console.WriteLine(result);
}
}
<file_sep>/C#/OOP/DefiningClassesPartOne/GSMTest/TestGSM.cs
namespace GSMTest
{
using System;
using GSMInfo;
class TestGSM
{
static void Main()
{
GSM[] phones = new GSM[] { new GSM("Lumia", "Microsoft", "Pesho"), new GSM("Galaxy", "Samsung", "Gosho"), new GSM("Iphone 6", "Apple", "Asen") };
phones[0].BatteryInfo.HoursTalk = 325;
phones[0].BatteryInfo.MAhCapacity = 4000;
phones[1].DisplayInfo.Colors = 256;
phones[1].Price = 200;
phones[2].DisplayInfo.Size = 6;
phones[2].BatteryInfo.MAhCapacity = 2000;
foreach (GSM phone in phones)
{
Console.WriteLine(phone);
Console.WriteLine();
}
Console.WriteLine(GSM.IPhone4S.Manufacturer + " " + GSM.IPhone4S.Model);
}
}
}
<file_sep>/C#/C# Programming Part I/Loops/PrintADeckOF52Cards/PrintCards.cs
//Write a program that generates and prints all possible cards from a standard deck of 52 cards
//(without the jokers). The cards should be printed using the classical notation
//(like 5 of spades, A of hearts, 9 of clubs; and K of diamonds).
//The card faces should start from 2 to A.
//Print each card face in its four possible suits: clubs, diamonds, hearts and spades.
//Use 2 nested for-loops and a switch-case statement.
using System;
using System.Text;
class PrintCards
{
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
for (int i = 2; i <= 14; i++)
{
if (i < 11)
{
Console.WriteLine("{0,2}\u2663, {0,2}\u2660, {0,2}\u2665, {0,2}\u2666", i);
}
switch (i)
{
case 11:
Console.WriteLine("{0,2}\u2663, {0,2}\u2660, {0,2}\u2665, {0,2}\u2666", "J");
break;
case 12:
Console.WriteLine("{0,2}\u2663, {0,2}\u2660, {0,2}\u2665, {0,2}\u2666", "Q");
break;
case 13:
Console.WriteLine("{0,2}\u2663, {0,2}\u2660, {0,2}\u2665, {0,2}\u2666", "K");
break;
case 14:
Console.WriteLine("{0,2}\u2663, {0,2}\u2660, {0,2}\u2665, {0,2}\u2666", "A");
break;
default:
break;
}
}
}
}
<file_sep>/C#/C# Programming Part II/Methods/SortingArray/SortAlgo.cs
//Write a method that return the maximal element in a portion of array of integers starting at given index.
//Using it write another method that sorts an array in ascending / descending order.
using System;
class SortAlgo
{
static void Main()
{
int[] intArray = new int[] { 10, 2, 5, 6, 4, 8, 2, 4, 2, 6, 2, 4 };
Sort(intArray);
Console.WriteLine("Sorted in descending order: {0}", string.Join(" ", intArray));
Array.Reverse(intArray);
Console.WriteLine("Sorted in ascending order: {0}", string.Join(" ", intArray));
}
static int FindMax(int[] array, int start = 0)
{
int biggest = 0;
int index = 0;
for (int i = start; i < array.Length; i++)
{
if (array[i] > biggest)
{
biggest = array[i];
index = i;
}
}
return index;
}
static void Sort(int[] toSort)
{
for (int i = 0; i < toSort.Length; i++)
{
int maxNumIndex = FindMax(toSort, i);
int temp = toSort[i];
toSort[i] = toSort[maxNumIndex];
toSort[maxNumIndex] = temp;
}
}
}
<file_sep>/C#/C# Programming Part I/IntroToProgramming/AgeAfter10Years/AgeAfter10Years.cs
//Write a program to read your birthday from the console and print how old you are now and how old you will be after 10 years.
using System;
class AgeAfter10Years
{
static void Main()
{
Console.Write("Please write your birthday (dd.mm.yyyy):");
string input = Console.ReadLine();
DateTime birthday = DateTime.Parse(input);
int age = DateTime.Now.Year - birthday.Year;
if (birthday.AddYears(age) > DateTime.Now) //Checks if person has had birthday yet
{
age -= 1;
}
Console.WriteLine("You are " + age + " years old now and you'll be " + (age + 10) + " in ten years.");
}
}
<file_sep>/C#/C# Programming Part II/UsingClassesAndObjects/Workdays/WorkDaysCounter.cs
//Write a method that calculates the number of workdays between today and given date, passed as parameter.
//Consider that workdays are all days from Monday to Friday except a fixed list of public holidays specified preliminary as array.
using System;
using System.Collections.Generic;
class WorkDaysCounter
{
static void Main()
{
Console.Write("Enter end date: ");
DateTime endDate = DateTime.Parse(Console.ReadLine());
int count = 0;
for (DateTime i = DateTime.Now; i < endDate.AddDays(1); i = i.AddDays(1))
{
if (CheckHolidays(i))
{
if ((int)i.DayOfWeek == 0 || ((int)i.DayOfWeek == 6))
{
continue;
}
count++;
}
}
Console.WriteLine("There are {0} workdays from today until {1}", count, endDate);
}
static bool CheckHolidays(DateTime toCheck)
{
DateTime[] holidays = { new DateTime(0001, 03, 03), new DateTime(0001, 05, 24), new DateTime(0001, 09, 06),
new DateTime(0001, 05, 01), new DateTime(0001, 05, 06), new DateTime(0001, 09, 22),
new DateTime(0001, 12, 24), new DateTime(0001, 12, 25), new DateTime(0001, 01, 01) };
for (int i = 0; i < holidays.Length; i++)
{
if (toCheck.Day == holidays[i].Day && toCheck.Month == holidays[i].Month)
{
return false;
}
}
return true;
}
}
<file_sep>/C#/C# Programming Part II/Methods/LargerThanNeighbours/NeighboursComparer.cs
//Write a method that checks if the element at given position in given array of integers is larger than its two neighbours (when such exist).
using System;
class NeighboursComparer
{
static void Main()
{
Console.Write("Enter a row of numbers separated by space: ");
string[] arrayInput = Console.ReadLine().Split();
Console.Write("Enter the position you want to check: ");
int positionInput = int.Parse(Console.ReadLine());
CheckNeighbours(arrayInput, positionInput);
}
static void CheckNeighbours(string[] inputArray, int position)
{
if (position + 1 >= inputArray.Length || position - 1 < 0)
{
Console.WriteLine("The element does not have two neighbours.");
}
else
{
bool checkPrevious = int.Parse(inputArray[position]) > int.Parse(inputArray[position - 1]);
bool checkNext = int.Parse(inputArray[position]) > int.Parse(inputArray[position + 1]);
if (checkNext && checkPrevious) Console.WriteLine("The element is larger than it's two neighbours.");
else Console.WriteLine("The element is not larger than it's two neighbours.");
}
}
}
<file_sep>/C#/C# Programming Part I/ConsoleInputOutput/CirclePerimeterAndArea/CircleParameters.cs
//Write a program that reads the radius r of a circle and prints its perimeter
//and area formatted with 2 digits after the decimal point.
using System;
class CircleParameters
{
static void Main()
{
Console.Write("Enter radius: ");
double radius = double.Parse(Console.ReadLine());
double perimeter = 2 * Math.PI * radius;
double area = Math.PI * radius * radius;
Console.WriteLine("Perimeter: {0,5:0.00}\nArea: {1,10:0.00}", perimeter, area);
}
}
<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/BitExchangeAdvanced/SwitchBitsAdvanced.cs
//Write a program that exchanges bits {p, p+1, …, p+k-1} with bits {q, q+1, …, q+k-1} of a given 32-bit unsigned integer.
//The first and the second sequence of bits may not overlap.
using System;
class SwitchBitsAdvanced
{
static void Main()
{
Console.Write("Enter number: ");
long number = long.Parse(Console.ReadLine());
Console.Write("Enter p value: ");
int p = int.Parse(Console.ReadLine());
Console.Write("Enter q value: ");
int q = int.Parse(Console.ReadLine());
Console.Write("Enter k value: ");
int k = int.Parse(Console.ReadLine());
if ((p + k) > Convert.ToString(number, 2).Length || (q + k) > Convert.ToString(number, 2).Length || p < 0 || q < 0)
{
Console.WriteLine("out of range");
}
else if ((Math.Min(p, q) + k) > Math.Max(p, q))
{
Console.WriteLine("overlapping");
}
else
{
int a;
int b;
for (a = p, b = q; a <= (p + k - 1); a++, b++)
{
long getBitA = (number >> a) & 1; //Gets the value of the bit at the current position
long getBitB = (number >> b) & 1;
if ((getBitA == 1) && (getBitB == 1))
{
number = number | (1 << b); //Switches the original bits with 1s and 0s depending on the case
number = number | (1 << a); //In this case both are ones
}
else if ((getBitA == 1) && (getBitB == 0))
{
number = number | (1 << b);
number = number & ~(1 << a);
}
else if ((getBitA == 0) && (getBitB == 1))
{
number = number & ~(1 << b);
number = number | (1 << a);
}
else
{
number = number & ~(1 << b);
number = number & ~(1 << a);
}
}
Console.WriteLine(number);
}
}
}
<file_sep>/C#/C# Programming Part II/ExceptionHandling/EnterNumbers/Program.cs
//Write a method ReadNumber(int start, int end) that enters an integer number in a given range [start…end].
//If an invalid number or non-number text is entered, the method should throw an exception.
//Using this method write a program that enters 10 numbers: a1, a2, … a10, such that 1 < a1 < … < a10 < 100
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> tenNums = new List<int>(10);
try
{
ReadNumber(tenNums);
Console.WriteLine(string.Join(" ", tenNums));
}
catch (Exception theException)
{
Console.WriteLine(theException.Message);
}
}
static void ReadNumber(List<int> addNums)
{
for (int i = 0; i < 10; i++)
{
Console.Write("Enter number {0}: ", i);
int input = int.Parse(Console.ReadLine());
if (addNums.Count > 0 && input < addNums[i - 1])
{
throw new ArgumentException("Number shoud be bigger than previous.");
}
addNums.Add(input);
}
}
}
<file_sep>/C#/C# Programming Part II/MultidimensionalArrays/MaximalSum/MaxSumFinder.cs
//Write a program that reads a rectangular matrix of size N x M and finds in it the square 3 x 3 that has maximal sum of its elements.
using System;
class MaxSumFinder
{
static void Main()
{
Console.Write("Enter N (at least 3): ");
int n = int.Parse(Console.ReadLine());
Console.Write("Enter M (at least 3): ");
int m = int.Parse(Console.ReadLine());
int maxSum = 0;
int maxSumRow = 0;
int maxSumCol = 0;
int[,] matrix = new int[n, m];
for (int row = 0; row < n; row++)
{
for (int col = 0; col < m; col++)
{
Console.Write("Enter element {0},{1} : ", row, col);
matrix[row, col] = int.Parse(Console.ReadLine());
}
}
for (int row = 0; row < matrix.GetLength(0) - 2; row++)
{
for (int col = 0; col < matrix.GetLength(1) - 2; col++)
{
int currentSum = matrix[row, col] + matrix[row, col + 1] + matrix[row, col + 2]
+ matrix[row + 1, col] + matrix[row + 1, col + 1] + matrix[row + 1, col + 2]
+ matrix[row + 2, col] + matrix[row + 2, col + 1] + matrix[row + 2, col + 2];
if (currentSum > maxSum)
{
maxSum = currentSum;
maxSumRow = row;
maxSumCol = col;
}
}
}
Console.WriteLine("Max sum : {0}",maxSum);
Console.WriteLine("{0,3}{1,3}{2,3}", matrix[maxSumRow, maxSumCol], matrix[maxSumRow, maxSumCol + 1], matrix[maxSumRow, maxSumCol + 2]);
Console.WriteLine("{0,3}{1,3}{2,3}", matrix[maxSumRow + 1, maxSumCol], matrix[maxSumRow + 1, maxSumCol + 1], matrix[maxSumRow + 1, maxSumCol + 2]);
Console.WriteLine("{0,3}{1,3}{2,3}", matrix[maxSumRow + 2, maxSumCol], matrix[maxSumRow + 2, maxSumCol + 1], matrix[maxSumRow + 2, maxSumCol + 2]);
}
}
<file_sep>/C#/OOP/CommonTypeSystem/Student/Enumarations/Faculty.cs
namespace Student.Enumarations
{
public enum Faculty
{
Mathematical,
Biological,
Historical
}
}
<file_sep>/C#/C# Programming Part II/Arrays/MaximalSum/FindsMaxSum.cs
//Write a program that finds the sequence of maximal sum in given array.
using System;
class FindsMaxSum
{
static void Main()
{
Console.Write("Please enter a row of integers separated by space: ");
string[] inputArray = Console.ReadLine().Split();
int[] intArray = new int[inputArray.Length];
for (int i = 0; i < inputArray.Length; i++)
{
intArray[i] = int.Parse(inputArray[i]);
}
int maxSum = 0;
int maxSumStart = 0;
int maxSumEnd = 0;
for (int i = 0; i < intArray.Length; i++)
{
int currSum = 0;
for (int j = i; j < intArray.Length; j++)
{
currSum += intArray[j];
if (currSum > maxSum)
{
maxSum = currSum;
maxSumStart = i;
maxSumEnd = j;
}
}
}
Console.WriteLine(maxSum);
for (int i = maxSumStart; i <= maxSumEnd; i++)
{
Console.Write(intArray[i] + " ");
}
Console.WriteLine();
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Strings/Strings/02.Correct brackets.js
console.log('\nTask 2: Write a JavaScript function to check if in a given expression the brackets are put correctly.');
function checkBrackets(str) {
var i,
length,
leftBr = 0,
rightBr = 0;
for (i = 0, length = str.length; i < length; i += 1) {
if (str[i] === '(') leftBr += 1;
else if (str[i] === ')') rightBr += 1;
if (rightBr > leftBr) return false;
}
return leftBr === rightBr;
}
console.log('(a+b)): ' + checkBrackets('(a+b))'));
console.log(')(a+b)): ' + checkBrackets(')(a+b))'));
console.log('((a+b)/5-d): ' + checkBrackets('((a+b)/5-d)'));
<file_sep>/C#/OOP/CommonTypeSystem/Person/TestPerson.cs
namespace Person
{
class TestPerson
{
static void Main()
{
Person someone = new Person("Pesho") { Age = 25};
System.Console.WriteLine(someone);
Person anotherone = new Person("Gosho");
System.Console.WriteLine(anotherone);
}
}
}
<file_sep>/C#/OOP/DefiningClassesPartOne/CallHistoryTest/GSMCallHistoryTest.cs
namespace CallHistoryTest
{
using System;
using GSMInfo;
using System.Collections.Generic;
public class GSMCallHistoryTest
{
static void Main()
{
GSM testPhone = new GSM("Lumia", "Microsoft");
testPhone.AddCall(new DateTime(2015, 1, 1), 0888123456, 50);
testPhone.AddCall(new DateTime(2015, 1, 10), 0888123456, 50);
testPhone.AddCall(DateTime.Now, 0888123456, 100);
PrintCalls(testPhone.CallHistory);
Console.WriteLine("Total price is {0}", testPhone.TotalCallsPrice(0.37));
int longestCallIndex = FindLongestCall(testPhone.CallHistory);
testPhone.DeleteCall(longestCallIndex);
Console.WriteLine("Total price after removal of longest call is {0}", testPhone.TotalCallsPrice(0.37));
testPhone.ClearCallHistory();
PrintCalls(testPhone.CallHistory);
}
public static int FindLongestCall(List<Call> callList)
{
double longestCall = 0;
int longestCallIndex = 0;
for (int i = 0; i < callList.Count; i++)
{
double currentCallDuration = callList[i].Duration;
if (longestCall < currentCallDuration)
{
longestCall = currentCallDuration;
longestCallIndex = i;
}
}
return longestCallIndex;
}
public static void PrintCalls(List<Call> callList)
{
if (callList.Count < 1)
{
Console.WriteLine("There are no calls in the call history!");
}
foreach (Call call in callList)
{
Console.WriteLine(call);
Console.WriteLine();
}
}
}
}
<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/ExtractBitFromInteger/ExtractBit.cs
//Write an expression that extracts from given integer n the value of given bit at index p.
using System;
class ExtractBit
{
static void Main()
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
Console.Write("Enter index p: ");
int index = int.Parse(Console.ReadLine());
int bitAtP = number >> index & 1;
Console.WriteLine("The bit at P is: " + bitAtP);
}
}
<file_sep>/C#/C# Programming Part II/MultidimensionalArrays/SequenceNMatrix/LongestSequence.cs
//Write a program that finds the longest sequence of equal strings in the matrix.
//We are given a matrix of strings of size N x M. Sequences in the matrix we define as sets of several neighbour elements located on the same line, column or diagonal.
using System;
class LongestSequence
{
static void Main()
{
Console.Write("Enter N: ");
int n = int.Parse(Console.ReadLine());
Console.Write("Enter M: ");
int m = int.Parse(Console.ReadLine());
int maxSequence = 1;
int sequenceStartRow = 0;
int sequenceStartCol = 0;
string[,] matrix = new string[n, m]; //{
//{"ha","fifi","ho","hi"},
//{"fo","ha","hi","xx"},
//{"xxx","ho","ha","xa"}
//};
for (int row = 0; row < n; row++)
{
for (int col = 0; col < m; col++)
{
Console.Write("Enter element {0},{1} : ", row, col);
matrix[row, col] = Console.ReadLine();
}
}
for (int row = 0; row < matrix.GetLength(0); row++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
int currentSequence = 1;
for (int i = col; i < matrix.GetLength(1) - 1; i++) //Checks lines.
{
if (matrix[row, i] == matrix[row, i + 1])
{
currentSequence++;
if (currentSequence > maxSequence)
{
maxSequence = currentSequence;
sequenceStartRow = row;
sequenceStartCol = col;
}
}
else
{
break;
}
}
currentSequence = 1;
for (int i = row; i < matrix.GetLength(0) - 1; i++) //Checks rows.
{
if (matrix[i, col] == matrix[i + 1, col])
{
currentSequence++;
if (currentSequence > maxSequence)
{
maxSequence = currentSequence;
sequenceStartRow = row;
sequenceStartCol = col;
}
}
else
{
break;
}
}
currentSequence = 1;
for (int i = 0; i < matrix.GetLength(1) - 1 - col && i < matrix.GetLength(0) - 1 - row; i++) //Checks first diagonal.
{
if (matrix[row + i, col + i] == matrix[row + i + 1, col + i + 1])
{
currentSequence++;
if (currentSequence > maxSequence)
{
maxSequence = currentSequence;
sequenceStartRow = row;
sequenceStartCol = col;
}
}
else
{
break;
}
}
currentSequence = 1;
for (int i = 0; i < matrix.GetLength(1) - 1 - col && i < matrix.GetLength(0) - 1 - row && col - i - 1 > 0; i++) //Checks second diagonal.
{
if (matrix[row + i, col - i] == matrix[row + i + 1, col - i - 1])
{
currentSequence++;
if (currentSequence > maxSequence)
{
maxSequence = currentSequence;
sequenceStartRow = row;
sequenceStartCol = col;
}
}
else
{
break;
}
}
}
}
for (int i = 0; i < maxSequence; i++)
{
Console.Write("{0} ", matrix[sequenceStartRow, sequenceStartCol]);
}
}
}
<file_sep>/C#/C# Programming Part I/ConditionalStatements/TheBiggestOfFiveNumbers/BiggestNumber.cs
//Write a program that finds the biggest of five numbers by using only five if statements.
using System;
class BiggestNumber
{
static void Main()
{
Console.Write("Enter A: ");
double a = double.Parse(Console.ReadLine());
Console.Write("Enter B: ");
double b = double.Parse(Console.ReadLine());
Console.Write("Enter C: ");
double c = double.Parse(Console.ReadLine());
Console.Write("Enter D: ");
double d = double.Parse(Console.ReadLine());
Console.Write("Enter E: ");
double e = double.Parse(Console.ReadLine());
double biggest = a;
if (b > a)
{
biggest = b;
}
if (c > biggest)
{
biggest = c;
}
if (d > biggest)
{
biggest = d;
}
if (e > biggest)
{
biggest = e;
}
Console.WriteLine(biggest);
}
}
<file_sep>/C#/C# Programming Part II/StringsAndTextProcessing/ParseURL/ParseURL.cs
//Write a program that parses an URL address given in the format: [protocol]://[server]/[resource] and extracts from it the [protocol], [server] and [resource] elements.
using System;
using System.Text.RegularExpressions;
class ParseURL
{
static void Main()
{
string url = Console.ReadLine();
var fragments = Regex.Match(url, "(.*)://(.*?)(/.*)").Groups;
Console.WriteLine("URL Address: {0}", url);
Console.WriteLine("\n[protocol] = {0}", fragments[1]);
Console.WriteLine("[server] = {0}", fragments[2]);
Console.WriteLine("[resource] = {0}\n", fragments[3]);
}
}
<file_sep>/C#/C# Programming Part II/UsingClassesAndObjects/ArithmeticalExpressions/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArithmeticalExpressions
{
class Program
{
static void Main(string[] args)
{
double a = 1.33f;
double b = 1f;
double c = 0.33f;
bool check = a == b + c;
Console.Write("1.33 = {0}\n 1 = {1}\n 0.33= {2}\n", a, b, c);
}
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Arrays/Increase array members/05.Selection sort.js
var left,
right,
tmp,
arr = [8, 12, 3, 4, 5, 2, 11, 13, 7, 4, 15, 14, 12, 8, 1],
len = arr.length;
console.log('\nTask 5: Write a script to sort an array. Use the selection sort algorithm.');
for (left = 0; left < len; left++) {
for (right = left + 1; right < len; right++) {
if (arr[left] > arr[right]) {
tmp = arr[right];
arr[right] = arr[left];
arr[left] = tmp;
}
}
}
console.log('sorted: ' + arr);
<file_sep>/C#/C# Programming Part II/UsingClassesAndObjects/SumIntegers/IntSumator.cs
//You are given a sequence of positive integer values written into a string, separated by spaces.
//Write a function that reads these values from given string and calculates their sum.
using System;
class IntSumator
{
static void Main()
{
string[] inputArray = Console.ReadLine().Split();
int sum = 0;
for (int i = 0; i < inputArray.Length; i++)
{
sum += int.Parse(inputArray[i]);
}
Console.WriteLine(sum);
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Array Methods/Array Methods/01.Make person.js
console.log('Task 1: Write a function for creating persons. Each person must have firstname, lastname, age and gender (true is female, false is male) Generate an array with ten person with different names, ages and genders.');
var arr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
fnames = ['Joy', 'Nicky', 'Aleks', 'Grui', 'Jay', 'Zoy', 'Nelli', 'Pol', 'Gol', 'Sol'],
lnames = ['Peterson', 'Johnson', 'Bolton', 'Clapton', 'Pikachu', 'Winfrey', 'Spencer', 'Cloppenburg', 'Heisenburg', 'West'];
var people = arr.map(function (_, i) {
return { fname: fnames[i], lname: lnames[i], age: Math.random() * 100 | 0, gender: !(Math.round(Math.random())) };
});
console.log(people);
<file_sep>/C#/C# Programming Part II/StringsAndTextProcessing/CorrectBrackets/BracketsChecker.cs
//Write a program to check if in a given expression the brackets are put correctly.
//Example of correct expression: ((a+b)/5-d). Example of incorrect expression: )(a+b)).
using System;
class BracketsChecker
{
static void Main()
{
Console.Write("Enter a math expression: ");
string input = Console.ReadLine();
int openingBrackets = 0;
int closingBrackets = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '(')
{
openingBrackets++;
}
else if (input[i] == ')')
{
closingBrackets++;
if (closingBrackets > openingBrackets)
{
Console.WriteLine("Brackets are not put correctly.");
break;
}
}
if (i == input.Length - 1 && closingBrackets == openingBrackets) Console.WriteLine("Brackets are correct.");
else if (i == input.Length - 1) Console.WriteLine("Brackets are not put correctly.");
}
}
}
<file_sep>/C#/C# Programming Part II/Arrays/FindSumInArray/FindSum.cs
//Write a program that finds in given array of integers a sequence of given sum S (if present).
using System;
class FindSum
{
static void Main()
{
Console.Write("Please enter a row of integers separated by space: ");
string[] inputArray = Console.ReadLine().Split();
int[] intArray = new int[inputArray.Length];
for (int i = 0; i < inputArray.Length; i++)
{
intArray[i] = int.Parse(inputArray[i]);
}
Console.Write("Please enter sum: ");
int sum = int.Parse(Console.ReadLine());
int sumStart = 0;
int sumEnd = 0;
for (int i = 0; i < intArray.Length; i++)
{
int currSum = 0;
for (int j = i; j < intArray.Length; j++)
{
currSum += intArray[j];
if (currSum == sum)
{
sumStart = i;
sumEnd = j;
}
}
}
for (int i = sumStart; i <= sumEnd; i++)
{
Console.Write(intArray[i] + " ");
}
Console.WriteLine();
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Arrays/Increase array members/01. ncrease array members.js
var i,
arr = new Array(20),
len = arr.length;
console.log('\nTask 1: Write a script that allocates array of 20 integers and initializes each element by its index multiplied by 5. \nPrint the obtained array on the console.');
for (i = 0; i < len; i += 1) {
arr[i] = i * 5;
}
console.log(arr);<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/FourDigitNumber/FourDigits.cs
//Write a program that takes as input a four-digit number in format abcd (e.g. 2011) and performs the following:
//Calculates the sum of the digits (in our example 2 + 0 + 1 + 1 = 4).
//Prints on the console the number in reversed order: dcba (in our example 1102).
//Puts the last digit in the first position: dabc (in our example 1201).
//Exchanges the second and the third digits: acbd (in our example 2101).
//The number has always exactly 4 digits and cannot start with 0.
using System;
class FourDigits
{
static void Main()
{
Console.Write("Please enter a four-digit number: ");
string input = Console.ReadLine();
char a = input[0];
char b = input[1];
char c = input[2];
char d = input[3];
int intA = (int)char.GetNumericValue(a);
int intB = (int)char.GetNumericValue(b);
int intC = (int)char.GetNumericValue(c);
int intD = (int)char.GetNumericValue(d);
Console.WriteLine(intA + intB + intC + intD);
Console.WriteLine("{0}{1}{2}{3}", d, c, b, a);
Console.WriteLine("{0}{1}{2}{3}", d, a, b, c);
Console.WriteLine("{0}{1}{2}{3}", a, c, b, d);
}
}
<file_sep>/Java Script/JavaScript UI and DOM/DOMOperations/CrazyDivs Homework/script.js
var randomDivs = function () {
var i,
div = document.createElement('div'),
wrapper = document.createElement('div'),
fragment = document.createDocumentFragment();
wrapper.id = 'wrapper';
div.style.position = 'absolute';
div.style.borderStyle = 'solid';
div.innerHTML = '<strong>div</strong>';
for (i = 0; i < randomize() ; i += 1) {
var currentDiv = div.cloneNode(true),
strongTag = currentDiv.getElementsByTagName('strong')[0];
currentDiv.style.width = randomize(20, 100) + 'px';
currentDiv.style.height = randomize(20, 100) + 'px';
currentDiv.style.color = randomColor();
currentDiv.style.background = randomColor();
currentDiv.style.left = randomize(0, 1000) + 'px';
currentDiv.style.top = randomize(0, 600) + 'px';
currentDiv.style.borderColor = randomColor();
currentDiv.style.borderWidth = randomize(1, 20) + 'px';
currentDiv.style.borderRadius = randomize(1, 20) + 'px';
strongTag.style.position = 'absolute';
strongTag.style.top = '30%';
strongTag.style.left = '30%';
wrapper.appendChild(currentDiv);
}
fragment.appendChild(wrapper);
document.body.insertBefore(fragment, document.body.firstChild);
}
randomDivs();
var rotateDivs = function () {
var i,
rotatingDivs,
firstElementTopPosition,
firstElementLeftPosition,
wrap = document.getElementById('wrapper'),
divs = wrap.getElementsByTagName('div'),
rotatingDivsContainer = document.createElement('div'),
numberOfRotatableDivs = 5;
for (i = 0; i < numberOfRotatableDivs; i += 1) {
rotatingDivsContainer.appendChild(divs[divs.length - 1 - i]);
}
document.body.appendChild(rotatingDivsContainer);
rotatingDivs = rotatingDivsContainer.getElementsByTagName('div');
setInterval(function () {
var i;
firstElementTopPosition = rotatingDivs[0].style.top;
firstElementLeftPosition = rotatingDivs[0].style.left;
for (i = 0; i < numberOfRotatableDivs - 1; i += 1) {
rotatingDivs[i].style.top = rotatingDivs[i + 1].style.top;
rotatingDivs[i].style.left = rotatingDivs[i + 1].style.left;
}
rotatingDivs[numberOfRotatableDivs - 1].style.top = firstElementTopPosition;
rotatingDivs[numberOfRotatableDivs - 1].style.left = firstElementLeftPosition;
}, 250);
}
rotateDivs();
//retuns random number between min inclusive and max exclusive, default values 10/100
function randomize(min, max) {
var randomResult;
max = max || 100;
min = min || 10;
randomResult = (Math.random() * (max - min) + min) | 0;
return randomResult;
}
function randomColor() {
var randomColor = 'rgba(' + randomize(0, 256) + ',' + randomize(0, 256) + ',' +
randomize(0, 256) + ',' + randomize(0, 256) + ')';
return randomColor;
}
//var input1 = document.createElement('input');
//var input2 = document.createElement('input');
//var input3 = document.createElement('input');
//var btn = document.createElement('button');
//input1.type = 'text';
//input2.type = 'color';
//input3.type = 'color';
//btn.innerHTML = 'do work';
//btn.onclick = updateTextInputField;
//function updateTextInputField() {
// input1.style.color = input2.value;
// input1.style.backgroundColor = input3.value;
//}
//document.body.appendChild(input1);
//document.body.appendChild(input2);
//document.body.appendChild(input3);
//document.body.appendChild(btn);<file_sep>/C#/C# Programming Part I/PrimitiveDataTypesAndVariables/PrintTheASCIITable/ASCIITable.cs
//Find online more information about ASCII (American Standard Code for Information Interchange) and write a program that prints
//the entire ASCII table of characters on the console (characters from 0 to 255).
using System;
using System.Text;
class ASCIITable
{
static void Main()
{
for (int i = 0; i <= 255; i++)
{
char asciiCharacter = (char)i;
Console.WriteLine(asciiCharacter);
}
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Strings/Strings/12. Generate list.js
console.log('\nTask 12: Write a function that creates a HTML <ul> using a template for every HTML <li>. The source of the list should be an array of elements. Replace all placeholders marked with –{…}– with the value of the corresponding property of the object.');
function generateList(people, template) {
var resultHTML = '<ul>',
i;
for (i = 0; i < people.length; i += 1) {
resultHTML += '<li>';
resultHTML += template.replace('-{name}-', people[i]['name']).replace('-{age}-', people[i]['age']);
resultHTML += '</li>';
}
return resultHTML + '</ul>';
}
var people = [{ name: 'Peter', age: 14 },
{ name: 'Ivan', age: 18 },
{ name: 'Asen', age: 29 }];
var template = '<strong>-{name}-</strong> <span>-{age}-</span>';
console.log(generateList(people, template));
<file_sep>/Java Script/JavaScript Fundmentals/Arrays/Increase array members/03.Maximal sequence.js
var i,
recurringElement,
result = [],
currentMax = 1,
max = currentMax,
arr = [2, 1, 1, 2, 3, 3, 2, 2, 2, 1],
len = arr.length;
console.log('\nTask 3: Write a script that finds the maximal sequence of equal elements in an array.');
for (i = 0; i < len - 1; i += 1) {
if (arr[i] === arr[i + 1]) {
currentMax += 1;
if (currentMax > max) {
max = currentMax;
recurringElement = arr[i];
}
} else {
currentMax = 1;
}
}
for (i = 0; i < max; i += 1) {
result[i] = recurringElement;
}
console.log('result: ' + result);<file_sep>/Java Script/JavaScript Fundmentals/Array Methods/Array Methods/06.Group people.js
console.log('\nTask 6: Write a function that groups an array of persons by first letter of first name and returns the groups as a JavaScript Object. Use Array#reduce. Use only array methods and no regular loops (for, while)');
var arr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
fnames = ['Joy', 'Nicky', 'Aleks', 'Grui', 'Jay', 'Zoy', 'Nelli', 'Pol', 'Gol', 'Sol'],
lnames = ['Peterson', 'Johnson', 'Bolton', 'Clapton', 'Pikachu', 'Winfrey', 'Spencer', 'Cloppenburg', 'Heisenburg', 'West'];
var people = arr.map(function (_, i) {
return { fname: fnames[i], lname: lnames[i], age: Math.random() * 100 | 0, gender: !(Math.round(Math.random())) };
});
var result = {};
people.reduce(function (_, person) {
if (!result[person.fname[0]]) result[person.fname[0]] = [];
result[person.fname[0]].push(person);
}, 0);
console.log(result);<file_sep>/C#/C# Programming Part I/ConsoleInputOutput/QuadraticEquation/QuadraticEquationsCalculator.cs
//Write a program that reads the coefficients a, b and c of a quadratic equation ax2 + bx + c = 0 and solves it (prints its real roots).
using System;
class QuadraticEquationsCalculator
{
static void Main()
{
Console.Write("Enter coefficient a: ");
double a = double.Parse(Console.ReadLine());
if (a == 0) //Coeff. a should not be zero.
{
do
{
Console.Write("Coefficient a should be different than 0, try again: ");
a = double.Parse(Console.ReadLine());
} while (a == 0);
}
Console.Write("Enter coefficient b: ");
double b = double.Parse(Console.ReadLine());
Console.Write("Enter coefficient c: ");
double c = double.Parse(Console.ReadLine());
double discriminant = b * b - 4 * a * c;
if (discriminant < 0)
{
Console.WriteLine("There are no real roots.");
}
else if (discriminant == 0)
{
double result = -b / (2 * a);
Console.WriteLine("The equation has a double root: " + result);
}
else
{
double result1 = (-b - Math.Sqrt(discriminant)) / (2 * a);
double result2 = (-b + Math.Sqrt(discriminant)) / (2 * a);
Console.WriteLine("The roots are {0} and {1}", result1, result2);
}
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Using Objects/Using Objects/04.Has property.js
console.log('\nTask 4: Write a function that checks if a given object contains a given property.');
function hasProperty(obj, proper) {
for (var prop in obj) {
if (prop === proper) return true;
}
return false;
}
var someObj = { something: 10, someOthreThing: 20 };
console.log('var someObj = { something: 10, someOthreThing: 20 }');
console.log('Has property: something? ' + hasProperty(someObj, 'something'));<file_sep>/C#/C# Programming Part II/StringsAndTextProcessing/ReverseString/StringReverser.cs
//Write a program that reads a string, reverses it and prints the result at the console.
using System;
class StringReverser
{
static void Main()
{
Console.Write("Enter some text: ");
string input = Console.ReadLine();
char[] reverse = input.ToCharArray();
Array.Reverse(reverse);
Console.WriteLine(reverse);
}
}
<file_sep>/C#/C# Programming Part II/MultidimensionalArrays/LargestAreaInMatrix/LargestArea.cs
//Write a program that finds the largest area of equal neighbour elements in a rectangular matrix and prints its size.
using System;
class LargestArea
{
static void Main()
{
int[,] inputArray = {{1,3,2,2,2,4},
{3,3,3,2,4,4},
{4,3,1,2,3,3},
{4,3,1,3,3,1},
{4,3,3,3,1,1}};
bool[,] checkedCells = new bool[inputArray.GetLength(0), inputArray.GetLength(1)];
int maxCount = 1;
for (int row = 0; row < inputArray.GetLength(0); row++)
{
for (int col = 0; col < inputArray.GetLength(1); col++)
{
if (!checkedCells[row, col])
{
int currentCount = FindNeighbours(inputArray, row, col, checkedCells);
if (currentCount > maxCount)
{
maxCount = currentCount;
}
}
}
}
Console.WriteLine(maxCount);
}
static int FindNeighbours(int[,] matrix, int currentRow, int currentCol, bool[,]check)
{
int count = 1;
check[currentRow, currentCol] = true;
if (currentCol + 1 < matrix.GetLength(1))
{
if (matrix[currentRow, currentCol] == matrix[currentRow, currentCol + 1] && !check[currentRow, currentCol + 1])
{
count += FindNeighbours(matrix, currentRow, currentCol + 1, check);
}
}
if (currentRow + 1 < matrix.GetLength(0))
{
if (matrix[currentRow, currentCol] == matrix[currentRow + 1, currentCol] && !check[currentRow + 1, currentCol])
{
count += FindNeighbours(matrix, currentRow + 1, currentCol, check);
}
}
if (currentCol - 1 >= 0)
{
if (matrix[currentRow, currentCol] == matrix[currentRow, currentCol - 1] && !check[currentRow, currentCol - 1])
{
count += FindNeighbours(matrix, currentRow, currentCol - 1, check);
}
}
if (currentRow - 1 >= 0)
{
if (matrix[currentRow, currentCol] == matrix[currentRow - 1, currentCol] && !check[currentRow - 1, currentCol])
{
count += FindNeighbours(matrix, currentRow - 1, currentCol, check);
}
}
return count;
}
}
<file_sep>/Java Script/JavaScript OOP/Functions and Function Expressions/Functions and Function Expressions/task-2.js
(function () {
function findPrimes(from, to) {
var i,
j,
from,
to,
maxDevider,
tempRange,
isPrime,
result = [];
if (!from || !to) throw 'Arguments Missing Error';
from = +from;
to = +to;
if (isNaN(from) || isNaN(to)) throw 'Arguments NaN Error';
if (from > to) {
tempRange = from;
from = to;
to = tempRange;
}
for (i = from; i <= to; i += 1) {
maxDevider = Math.sqrt(i);
isPrime = true;
for (j = 2; j <= maxDevider; j += 1) {
if (!(i % j)) isPrime = false;
}
if (isPrime) result.push(i);
}
return result;
}
console.log(findPrimes(5, 10));
}());<file_sep>/C#/C# Programming Part II/NumeralSystems/BinaryToDecimal/BinToDecConverter.cs
//Write a program to convert binary numbers to their decimal representation.
using System;
class BinToDecConverter
{
static void Main()
{
string input = Console.ReadLine();
double result = new int();
int powersOfTwo = 1;
for (int i = input.Length - 1; i >= 0; i--)
{
result += (input[i] - '0') * powersOfTwo;
powersOfTwo *= 2;
}
Console.WriteLine(result);
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Strings/Strings/07. Parse URL.js
console.log('\nTask 7: Write a script that parses an URL address given in the format: [protocol]://[server]/[resource] and extracts from it the [protocol], [server] and [resource] elements. Return the elements in a JSON object.');
var url = 'https://github.com/TelerikAcademy/JavaScript-Fundamentals/blob/master/11.%20Strings/README.md';
function parseURL(url) {
var obj = {
protocol: url.match(/[^:]*/)[0],
server: url.match(/[^\/]*\.[^\/]*/)[0],
resource: url.substr(url.match(/[^:]*/)[0].length + url.match(/[^\/]*\.[^\/]*/)[0].length + 3)
};
return obj;
}
console.log(parseURL(url));<file_sep>/C#/C# Programming Part II/Methods/SolveTasks/Solver.cs
//Write a program that can solve these tasks:
//Reverses the digits of a number
//Calculates the average of a sequence of integers
//Solves a linear equation a * x + b = 0
//Create appropriate methods.
//Provide a simple text-based menu for the user to choose which task to solve.
//Validate the input data:
//The decimal number should be non-negative
//The sequence should not be empty
//a should not be equal to 0
using System;
class Solver
{
static void Main()
{
Console.WriteLine("SELECT TASK TO SOLVE:");
Console.Write("\u250c");
Console.Write("----------------------------------------");
Console.WriteLine("\u2510");
Console.WriteLine("| 1. Reverse the digits of a number |");
Console.WriteLine("| 2. Calculate Average |");
Console.WriteLine("| 3. Solve linear equation a * x + b = 0 |");
Console.Write("\u2514");
Console.Write("----------------------------------------");
Console.WriteLine("\u2518");
Console.Write("Choice: ");
int input = int.Parse(Console.ReadLine());
switch (input)
{
case 1:
ReverseInput();
break;
case 2:
InputAverage();
break;
case 3:
EquationInput();
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
static void EquationInput()
{
Console.Write("Enter a: ");
int a = int.Parse(Console.ReadLine());
Console.Write("Enter b: ");
int b = int.Parse(Console.ReadLine());
if (a == 0)
{
Console.WriteLine("a must not be equal to Zero!");
}
else
{
Console.WriteLine("Equation result is {0}", CalculateEquation(a, b));
}
}
static double CalculateEquation(int a, int b)
{
return (double)-b / a;
}
static void InputAverage()
{
Console.Write("Enter size of sequence: ");
int size = int.Parse(Console.ReadLine());
if (size <= 0)
{
Console.WriteLine("The sequence must have at leaste 1 or more elements ");
return;
}
int[] sequence = new int[size];
for (int i = 0; i < size; i++)
{
Console.Write("sequence[{0}] = ", i);
sequence[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("The average sequence is: {0}", CalculateAverage(sequence));
}
static double CalculateAverage(int[] sequence)
{
int sum = 0;
for (int i = 0; i < sequence.Length; i++)
{
sum += sequence[i];
}
return (double)sum / sequence.Length;
}
static void ReverseInput()
{
Console.Write("Enter number: ");
string number = Console.ReadLine();
if (decimal.Parse(number) > 0)
{
Console.WriteLine("The reversed number is " + Reverse(number));
}
else
{
Console.WriteLine("The number must be non-negative!");
}
}
static decimal Reverse(string number)
{
char[] toBeReversed = number.ToCharArray();
Array.Reverse(toBeReversed);
string reversed = new string(toBeReversed);
decimal reversedNumber = decimal.Parse(reversed);
return reversedNumber;
}
}
<file_sep>/C#/C# Programming Part II/StringsAndTextProcessing/ForbiddenWords/CensoreWords.cs
//We are given a string containing a list of forbidden words and a text containing some of these words.
//Write a program that replaces the forbidden words with asterisks.
using System;
using System.Text;
class CensoreWords
{
static void Main()
{
Console.Write("Enter the text you want do censore: ");
StringBuilder text = new StringBuilder(Console.ReadLine());
Console.Write("Enter forbidden words: ");
char[] separators = {' ', ','};
string[] forbWords = Console.ReadLine().Split(separators, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < forbWords.Length; i++)
{
text.Replace(forbWords[i], new string('*', forbWords[i].Length));
}
Console.WriteLine(text);
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Conditional statements/Conditional statements/06.Quadratic equation.js
function findRoots(a, b, c) {
var a = document.getElementById('first-coeff').value * 1,
b = document.getElementById('second-coeff').value * 1,
c = document.getElementById('third-coeff').value * 1,
discriminant = b * b - 4 * a * c,
result1,
result2;
if (discriminant < 0) {
document.getElementById('answer6').innerHTML = 'no real roots';
} else if (discriminant === 0) {
result1 = -b / (2 * a);
document.getElementById('answer6').innerHTML = 'x1=x2=' + result1;
} else {
result1 = (-b - Math.sqrt(discriminant)) / (2 * a);
result2 = (-b + Math.sqrt(discriminant)) / (2 * a);
document.getElementById('answer6').innerHTML = 'x1=' + result1 + '; ' + 'x2=' + result2;
}
}<file_sep>/Java Script/JavaScript UI and DOM/HTML Templates/tasks/task-3.js
///<reference path="../node_modules/jquery/dist/jquery.js" />
function solve() {
return function () {
$.fn.listview = function (data) {
var i,
html = $('#' + $(this).attr('data-template')).html(),
template = handlebars.compile(html);
for (i = 0; i < data.length; i += 1) {
$('#' + $(this).attr('id')).append(template(data[i]));
}
return this;
};
};
}
module.exports = solve;<file_sep>/C#/OOP/OOPPrinciplesPart1/SchoolClasses/Student.cs
namespace SchoolClasses
{
using System;
public class Student : People
{
public int ClassNumber { get; set; }
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Functions/Functions/01.English digit.js
function digitToWord(num) {
var result;
switch (num) {
case 0: result = 'zero'; break;
case 1: result = 'one'; break;
case 2: result = 'two'; break;
case 3: result = 'three'; break;
case 4: result = 'four'; break;
case 5: result = 'five'; break;
case 6: result = 'six'; break;
case 7: result = 'seven'; break;
case 8: result = 'eight'; break;
case 9: result = 'nine'; break;
default: result = 'not a digit'; break;
}
return result;
}
function lastDigit() {
var input = +document.getElementById('num').value,
digit = input % 10,
result = digitToWord(digit);
document.getElementById('result1').innerHTML = result;
}<file_sep>/C#/C# Programming Part II/StringsAndTextProcessing/ExtractSentences/FindSentences.cs
//Write a program that extracts from a given text all sentences containing given word.
//Example:
//The word is: in
//The text is: We are living in a yellow submarine. We don't have anything else.
//Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.
//The expected result is: We are living in a yellow submarine. We will move out of it in 5 days.
//Consider that the sentences are separated by . and the words – by non-letter symbols.
using System;
class FindSentences
{
static void Main()
{
Console.Write("Enter text: ");
string inputText = " " + Console.ReadLine();
Console.Write("Enter word: ");
string searchedWord = Console.ReadLine();
int sentenceStart = 1;
int sentenceEnd = 0;
while (sentenceStart < inputText.Length)
{
for (int i = sentenceStart; i < inputText.Length - 2; i++) //Finds current sentence boundaries.
{
if (inputText[i] == '.' && char.IsUpper(inputText[i + 2]))
{
sentenceEnd = i;
break;
}
else if (i == inputText.Length - 3)
{
sentenceEnd = i + 2;
break;
}
}
int subStrLength = sentenceEnd + 1 - sentenceStart;
int searchedWordIndex = inputText.ToUpper().IndexOf(searchedWord.ToUpper(), sentenceStart, subStrLength); //Finds the first instance of the word in the curr. sentence if there's any.
while (searchedWordIndex != -1) //Checks if there are any more instances of the word in the rest of the current sentance.
{
if (searchedWordIndex != -1 && !char.IsLetter(inputText[searchedWordIndex - 1]) && !char.IsLetter(inputText[searchedWordIndex + searchedWord.Length]))
{
Console.Write(inputText.Substring(sentenceStart, subStrLength) + " ");
}
searchedWordIndex = inputText.ToUpper().IndexOf(searchedWord.ToUpper(), searchedWordIndex + 1, subStrLength - (searchedWordIndex + 1 - sentenceStart));
}
sentenceStart = sentenceEnd + 2;
}
Console.WriteLine();
}
}
<file_sep>/C#/C# Programming Part I/PrimitiveDataTypesAndVariables/EmployeeData/EmployeesData.cs
//A marketing company wants to keep record of its employees. Each record would have the following characteristics:
//First name
//Last name
//Age (0...100)
//Gender (m or f)
//Personal ID number (e.g. 8306112507)
//Unique employee number (27560000…27569999)
//Declare the variables needed to keep the information for a single employee using appropriate primitive data types. Use descriptive names. Print the data at the console.
using System;
class EmployeesData
{
static void Main()
{
string firstName = "Pesho";
string lastName = "Peshev";
byte age = 80;
char gender = 'm';
ulong personalId = 8306112507;
uint uniqueNumber = 27569999;
Console.WriteLine("{0}\n{1}\n{2}\n{3}\n{4}\n{5}", firstName, lastName, age, gender, personalId, uniqueNumber);
}
}
<file_sep>/C#/C# Programming Part II/UsingClassesAndObjects/TriangleSurface/TriangleSurfaceCalculator.cs
//Write methods that calculate the surface of a triangle by given:
//Side and an altitude to it;
//Three sides;
//Two sides and an angle between them;
//Use System.Math.
using System;
class TriangleSurfaceCalculator
{
static void Main()
{
Console.WriteLine("Choose how to calculate the surface: ");
Console.WriteLine("1. From a side and height.");
Console.WriteLine("2. From three sides.");
Console.WriteLine("3. From two sides and ana angle between them.");
Console.Write("Choice: ");
int choice = int.Parse(Console.ReadLine());
while (choice != 1 && choice != 2 && choice != 3)
{
Console.Write("Wrong choice, try again: ");
choice = int.Parse(Console.ReadLine());
}
if (choice == 1)
{
Console.Write("Enter the side: ");
double sideA = double.Parse(Console.ReadLine());
Console.Write("Enter the height: ");
double heaightA = double.Parse(Console.ReadLine());
Console.WriteLine(SurfaceFromSideAndHeight(sideA, heaightA));
}
else if (choice == 2)
{
Console.Write("Enter side a: ");
int sideA = int.Parse(Console.ReadLine());
Console.Write("Enter side b: ");
int sideB = int.Parse(Console.ReadLine());
Console.Write("Enter side c: ");
int sideC = int.Parse(Console.ReadLine());
Console.WriteLine(SurfaceFromThreeSides(sideA, sideB, sideC));
}
else if (choice == 3)
{
Console.Write("Enter side a: ");
double sideA = double.Parse(Console.ReadLine());
Console.Write("Enter side b: ");
double sideB = double.Parse(Console.ReadLine());
Console.Write("Enter the angle betweent them: ");
double angle = double.Parse(Console.ReadLine());
Console.WriteLine(SurfaceFromSidesAndAngle(sideA, sideB, angle));
}
}
static double SurfaceFromSideAndHeight(double side, double height)
{
double surface = (side * height) / 2;
return surface;
}
static double SurfaceFromThreeSides(double a, double b, double c)
{
double halfPerimeter = (a + b + c) / 2;
double surface = Math.Sqrt(halfPerimeter * (halfPerimeter - a) * (halfPerimeter - b) * (halfPerimeter - c));
return surface;
}
static double SurfaceFromSidesAndAngle(double a, double b, double angle)
{
double surface = (a * b * Math.Sin(angle)) / 2;
return surface;
}
}
<file_sep>/C#/C# Programming Part II/Methods/ReverseNumber/NumberReverser.cs
//Write a method that reverses the digits of given decimal number.
using System;
class NumberReverser
{
static void Main()
{
Console.Write("Enter a number: ");
char[] inputArray = Console.ReadLine().ToCharArray();
Reverse(inputArray);
Console.WriteLine(inputArray);
}
static void Reverse(char[] toReverse)
{
char temp;
for (int i = 0; i < toReverse.Length / 2; i++)
{
temp = toReverse[toReverse.Length - 1 - i];
toReverse[toReverse.Length - 1 - i] = toReverse[i];
toReverse[i] = temp;
}
}
}
<file_sep>/Java Script/JavaScript UI and DOM/Document Object Model/scripts.js
function colorDivsWithSelectorAll() {
var divs = document.querySelectorAll('div > div');
for (var i = 0, len = divs.length; i < len; i++) {
divs[i].style.borderColor = 'red';
divs[i].style.borderWidth = '1px';
divs[i].style.borderStyle = 'solid';
}
}
function colorDivsWithGetElements() {
var divs = document.getElementsByTagName('div');
for (var i = 0, len = divs.length; i < len; i++) {
if (divs[i].parentElement instanceof HTMLDivElement) {
divs[i].style.borderColor = 'green';
divs[i].style.borderWidth = '1px';
divs[i].style.borderStyle = 'solid';
}
}
}
function printInputValue() {
var i,
len,
val,
parentDiv,
spanElement;
parentDiv = document.getElementById('inputTask2').parentElement;
spanElement = parentDiv.getElementsByTagName('span')[0];
if (spanElement) {
parentDiv.removeChild(spanElement);
}
val = document.getElementById('inputTask2').value;
console.log(val);
document.getElementById('inputTask2').parentElement.innerHTML += '<span>' + val + '</span>';
}
function setBackgroundColor() {
document.body.style.backgroundColor = document.getElementById('inputTask3').value;
}<file_sep>/Java Script/JavaScript Fundmentals/Using Objects/Using Objects/06.People grouping.js
console.log('\nTask 6: Write a function that groups an array of people by age, first or last name. The function must return an associative array, with keys - the groups, and values - arrays with people in this groups');
function group(people, filter) {
var i,
groups = [],
len = people.length;
for (i = 0; i < len; i += 1) {
if (!groups[people[i][filter]]) groups[people[i][filter]] = [];
groups[people[i][filter]].push(people[i]);
}
return groups;
}
var people = [
{ firstname: 'Gosho', lastname: 'Petrov', age: 82 },
{ firstname: 'Bay', lastname: 'Ivan', age: 91 },
{ firstname: 'Pesho', lastname: 'Peshev', age: 50 },
{ firstname: 'Gosho', lastname: 'Peshev', age: 82 },
{ firstname: 'Pesho', lastname: 'Petrov', age: 50 }
];
console.log('var people = [{ firstname: Gosho, lastname: Petrov, age: 82 },{ firstname: Bay, lastname: Ivan, age: 91 },{ firstname: Pesho, lastname: Peshev, age: 50 },{ firstname: Gosho, lastname: Peshev, age: 82 },{ firstname: Pesho, lastname: Petrov, age: 50 }];');
console.log(group(people, 'firstname'));
console.log(group(people, 'age'));
console.log(group(people, 'lastname'));
<file_sep>/C#/C# Programming Part II/Methods/EnglishDigit/DigitAsWord.cs
//Write a method that returns the last digit of given integer as an English word.
using System;
class DigitAsWord
{
static void Main()
{
Console.Write("Enter a number: ");
int userInput = int.Parse(Console.ReadLine());
Console.WriteLine("Last digit is: {0}", GetDigit(userInput));
}
static string GetDigit(int input)
{
int lastDigit = input % 10;
string result = "";
switch (lastDigit)
{
case 0: result= "zero"; break;
case 1: result= "one"; break;
case 2: result= "two"; break;
case 3: result= "three"; break;
case 4: result= "four"; break;
case 5: result= "five"; break;
case 6: result= "six"; break;
case 7: result= "seven"; break;
case 8: result= "eight"; break;
case 9: result= "nine"; break;
}
return result;
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Functions/Functions/03.Occurrences of word.js
function findWord() {
var i,
text = document.getElementById('text').value,
word = document.getElementById('word').value,
textArray = text.split(' '),
len = textArray.length,
result = [];
for (i = 0; i < len; i += 1) {
if (document.getElementById('caseInsensitive').checked) {
word = word.toUpperCase();
textArray[i] = textArray[i].toUpperCase();
}
if (textArray[i] == word) result.push(i);
}
if (result.length == 0) result = 'No matches';
document.getElementById('result3').innerHTML = result;
}<file_sep>/C#/C# Programming Part II/Arrays/CompareArrays/ArrayComparer.cs
//Write a program that reads two integer arrays from the console and compares them element by element.
using System;
class ArrayComparer
{
static void Main()
{
Console.Write("Please enter first row of integers separated by space: ");
string[] firstArray = Console.ReadLine().Split();
Console.Write("Please enter second row of integers separated by space: ");
string[] secondArray = Console.ReadLine().Split();
Console.WriteLine("First Array: | Second Array:");
for (int i = 0; i < Math.Max(firstArray.Length, secondArray.Length); i++)
{
if (firstArray.Length - 1 < i)
{
Console.WriteLine(" No Value |{0,8}", secondArray[i]);
}
else if (secondArray.Length - 1 < i)
{
Console.WriteLine("{0,6} | No Value", firstArray[i]);
}
else
{
Console.Write("{0,6} |{1,8} - ", firstArray[i], secondArray[i]);
if (firstArray[i] == secondArray[i])
{
Console.WriteLine("equal");
}
else
{
Console.WriteLine("different");
}
}
}
}
}
<file_sep>/C#/C# Programming Part I/PrimitiveDataTypesAndVariables/BankAccountData/BankAccount.cs
//A bank account has a holder name (first name, middle name and last name), available amount of money (balance), bank name, IBAN, 3 credit card numbers associated with the account.
//Declare the variables needed to keep the information for a single bank account using the appropriate data types and descriptive names.
using System;
class BankAccount
{
static void Main()
{
string firstName = "Pesho";
string middleName = "Peshev";
string lastName = "Peshistiq";
decimal balance = 9999999.999999M;
string bankName = "Banka PESHOVSKA";
string iban = "BG25 BPES 2551 2364 2164";
ulong creditCard1 = 4536123456984567;
ulong creditCard2 = 9437126981919783;
ulong creditCard3 = 9836123456959737;
Console.WriteLine("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}", firstName, middleName, lastName, balance, bankName, iban, creditCard1, creditCard2, creditCard3);
}
}
<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/PointInsideACircleAndOutsideOfARectangle/PointLocation.cs
//Write an expression that checks for given point (x, y) if it is within the circle K({1, 1}, 1.5)
//and out of the rectangle R(top=1, left=-1, width=6, height=2).
using System;
class PointLocation
{
static void Main()
{
Console.Write("Enter x coordinate: ");
double x = double.Parse(Console.ReadLine());
Console.Write("Enter y coordinate: ");
double y = double.Parse(Console.ReadLine());
bool checkCircle = Math.Sqrt((x - 1) * (x - 1) + (y - 1) * (y - 1)) <= 1.5;
bool checkRectangle = (x >= 0 && x <= 5) && (y >= -1 && y <= 1);
if ((checkCircle == true) && (checkRectangle == false))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}<file_sep>/Java Script/JavaScript Fundmentals/Arrays/Increase array members/07.Binary search.js
var mid,
element = 8,
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
min = 0,
max = arr.length - 1,
result = -1;
console.log('\nTask 7: Write a script that finds the index of given element in a sorted array of integers by using the binary search algorithm.');
while (min <= max) {
mid = Math.floor(min + (max - min) / 2);
if (arr[mid] > element) {
max = mid - 1;
}
else if (arr[mid] < element) {
min = mid + 1;
}
else {
result = mid;
break;
}
}
console.log('Index of element ' + element + ' is ' + result);<file_sep>/C#/C# Programming Part II/StringsAndTextProcessing/SubStringInText/CountSubStrings.cs
//Write a program that finds how many times a sub-string is contained in a given text (perform case insensitive search).
using System;
class CountSubStrings
{
static void Main()
{
Console.Write("Enter some text: ");
string inputText = Console.ReadLine();
Console.Write("Enter a substring to search for: ");
string inputString = Console.ReadLine();
int count = 0;
for (int i = 0; i <= inputText.Length - inputString.Length; i++)
{
string currentSubStr = inputText.Substring(i, inputString.Length);
if (currentSubStr == inputString)
{
count++;
i += inputString.Length - 1; // skips a few pointless iterations
}
}
Console.WriteLine(count);
}
}
<file_sep>/C#/C# Programming Part I/ConsoleInputOutput/FormattingNumbers/NumberFormatting.cs
using System;
class NumberFormatting
{
static void Main()
{
Console.Write("Enter integer a: ");
int a = int.Parse(Console.ReadLine());
string binaryA = Convert.ToString(a, 2).PadLeft(10, '0');
Console.Write("Enter floating-point b: ");
double b = double.Parse(Console.ReadLine());
Console.Write("Enter floating-point c: ");
double c = double.Parse(Console.ReadLine());
Console.WriteLine("{0,-5:X}|{1}|{2,7:0.00}|{3,-7:0.000}|", a, binaryA, b, c);
}
}
<file_sep>/C#/C# Programming Part II/Arrays/MergeSort/MergeSort.cs
//Write a program that sorts an array of integers using the Merge sort algorithm.
using System;
class MergeSort
{
static void Main()
{
Console.Write("Please enter a row of integers separated by space: ");
string[] inputArray = Console.ReadLine().Split();
int[] notSorted = new int[inputArray.Length];
for (int i = 0; i < inputArray.Length; i++)
{
notSorted[i] = int.Parse(inputArray[i]);
}
int[] sortedArray = MergeSortAlgo(notSorted);
foreach (var item in sortedArray)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
static int[] MergeSortAlgo(int[] toSort)
{
if (toSort.Length == 1)
{
return toSort;
}
//Split the array in two
int[] firstHalf = new int[toSort.Length - toSort.Length / 2];
int[] secondHalf = new int[toSort.Length / 2];
for (int i = 0; i < firstHalf.Length; i++)
{
firstHalf[i] = toSort[i];
}
for (int i = toSort.Length - toSort.Length / 2; i < toSort.Length; i++)
{
secondHalf[i - (toSort.Length - toSort.Length / 2)] = toSort[i];
}
int[] sortedFirstHalf = MergeSortAlgo(firstHalf);
int[] sortedSecondHalf = MergeSortAlgo(secondHalf);
int[] result = new int[sortedFirstHalf.Length + sortedSecondHalf.Length];
//Sorts and merges the two halves
bool[] sortedFirstHalfChek = new bool[sortedFirstHalf.Length]; //Checks if the element from the first half has been sorted and merged yet.
bool[] sortedSecondHalfCheck = new bool[sortedSecondHalf.Length]; //Checks if the element from the second half has been sorted and merged yet.
int currElementFirstHalf = 0;
int currElementFirstHalfPosition = 0;
int currElementSecondHalf = 0;
int currElementSecondHalfPosition = 0;
for (int i = 0; i < result.Length; i++) //Fills the resulting array from the two halves.
{
for (int j = 0; j < sortedFirstHalf.Length; j++) //Check what's the current element in the first half that is to be sorted.
{
if (!sortedFirstHalfChek[j])
{
currElementFirstHalf = sortedFirstHalf[j];
currElementFirstHalfPosition = j;
break;
}
}
for (int j = 0; j < sortedSecondHalf.Length; j++) //Check what's the current element in the second half that is to be sorted.
{
if (!sortedSecondHalfCheck[j])
{
currElementSecondHalf = sortedSecondHalf[j];
currElementSecondHalfPosition = j;
break;
}
}
if (currElementFirstHalf <= currElementSecondHalf && !sortedFirstHalfChek[sortedFirstHalfChek.Length - 1]) //Compares the elements from both halves and sets the smaller in result[i]
{
result[i] = currElementFirstHalf;
sortedFirstHalfChek[currElementFirstHalfPosition] = true;
}
else if (currElementFirstHalf > currElementSecondHalf && !sortedSecondHalfCheck[sortedSecondHalfCheck.Length - 1])
{
result[i] = currElementSecondHalf;
sortedSecondHalfCheck[currElementSecondHalfPosition] = true;
}
else if (sortedFirstHalfChek[sortedFirstHalfChek.Length - 1])
{
result[i] = currElementSecondHalf;
sortedSecondHalfCheck[currElementSecondHalfPosition] = true;
}
else
{
result[i] = currElementFirstHalf;
sortedFirstHalfChek[currElementFirstHalfPosition] = true;
}
}
return result;
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart1/AnimalHierarchy/Animal.cs
namespace AnimalHierarchy
{
using System;
public abstract class Animal : ISound
{
private string name;
private int age;
public Animal(string name, GEnder gender, int age)
{
this.Name = name;
this.Gender = gender;
this.Age = age;
}
public Animal(string name, int age)
{
this.Name = name;
this.Age = age;
}
public string Name
{
get { return this.name; }
private set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("Name cannot be null or empty");
}
this.name = value;
}
}
public GEnder Gender { get; protected set; }
public int Age
{
get { return this.age; }
set
{
if (age < 0)
{
throw new ArgumentException("Age cannot be negative");
}
this.age = value;
}
}
public abstract void MakeSound();
}
}
<file_sep>/C#/C# Programming Part II/StringsAndTextProcessing/ConsoleApplication1/AboutStrings.cs
//Describe the strings in C#.
//What is typical for the string data type?
//Describe the most important methods of the String class.
using System;
using System.Text;
class AboutStrings
{
static void Main()
{
string definition = @"Strings are immutable sequences of characters (instances of the System.String Class in .NET Framework)
->Declared by the keyword string in C#
->Can be initialized by string literals
->Use Unicode to support multiple languages and alphabets
->Stored in the dynamic memory (managed heap)
System.String is a reference type
String objects are like arrays of characters (char[])
->Have fixed length (String.Length)
->Elements can be accessed directly by index (the index is in the range [0..Length-1])
Most important string processing members are:
->Length, this[], Compare(str1, str2), IndexOf(str), LastIndexOf(str), Substring(startIndex, length), Replace(oldStr, newStr),
Remove(startIndex, length), ToLower(), ToUpper(), Trim()";
Console.WriteLine(definition);
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Strings/Strings/01.Reverse string.js
console.log('Task 1: Write a JavaScript function that reverses a string and returns it.');
function reverseStr(str) {
return result = str.split('').reverse().join('');
}
console.log('reverseStr("sample")');
console.log('result: ' + reverseStr('sample'));
console.log('reverseStr("another test")');
console.log('result: ' + reverseStr('another test'));<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/ThirdDigitIs7/CheckThirdDigit.cs
//Write an expression that checks for given integer if its third digit from right-to-left is 7.
using System;
class CheckThirdDigit
{
static void Main()
{
Console.Write("Enter your number: ");
int number = int.Parse(Console.ReadLine());
int result = (number / 100) % 10;
Console.WriteLine(result == 7);
}
}
<file_sep>/C#/C# Programming Part I/Loops/MinMaxSumAndAverageOfNNumbers/MinMaxSumAvgOfNums.cs
//Write a program that reads from the console a sequence of n integer numbers and returns the minimal, the maximal number, the sum and the average of all numbers (displayed with 2 digits after the decimal point).
//The input starts by the number n (alone in a line) followed by n lines, each holding an integer number.
//The output is like in the examples below.
using System;
class MinMaxSumAvgOfNums
{
static void Main()
{
Console.Write("Enter how many integers you want: ");
int intCount = int.Parse(Console.ReadLine());
Console.Write("Enter integer: ");
double input = double.Parse(Console.ReadLine()); ;
double min = input;
double max = input;
double sum = input;
double avg;
for (int i = 0; i < intCount - 1; i++)
{
Console.Write("Enter integer: ");
input = double.Parse(Console.ReadLine());
if (input < min)
{
min = input;
}
else if (input > max)
{
max = input;
}
sum += input;
}
avg = sum / intCount;
Console.WriteLine("min = {0}", min);
Console.WriteLine("max = {0}", max);
Console.WriteLine("sum = {0}", sum);
Console.WriteLine("avg = {0}", avg);
}
}
<file_sep>/C#/C# Programming Part I/Loops/DecimalToHexadecimalNumber/DecToHex.cs
//Using loops write a program that converts an integer number to its hexadecimal representation.
//The input is entered as long. The output should be a variable of type string.
//Do not use the built-in .NET functionality.
using System;
class DecToHex
{
static void Main()
{
int input = int.Parse(Console.ReadLine());
string result = string.Empty;
while (input != 0)
{
int reminder = input % 16;
switch (reminder)
{
case 10:
result += 'A';
break;
case 11:
result += 'B';
break;
case 12:
result += 'C';
break;
case 13:
result += 'D';
break;
case 14:
result += 'E';
break;
case 15:
result += 'F';
break;
default:
result += reminder.ToString();
break;
}
input /= 16;
}
char[] charArray = result.ToCharArray();
Array.Reverse(charArray);
Console.WriteLine(new string(charArray));
}
}
<file_sep>/Latest Exams/ExamDSA/ExamDSA/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExamDSA
{
class Program
{
static void MockInput()
{
var input = @"add TheMightyThor God 100
add Artanis Protoss 250
add Fenix Protoss 200
add Spiderman MutatedHuman 180
add XelNaga God 500
add Wolverine MutatedHuman 200
add Zeratul Protoss 300
add Spiderman MutatedHuman 180
power 3
find Protoss
find God
remove Kerrigan
remove XelNaga
power 3
find Kerrigan
find God
end
";
Console.SetIn(new StringReader(input));
}
static void Main()
{
MockInput();
var units = new Dictionary<string, Unit>();
var unitsByAttack = new SortedSet<Unit>();
var input = Console.ReadLine();
var finalResult = new StringBuilder();
while (input != "end")
{
var currentLine = input.Split();
if (currentLine[0] == "add")
{
try
{
var newUnit = new Unit
{
Name = currentLine[1],
Type = currentLine[2],
Attack = int.Parse(currentLine[3])
};
units.Add(currentLine[1], newUnit);
unitsByAttack.Add(newUnit);
finalResult.AppendLine(string.Format("SUCCESS: {0} added!", currentLine[1]));
}
catch (Exception)
{
finalResult.AppendLine(string.Format("FAIL: {0} already exists!", currentLine[1]));
}
}
else if (currentLine[0] == "remove")
{
try
{
var unit = units[currentLine[1]];
unitsByAttack.Remove(unit);
units.Remove(currentLine[1]);
finalResult.AppendLine(string.Format("SUCCESS: {0} removed!", currentLine[1]));
}
catch (Exception)
{
finalResult.AppendLine(string.Format("FAIL: {0} could not be found!", currentLine[1]));
}
}
else if (currentLine[0] == "find")
{
var result = new StringBuilder("RESULT: ");
var resultingUnits = unitsByAttack
.Where(u => u.Type == currentLine[1])
.Take(10);
foreach (var unit in resultingUnits)
{
result.Append(string.Format("{0}[{1}]({2}), ", unit.Name, unit.Type, unit.Attack));
}
if (result.Length > 8)
{
result.Remove(result.Length - 2, 2);
}
finalResult.AppendLine(result.ToString());
}
else if (currentLine[0] == "power")
{
var result = new StringBuilder("RESULT: ");
var resultingUnits = unitsByAttack.Take(int.Parse(currentLine[1]));
foreach (var unit in resultingUnits)
{
result.Append(string.Format("{0}[{1}]({2}), ", unit.Name, unit.Type, unit.Attack));
}
if (result.Length > 8)
{
result.Remove(result.Length - 2, 2);
}
finalResult.AppendLine(result.ToString());
}
input = Console.ReadLine();
}
Console.Write(finalResult);
}
}
public class Unit : IComparable<Unit>
{
public string Name { get; set; }
public string Type { get; set; }
public int Attack { get; set; }
public int CompareTo(Unit other)
{
if (this.Attack.CompareTo(other.Attack) == 0)
{
return this.Name.CompareTo(other.Name);
}
return this.Attack.CompareTo(other.Attack) * -1;
}
}
}<file_sep>/C#/C# Programming Part I/OperatorsAndExpressions/ModifyABitAtGivenPosition/ModifyaABit.cs
//We are given an integer number n, a bit value v (v=0 or 1) and a position p.
//Write a sequence of operators (a few lines of C# code) that modifies n to hold
//the value v at the position p from the binary representation of n while preserving all other bits in n.
using System;
class ModifyaABit
{
static void Main()
{
Console.Write("Enter number: ");
int number = int.Parse(Console.ReadLine());
Console.Write("Enter position: ");
int position = int.Parse(Console.ReadLine());
Console.Write("Enter value: ");
int value = int.Parse(Console.ReadLine());
int setBit = 1 << position;
if (value == 0)
{
Console.WriteLine(number & ~setBit);
}
else
{
Console.WriteLine(number | setBit);
}
}
}
<file_sep>/C#/OOP/DefiningClassesPartTwo/Structure/Path.cs
namespace Structure
{
using System;
using System.Collections.Generic;
public class Path
{
private List<Point3D> points;
public Path()
{
this.points = new List<Point3D>();
}
public List<Point3D> Points
{
get { return this.points; }
set { this.points = value; }
}
public void AddPoint(Point3D point)
{
points.Add(point);
}
public void AddPoints(params Point3D[] point)
{
points.AddRange(point);
}
public override string ToString()
{
return string.Join(" ", points);
}
}
}
<file_sep>/C#/C# Programming Part I/ConsoleInputOutput/SumOf5Numbers/SumOfNumbers.cs
//Write a program that enters 5 numbers (given in a single line, separated by a space), calculates and prints their sum.
using System;
class SumOfNumbers
{
static void Main()
{
Console.Write("Enter five numbers in a row: ");
string input = Console.ReadLine();
string[] numbers = input.Split();
double sum = 0;
for (int i = 0; i < 5; i++)
{
sum += double.Parse(numbers[i]);
}
Console.WriteLine(sum);
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart2/BankAccounts/Customers/Individual.cs
namespace BankAccounts.Customers
{
public class Individual : Customer
{
public float Age { get; set; }
public string Occupation { get; set; }
public decimal Salary { get; set; }
public Individual(string name, string address)
{
this.Name = name;
this.Address = address;
}
}
}
<file_sep>/Latest Exams/ExamDSA/Passwords/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Passwords
{
class Program
{
static int passLength;
static string keyPresses;
static int k;
static int count;
static int[] pass;
static int smaller;
static int bigger;
static int level;
static void MockInput()
{
var input = @"7
<=>>=<
23";
Console.SetIn(new StringReader(input));
}
static void Main()
{
MockInput();
passLength = int.Parse(Console.ReadLine());
keyPresses = Console.ReadLine();
k = int.Parse(Console.ReadLine());
count = 0;
pass = new int[passLength];
smaller = 0;
bigger = 0;
level = 0;
Magic(0);
GetPass(0, 0, 0);
}
public static void Magic(int index)
{
if (index >= keyPresses.Length)
{
return;
}
if (keyPresses[index] == '<')
{
//if (level == 0)
//{
// smaller++;
//}
//else
if (level > 0)
{
smaller++;
level++;
}
else
{
bigger--;
level++;
}
}
if (keyPresses[index] == '>')
{
//if (level == 0)
//{
// bigger++;
//}
//else
if (level > 0)
{
smaller++;
level--;
}
else
{
bigger++;
level--;
}
}
Magic(index + 1);
}
public static void GetPass(int index, int min, int max)
{
if (count >= k)
{
return;
}
if (index >= pass.Length)
{
count++;
if (k == count)
{
Console.WriteLine(string.Join("", pass));
}
return;
}
for (int i = min; i <= max; i++)
{
if (i == 10)
{
pass[index] = 0;
}
else
{
pass[index] = i;
}
var nextDir = keyPresses[index + 1];
var nextMin = min;
var nextMax = max;
if (nextDir == '>')
{
nextMax++;
}
else if (nextDir == '<')
{
nextMax--;
}
GetPass(index + 1, nextMin, nextMax);
}
}
}
}
<file_sep>/C#/C# Programming Part II/MultidimensionalArrays/D.FillTheMatrix/MatrixFiller.cs
using System;
class MatrixFiller
{
static void Main()
{
Console.Write("Enter N: ");
int n = int.Parse(Console.ReadLine());
int[,] matrix = new int[n, n];
int height = matrix.GetLength(0);
int currentCol = 0;
int revCurrentCol = n - 1;
int currentRow = 0;
int revCurrentRow = n - 1;
int counter = 1;
bool keepWorking = true;
while (keepWorking) //Fills the matrix by sequencing each direction until its filled.
{
for (int row = currentRow; row < height; row++)
{
matrix[row, currentCol] = counter;
counter++;
}
currentCol++;
for (int col = currentCol; col < height; col++)
{
matrix[revCurrentRow, col] = counter;
counter++;
}
revCurrentRow--;
for (int row = height - 2; row >= currentRow; row--)
{
matrix[row, revCurrentCol] = counter;
counter++;
}
revCurrentCol--;
for (int col = height - 2; col > currentRow; col--)
{
matrix[currentRow, col] = counter;
counter++;
}
currentRow++;
height--;
if (currentRow > height)
{
keepWorking = false;
}
}
for (int row = 0; row < matrix.GetLength(0); row++) //Prints the matrix
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
Console.Write("{0,4}", matrix[row, col]);
}
Console.WriteLine();
}
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Strings/Strings/06.Extract text from HTML.js
console.log('\nTask 6: Write a function that extracts the content of a html page given as text. The function should return anything that is in a tag, without the tags.');
var html = '<html><head><title>Sample site</title></head><body><div>text<div>more text</div>and more...</div>in body</body></html>';
function getContent(input) {
return input.replace(/<[^>]*>/g, '');
}
console.log(html);
console.log(getContent(html));<file_sep>/Java Script/JavaScript Fundmentals/Arrays/Increase array members/06.Most frequent number.js
var i,
j,
mostFrequent,
currentMax = 1,
max = currentMax,
arr = [4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3],
len = arr.length;
console.log('\nTask 6: Write a script that finds the most frequent number in an array.');
for (i = 0; i < len; i += 1) {
if (arr[i] !== false) {
for (j = i + 1; j < len; j += 1) {
if (arr[i] === arr[j]) {
currentMax += 1;
if (currentMax > max) {
max = currentMax;
mostFrequent = arr[i];
}
arr[j] = false;
}
}
}
currentMax = 1;
}
console.log('result: ' + mostFrequent + ' (' + max + ' times)');<file_sep>/C#/C# Programming Part I/PrimitiveDataTypesAndVariables/ComparingFloats/FloatComparison.cs
//Write a program that safely compares floating-point numbers (double) with precision eps = 0.000001.
using System;
class FloatComparison
{
static void Main()
{
Console.Write("Enter first fraction: ");
double numberA = double.Parse(Console.ReadLine());
Console.Write("Enter second fraction: ");
double numberB = double.Parse(Console.ReadLine());
bool result = Math.Abs(numberA - numberB) < 0.000001 ? true : false;
Console.WriteLine(result);
}
}
<file_sep>/Java Script/JavaScript Fundmentals/Array Methods/Array Methods/05.Youngest person.js
console.log('\nTask 5: Write a function that finds the youngest male person in a given array of people and prints his full name. Use only array methods and no regular loops (for, while). Use Array#find');
var arr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
fnames = ['Joy', 'Nicky', 'Aleks', 'Grui', 'Jay', 'Zoy', 'Nelli', 'Pol', 'Gol', 'Sol'],
lnames = ['Peterson', 'Johnson', 'Bolton', 'Clapton', 'Pikachu', 'Winfrey', 'Spencer', 'Cloppenburg', 'Heisenburg', 'West'];
var people = arr.map(function (_, i) {
return { fname: fnames[i], lname: lnames[i], age: Math.random() * 100 | 0, gender: !(Math.round(Math.random())) };
});
console.log(people);
if (!Array.prototype.find) {
Array.prototype.find = function (callback) {
var i,
len;
for (i = 0, len = this.length; i < len; i += 1) {
if (callback(this[i], i, this)) return this[i];
}
}
}
var result = people.sort(function (person1, person2) {
return person1.age - person2.age;
}).find(function (person) {
return !person.gender;
});
console.log(result.fname + ' ' + result.lname);<file_sep>/C#/C# Programming Part II/Arrays/FrequentNumber/FindMostFrequent.cs
//Write a program that finds the most frequent number in an array.
using System;
class FindMostFrequent
{
static void Main()
{
Console.Write("Please enter a row of integers separated by space: ");
string[] inputArray = Console.ReadLine().Split();
int[] intArray = new int[inputArray.Length];
for (int i = 0; i < inputArray.Length; i++)
{
intArray[i] = int.Parse(inputArray[i]);
}
bool[] doubleCountCheck = new bool[intArray.Length];
int count = 1;
int freqNumber = intArray[0];
for (int i = 0; i < intArray.Length; i++)
{
if (doubleCountCheck[i])
{
continue;
}
else
{
int currCount = 1;
for (int j = i + 1; j < intArray.Length; j++)
{
if (intArray[j] == intArray[i])
{
currCount++;
doubleCountCheck[j] = true;
}
}
if (currCount > count)
{
count = currCount;
freqNumber = intArray[i];
}
}
}
Console.WriteLine("{0} ({1} times)", freqNumber, count);
}
}
<file_sep>/C#/C# Programming Part II/MultidimensionalArrays/C.FillTheMatrix/MatrixFiller.cs
using System;
class MatrixFiller
{
static void Main()
{
Console.Write("Enter N: ");
int n = int.Parse(Console.ReadLine());
int[,] matrix = new int[n, n];
for (int row = 0; row < matrix.GetLength(0); row++) //Fills the matrix by counting the number of elements
{ //before the current element.
for (int col = 0; col < matrix.GetLength(1); col++)
{
int counter = 0;
int addition = col + 1;
for (int i = row; i < matrix.GetLength(0) - 1; i++)
{
counter += addition;
addition++;
if (addition > matrix.GetLength(1))
{
addition--;
}
}
addition = col + 1;
for (int i = row; i >= 0; i--)
{
counter += addition;
addition--;
if (addition == 0)
{
break;
}
}
matrix[row, col] = counter;
}
}
for (int row = 0; row < matrix.GetLength(0); row++) //Prints the matrix
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
Console.Write("{0,3}", matrix[row, col]);
}
Console.WriteLine();
}
}
}
<file_sep>/C#/C# Programming Part II/Arrays/IndexOfLetters/PrintIndexOfLetter.cs
//Write a program that creates an array containing all letters from the alphabet (A-Z).
//Read a word from the console and print the index of each of its letters in the array.
using System;
class PrintIndexOfLetter
{
static void Main()
{
char[] alphabet = new char[26];
for (int i = 0; i < alphabet.Length; i++)
{
alphabet[i] = (char)((int)'A' + i);
}
Console.Write("Please enter a word with capital letters: ");
char[] inputArray = Console.ReadLine().ToCharArray();
for (int i = 0; i < inputArray.Length; i++)
{
bool indexFound = false;
int index = 0;
int devisor = 2;
int subsetMiddle = alphabet.Length / 2;
while (!indexFound)
{
if (alphabet[subsetMiddle] == inputArray[i])
{
indexFound = true;
index = subsetMiddle;
}
else if (alphabet[subsetMiddle] > inputArray[i])
{
if (devisor > alphabet.Length)
{
subsetMiddle -= 1;
}
else
{
devisor *= 2;
subsetMiddle -= alphabet.Length / devisor;
}
}
else
{
if (devisor > alphabet.Length)
{
subsetMiddle += 1;
}
else
{
devisor *= 2;
subsetMiddle += alphabet.Length / devisor;
}
}
}
Console.WriteLine(index);
}
}
}
<file_sep>/C#/OOP/OOPPrinciplesPart2/BankAccounts/Customers/Company.cs
namespace BankAccounts.Customers
{
class Company : Customer
{
public string industrySector { get; set; }
public bool sisterCompany { get; set; }
public Company(string name, string address)
{
this.Name = name;
this.Address = address;
}
}
}
| 8a510c6e01dc4827073f86049535d4a9d680c061 | [
"JavaScript",
"C#",
"HTML"
] | 168 | C# | mdraganov/Telerik-Academy | 68cd42e1e9bc96a61d17e9b797cb3bdc61405946 | f437815037e8f9cc2727a4dd4321ff69554588b3 |
refs/heads/master | <repo_name>DanielWFrancis/admincode-co<file_sep>/driver.py
"""
driver.py: Driver for generic corpus
This modules has two members for interacting with this corpus:
* `INDEX` is a tuple containing a name for each level of the corpus index
* `stream()` returns an iterator of 2-tuples representing each item in the
corpus. The first element of this tuple is the index value for the item,
represented as a tuple corresponding to the name(s) in INDEX. The second
element is the text of the item itself.
To use this driver, add the directory containing it to sys.path and import it
as you would any other module.
This generic corpus simply reads in the files from a directory located in
`.\data\clean` relative to the location of the driver. The filepaths are used
as the index.
"""
import concurrent.futures
import logging
from pathlib import Path
INDEX = ('date','version','agency','title')
_DATA_DIR = Path(__file__).parent.resolve().joinpath('data', 'clean')
_ENCODING = 'ISO-8859-1'
log = logging.getLogger(Path(__file__).stem)
def _read_text(path):
log.info("Reading {}".format(path))
if path.stem != ".DS_Store":
agency = path.stem.split('__')[0].split('_')[-1:]
title, version, date = path.stem.split('__')
return ((date, version, agency, title), path.read_text(encoding=_ENCODING))
def _generate_paths(basedir):
for sub in basedir.iterdir():
try:
yield from _generate_paths(sub)
except NotADirectoryError:
yield sub
def stream():
# Using a ThreadPoolExecutor for concurrency because IO releases the GIL.
with concurrent.futures.ThreadPoolExecutor() as pool:
# Use lazy iteration so we don't unnecessarily fill up memory
workers = []
for i in _generate_paths(_DATA_DIR):
if i.stem != ".DS_Store":
workers.append(pool.submit(_read_text, i))
if len(workers) == pool._max_workers:
yield workers.pop(0).result()
yield from (i.result() for i in workers)
#print("done!")
<file_sep>/scripts/count_words.py
#!/usr/bin/env python
"""
count_words.py: count the number of words for each item in a corpus
"""
import argparse
import csv
import io
import logging
import re
import sys
from pathlib import Path
ENCODE_IN = 'utf-8'
ENCODE_OUT = 'utf-8'
WORD_REGEX = re.compile(r'\b\w+\b')
log = logging.getLogger(Path(__file__).stem)
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('driver', type=Path)
parser.add_argument('-o', '--outfile',
type=lambda x: open(
x, 'w', encoding=ENCODE_OUT, newline=''),
default=io.TextIOWrapper(
sys.stdout.buffer, encoding=ENCODE_OUT)
)
verbosity = parser.add_mutually_exclusive_group()
verbosity.add_argument('-v', '--verbose', action='store_const',
const=logging.DEBUG, default=logging.INFO)
verbosity.add_argument('-q', '--quiet', dest='verbose',
action='store_const', const=logging.WARNING)
return parser.parse_args()
def load_index_and_stream(driver):
sys.path.append(str(driver.parent))
import driver
return driver.INDEX, driver.stream()
def main():
args = parse_args()
logging.basicConfig(level=args.verbose)
index_names, stream = load_index_and_stream(args.driver)
writer = csv.writer(args.outfile)
writer.writerow(index_names + ('wordcount',))
for docind, text in stream:
writer.writerow(docind + (len(WORD_REGEX.findall(text)),))
if __name__ == "__main__":
main()
<file_sep>/scripts/count_restrictions.py
#!/usr/bin/env python
"""
count_restrictions.py: count the number of restriction words for each item in a
corpus
"""
import argparse
import io
import csv
import logging
import sys
import count_matches
from pathlib import Path
ENCODE_OUT = 'utf-8'
RESTRICTIONS = ('shall', 'must', 'may not', 'required', 'prohibited')
log = logging.getLogger(Path(__file__).stem)
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('driver', type=Path)
parser.add_argument('-o', '--outfile',
type=lambda x: open(
x, 'w', encoding=ENCODE_OUT, newline=''),
default=io.TextIOWrapper(
sys.stdout.buffer, encoding=ENCODE_OUT)
)
verbosity = parser.add_mutually_exclusive_group()
verbosity.add_argument('-v', '--verbose', action='store_const',
const=logging.DEBUG, default=logging.INFO)
verbosity.add_argument('-q', '--quiet', dest='verbose',
action='store_const', const=logging.WARNING)
return parser.parse_args()
def load_index_and_stream(driver):
sys.path.append(str(driver.parent))
import driver
return driver.INDEX, driver.stream()
def main():
args = parse_args()
logging.basicConfig(level=args.verbose)
index_names, stream = load_index_and_stream(args.driver)
regex = count_matches.get_regex(RESTRICTIONS, lowercase=True)
writer = csv.writer(args.outfile)
writer.writerow(index_names + RESTRICTIONS + ('restrictions',))
for docind, text in stream:
counter = count_matches.count_matches(regex, text, lowercase=True)
writer.writerow(
docind + tuple(counter[i] for i in RESTRICTIONS) +
(sum(counter.values()),)
)
if __name__ == "__main__":
main()
<file_sep>/scripts/download.py
import requests
import bs4
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO)
STARTURL = "https://www.sos.state.co.us/CCR/NumericalDeptList.do"
DIRECTORY = "https://www.sos.state.co.us"
false_links = []
def get_soup(url):
r = requests.get(url)
soup = bs4.BeautifulSoup(r.text, "lxml")
r.close()
return soup
def download_all_divisions(url):
soup = get_soup(url)
div_links = [DIRECTORY + x["href"].replace(" ", "%20") for x in soup.find_all('a')
if (x.find_parent('tr', class_="rowEven") or x.find_parent('tr', class_="rowOdd")) and len(x.get_text())>4]
if url == STARTURL:
for link in div_links:
download_all_divisions(link)
else:
for link in div_links:
download_rule_pdf(link)
def download_rule_pdf(url):
soup = get_soup(url)
#A javascript produces the links displayed on the page by concatenating the section's file_name
#and ID, both of which are available in the page's HTML
for x in soup.find_all('a', href="javascript:void(0)"):
#print(str(x.parent['style']))
if x.parent['style'] == "text-align: center;":
if x:
rule_tag = x
version_id = rule_tag["onclick"].split("'")[1]
file_name = rule_tag["onclick"].split("'")[3]
date_effect = x.text.replace("/", "-")
record_name = file_name.replace(" ", "_") + "__" + version_id + "__" + date_effect
link = DIRECTORY + "/CCR/GenerateRulePdf.do?ruleVersionId=" + version_id + "&fileName=" + file_name.replace(" ", "%20")
else:
false_links.append(url)
return
folder = "data/raw/Agency_" + file_name.split(" ")[2].split("-")[0]
if not Path(folder).exists():
Path(folder).mkdir(parents=True)
outpath = Path(folder + "/" + record_name + ".pdf")
if not Path(outpath).exists():
logging.info("Downloading {}".format(record_name))
r = requests.get(link)
with outpath.open('wb') as outf:
outf.write(r.content)
r.close()
return
download_all_divisions(STARTURL)
<file_sep>/scripts/count_matches.py
#!/usr/bin/env python
"""
count_words.py
A library containing functions for counting occurrence of words or phrases in
text. Linebreaks and extra spaces are always ignored.
Can also be used as a script to count matches in stdin or a file
"""
import argparse
import collections
import csv
import io
import logging
import re
import sys
from pathlib import Path
ENCODE_IN = 'utf-8'
ENCODE_OUT = 'utf-8'
log = logging.getLogger(Path(__file__).stem)
def get_regex(terms, lowercase=False, flags=0):
"""
Return as few compiled regular expressions as possible to locate all
desired terms.
For each match, the matched term will be in a matchgroup named 'match'.
Arguments:
* terms: list of terms to compile
* lowercase: if True, lowercase search terms before compiling (much faster
than using the ignorecase flag, but be sure to lowercase text as well)
* flags: flags to pass to compiler
"""
if lowercase:
terms = [i.casefold() for i in terms]
terms = [' '.join(i.split()) for i in terms]
return re.compile(
r'\b(?P<match>{})\b'.format('|'.join(sorted(terms, reverse=True))),
flags)
def count_matches(regex, text, lowercase=False):
if lowercase:
text = text.casefold()
text = ' '.join(text.split())
counter = collections.Counter(
i.groupdict()['match'] for i in regex.finditer(text)
)
return counter
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('terms', nargs='+')
parser.add_argument('-i', '--infile',
type=lambda x: open(x, encoding=ENCODE_IN),
default=io.TextIOWrapper(
sys.stdin.buffer, encoding=ENCODE_IN)
)
parser.add_argument('-o', '--outfile',
type=lambda x: open(x, 'w', encoding=ENCODE_OUT),
default=io.TextIOWrapper(
sys.stdout.buffer, encoding=ENCODE_OUT)
)
parser.add_argument('--ignorecase', action='store_true', default=False)
verbosity = parser.add_mutually_exclusive_group()
verbosity.add_argument('-v', '--verbose', action='store_const',
const=logging.DEBUG, default=logging.INFO)
verbosity.add_argument('-q', '--quiet', dest='verbose',
action='store_const', const=logging.WARNING)
return parser.parse_args()
def main():
args = parse_args()
logging.basicConfig(level=args.verbose)
regex = get_regex(args.terms, lowercase=args.ignorecase)
counts = count_matches(regex, args.infile.read(),
lowercase=args.ignorecase)
writer = csv.writer(args.outfile)
writer.writerows(counts.items())
if __name__ == "__main__":
main()
<file_sep>/makefile
# prep: data/clean data/metadata.csv driver.py
VERBOSE_FLAG=-v # Set to empty for less info or to -q for quiet
# Canned recipe for targets that only need to have their timestamps updated
# when their dependencies change, such as a library dependency for a script
define lib
touch $@
endef
# Canned recipe for running python scripts. The script should be the first
# dependency, and the other dependencies should be positional arguments in
# order. The script should allow you to specify the output file with a -o flag,
# and to specify verbosity with a -v flag. If you're using a Python script that
# doesn't follow this pattern, you can of course write the recipe directly.
# Additional explicit arguments can be added after the canned recipe if needed.
define py
python $^ -o $@ $(VERBOSE_FLAG)
endef
METADATA = data/wordcount.csv data/restrictions.csv
.PHONY: data/clean data/raw
data/metadata.csv: scripts/combine_datasets.py $(METADATA)
$(py)
data/wordcount.csv: scripts/count_words.py driver.py
$(py)
data/restrictions.csv: scripts/count_restrictions.py driver.py
$(py)
scripts/count_restrictions.py: scripts/count_matches.py
$(lib)
driver.py: data/clean
$(lib)
data/clean: scripts/clean.py data/raw
python $^ $@
data/raw: scripts/download.py
python $^ $@
#
# #legislative_code/clean: scripts/download_legislative_code.py
# # python $^ $@
# constitution/clean: scripts/download_constitution.py
# python $^ $@
<file_sep>/scripts/extract_text.py
import bs4
import subprocess
import sys
PDF_CMD = 'pdftotext -enc UTF-8 {filepath} -'
RTF_CMD = 'unrtf {filepath}'
DOC_CMD = 'antiword {filepath}'
PANDOC = 'pandoc -t plain {filepath}'
def _extract_bytes(filepath, cmd):
return subprocess.check_output(
[i.format(filepath=filepath) for i in cmd.split()],
stderr=subprocess.DEVNULL)
def _extract_utf(filepath, cmd):
return _extract_bytes(filepath, cmd).decode('utf-8', errors="ignore")
def _extract_sysenc(filepath, cmd):
return _extract_bytes(filepath, cmd).decode(sys.stdin.encoding)
def _pandoc(filepath):
return _extract_utf(filepath, PANDOC)
def extract_pdf(filepath):
return _extract_utf(filepath, PDF_CMD)
def extract_rtf(filepath):
return _extract_sysenc(filepath, RTF_CMD)
def extract_doc(filepath):
return _extract_sysenc(filepath, DOC_CMD)
def extract_docx(filepath):
return _pandoc(filepath)
def extract_html(filepath):
with filepath.open('rb') as inf:
soup = bs4.BeautifulSoup(inf.read())
return soup.get_text()
def extract_text_from_file(filepath):
return {'.pdf': extract_pdf,
'.rtf': extract_rtf,
'.doc': extract_doc,
'.html': extract_html,
}.get(filepath.suffix.lower(), _pandoc)(filepath)
<file_sep>/README.md
# Corpus
*Official QuantGov Corpora*
This repository is for those who would like to create new datasets using the QuantGov platform. If you would like to find data that has been produced using the QuantGov platform, please visit http://www.quantgov.org/data.
This repository contains all official QuantGov corpora, with each corpus stored in its own branch. The `master` branch of this repository is the Generic Corpus, which serves all files in the data/clean folder, with the file path as the index. Scripts for wordcount and regulatory restriction count are included, however, only the wordcount is included in the data/metadata.csv by default. See the `makefile` for more details.
For more information about QuantGov see http://www.quantgov.org. Technical documentation for the QuantGov platform is provided at http://docs.quantgov.org.
<file_sep>/scripts/clean.py
import logging
import subprocess
import extract_text
from pathlib import Path
def convert_to_text(indir):
for i in indir.iterdir():
if i.is_dir():
convert_to_text(i)
elif i.name == ".DS_Store":
pass
else:
new_parts = i.parts[2:len(i.parts)-1]
new_path = Path("data/clean/" + "/".join(new_parts))
outfile = new_path.joinpath(i.stem + ".txt")
if not new_path.exists():
new_path.mkdir(parents=True)
if not Path(outfile).exists():
try:
# print("Looking at " + str(new_path))
# print(i)
text = extract_text.extract_text_from_file(i)
except subprocess.CalledProcessError:
logging.error('Problem extracting file: {}'.format(i))
continue
with outfile.open('w', encoding='utf-8') as outf:
outf.write(text)
convert_to_text(Path("data/raw"))
<file_sep>/scripts/download_constitution.py
import requests
import bs4
from pathlib import Path
import roman
START_STRING = "Recognizances, bonds, payable to people continue."
STOP_STRING = "Office of Legislative Legal Services, State Capitol Building, 200 E"
STARTURL = "http://tornado.state.co.us/gov_dir/leg_dir/olls/constitution.htm"
def download_all_articles(url):
r = requests.get(url)
soup = bs4.BeautifulSoup(r.text)
r.close()
text = " ".join(soup.get_text().split(START_STRING)[-1].split(STOP_STRING)[0].split()).strip()
#One irregular capitalization of the term "section" in Article 2 throws off the section delimiter.
text = text.replace("Section of the Constitution shall", "section of the Constitution shall")
preamble = text.split("ARTICLE")[0]
articles = ["ARTICLE " + article.strip() for article in text.split("ARTICLE")[1:]]
download_section("Preamble", "Preamble", preamble)
for article in articles:
article_number = "Article_" + str(roman.fromRoman(article.split(" ")[1].strip(". ")))
if "Section " in article:
download_all_sections(article, article_number)
else:
download_section(article_number, article_number, article)
def download_all_sections(article_text, article_number):
sections = ["Section " + section.strip() for section in article_text.split("Section ")[1:]]
for section in sections:
section_number = "Section " + section.split(" ")[1].strip(". ")
download_section(article_number, section_number, section)
def download_section(article_number, section_number, text):
folder = "constitution/clean/" + article_number
if not Path(folder).exists():
Path(folder).mkdir(parents=True)
outpath = Path(folder + "/" + section_number + ".txt")
if outpath.exists():
return
with outpath.open('w', encoding='utf-8') as outf:
outf.write(text)
download_all_articles(STARTURL)
| 2cf42685e8d5ce4b16dbdf78f83f0c7df02d518b | [
"Markdown",
"Python",
"Makefile"
] | 10 | Python | DanielWFrancis/admincode-co | 07b4ee4c1666719550e4582fb8367cfda15d30f8 | 72c5fab86cdef120d189b3715a3fce70d6e9a9f0 |
refs/heads/main | <repo_name>david-fb/sandra-blog<file_sep>/src/components/Menu/Menu.js
import React from 'react'
import { slide as HamburguerMenu} from 'react-burger-menu'
import {Link} from 'react-router-dom'
import './Menu.css'
export default function Menu(){
return(
<section id="Menu-section" className="Menu-nav__container">
{/* <h1>Menu</h1> */}
<HamburguerMenu right>
{/* <a id="home" className="menu-item" href="/">Home</a>
<a id="about" className="menu-item" href="/soul-blog">Blog</a> */}
<Link id="home" className="menu-item" to="/">Inicio</Link>
<Link id="about" className="menu-item" to="/hablemos-soul">Hablemos de Soul</Link>
<Link id="about" className="menu-item" to="/soul-blog">Soul Sinopsis</Link>
</HamburguerMenu>
</section>
)
}<file_sep>/src/pages/HablemosSoul/HablemosSoul.js
import React from 'react'
import './HablemosSoul.css'
export default function HablemosSoul(){
return(
<div className="NewBlog__container">
<h1>Hablemos de Soul</h1>
<div className="NewBlog__paragraphs">
<p>
Soul es un filme que realmente vale la pena ver, es sencillamente espectacular, es una película que, al ser comparada con Coco, da un mensaje de la paradoja de lo que es la vida, es decir, el Gran Antes y el Gran Después da a entender la puerta hacia nuevas dimensiones, el momento en que se llega a la Tierra (el nacimiento) y el momento en que se parte (la muerte).
</p>
<p>
El desarrollo de esta película esta basado en un gran tema, es una narración de lo que sucede con las almas desde el punto de vista del escritor, despliega todo un escenario que entretiene, pero a la vez deja el mensaje claro con respecto a lo que piensa de la vida y la muerte.
</p>
<p>
Se quiere dar una idea de lo que en realidad es la vida, es decir, en el contexto de la película es lo que pasa mientras se está planeando, hoy en día los seres humanos buscan el propósito de la existencia por el cuál seguir, como es, elegir una carrera con la cual se va a lograr alcanzar la felicidad tan esperada, pero en realidad eso no es la vida como tal y así no se alcanza la verdadera felicidad, por estar tan concentrados en cumplir metas o expectativas, se olvida de valorar lo que es la vida, el tan solo respirar, el caminar, ver el cielo y las maravillas del mundo, el hombre por naturaleza busca demostrar algo, complacer a los demás o encajar en la sociedad, "dejar una huella", cuando en realidad se debe complacer a sí mismo.
</p>
<p>
La animación es verdaderamente brillante, realista y muy creativa. <NAME> y <NAME> en particular hicieron grandes actuaciones de voz en los personajes de <NAME> y 22 respectivamente, es de destacar también la banda sonora de jazz de <NAME>.
</p>
<p>
<NAME> es el personaje principal de Soul. Él es un profesor de música en una escuela de Secundaria, sueña con dedicarse de lleno a la música y algún día tocar en importantes escenarios y 22 recibe su nombre porque fue el alma Número 22 creada.
</p>
<p>
Con la posible excepción de Ratatouille, esta película se siente menos como una película dirigida a niños de todo el panteón de Pixar, ya que trata temas y mensajes que pueden ser demasiado complejos para los niños. La explicación de cómo las nuevas almas adquieren su personalidad es realmente inteligente.
</p>
<p>
Como muchas de las otras películas de Pixar, Soul tiene grandes combinaciones de humor, corazón, drama y encanto. Es ilustrativo los momentos divertidos y emocionales que hace reflexionar esta película.
</p>
</div>
<div className="NewBlog__side">
<div className="NewBlog__side-image">
</div>
</div>
</div>
)
}<file_sep>/src/components/App/App.js
import React from 'react'
import {Route, Switch, HashRouter} from 'react-router-dom'
import Layout from '../Layout/Layout'
import Home from '../../pages/Home/Home'
import SoulBlog from '../../pages/SoulBolg/SoulBlog'
import HablemosSoul from '../../pages/HablemosSoul/HablemosSoul'
function App(){
return(
<HashRouter>
<Layout>
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path='/soul-blog' component={SoulBlog}/>
<Route exact path='/hablemos-soul' component={HablemosSoul}/>
</Switch>
</Layout>
</HashRouter>
)
}
export default App<file_sep>/src/components/Footer/Footer.js
import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { library } from '@fortawesome/fontawesome-svg-core'
import './Footer.css'
export default function Footer(){
library.add(fab)
return(
<React.Fragment>
<div className="Footer__container">
<div className="Footer__social-media">
<a href="https://www.facebook.com/Sandra-Blog-106554748345736/" target="blank"> <FontAwesomeIcon icon={['fab', 'facebook']} /> </a>
<a href="https://instagram.com/sandrablog_u" target="blank"><FontAwesomeIcon icon={['fab', 'instagram']}/></a>
</div>
</div>
</React.Fragment>
)
}<file_sep>/src/pages/Home/Home.js
import React from 'react'
import {Link} from 'react-router-dom'
import './Home.css'
import imgSandra from '../../images/imgSandra.jpg'
import FondoSoul from '../../images/fondoSoul.jpg'
import HablemosSoul from '../../images/hablemos-Soul.png'
export default function Home(){
return(
<div className="Home__container">
<div className="Menu__title">
<h1>SandraBlog</h1><span>.</span>
</div>
<div className="Home-wrapper">
<div className="Home__container__img">
<img src={imgSandra} alt="imagen de sandra animada"/>
</div>
<div className="Home__container__text">
<div className="Home__text__blog-entries">
<h2>Bienvenidos</h2>
<p>
En este espacio compartiré las películas que desde mi punto crítico dejan un mensaje acerca de la vida.
</p>
<p>Échale un vistazo a mis últimas entradas, espero que sea de tu agrado</p>
</div>
<div className="Home__container__text__blog-entries">
<div className="Home__blog-entries">
<Link to="/soul-blog"><img src={FondoSoul} alt="soul resumen preview"/></Link>
</div>
<div className="Home__blog-entries">
<Link to="/hablemos-soul"><img src={HablemosSoul} alt="soul resumen preview"/></Link>
</div>
</div>
</div>
</div>
</div>
)
} | ce5267b8652001888ad03dce76107ffd4ed31b2b | [
"JavaScript"
] | 5 | JavaScript | david-fb/sandra-blog | 33fb32b036c46d393d469244e1a1e466f9976ba4 | cc6c4d0bfd44be53c0a13e5cbefdf87f9709b6b4 |
refs/heads/master | <repo_name>beamiter/CarND-Path-Planning-Project-1<file_sep>/clean.sh
#!/bin/bash
rm -fR build
rm -f path_planning
<file_sep>/src/path_planner.h
#ifndef PATH_PLANNER_H
#define PATH_PLANNER_H
#include "behavior_planner.h"
#include "waypoints.h"
struct PathPlanner {
/** @brief Current route plan. */
Waypoints plan;
/**
* @brief Plan a path for the given behavior.
*/
const Waypoints &operator () (const BehaviorPlanner &behavior);
};
#endif
<file_sep>/src/behavior_planner.h
#ifndef BEHAVIOR_PLANNER_H
#define BEHAVIOR_PLANNER_H
#include "highway_map.h"
#include "obstacles.h"
#include "state.h"
#include "json.hpp"
#include <Eigen/Dense>
#include <functional>
struct BehaviorPlanner {
/**
* @brief A state in the Behavior Planner's state machine.
*/
struct Behavior: std::function<Behavior(BehaviorPlanner&)> {
/** @brief A convenient alias for the base type. */
typedef std::function<Behavior(BehaviorPlanner&)> functor;
/**
* @brief Default constructor.
*/
Behavior():
functor()
{
// Nothing to do.
}
/**
* @brief Wraps a custom function into a Behavior object.
*/
template<class F> Behavior(F f):
functor(f)
{
// Nothing to do.
}
};
/** @brief Currently selected behavior. */
Behavior behavior;
/** @brief Map of the highway on which the navigator will drive. */
HighwayMap highway;
/** @brief Current lane, or departing lane if the car is in the process of changing lanes. */
size_t origin_lane;
/** @brief Current lane, or approaching lane if the car is in the process of changing lanes. */
size_t target_lane;
/** @brief Current car position and speed. */
State state;
/** @brief Surrounding obstacles. */
Obstacles obstacles;
/** @brief Target speed. */
double v;
/** @brief Target route. */
Eigen::VectorXd route;
/**
* @brief Default constructor.
*/
BehaviorPlanner();
/**
* @brief Update the behavior planner with data from the currently planned route and given JSON node.
*/
void update(const Waypoints &plan, const nlohmann::json &json);
};
#endif
<file_sep>/src/state.h
#ifndef STATE_H
#define STATE_H
#include "waypoints.h"
#include "json.hpp"
// Forward declaration.
struct HighwayMap;
struct State {
/** @brief Current position in Cartesian coordinates. */
double x, y;
/** @brief Current orientation in radians. */
double o;
/** @brief Current position in Frenet coordinates. */
double s, d;
/** @brief Current linear speed. */
double v;
/** @brief Current lane. */
size_t lane;
/**
* @brief Default constructor.
*/
State();
/**
* @brief Update this state with data from the given route and JSON node.
*/
void update(const HighwayMap &highway, const Waypoints &route, const nlohmann::json &json);
/**
* @brief Convert the given waypoints to a local frame relative to this state.
*/
void toLocalFrame(Waypoints &waypoints) const;
/**
* @brief Convert the given waypoints to the global frame using this state as reference.
*/
void toGlobalFrame(Waypoints &waypoints) const;
};
#endif
<file_sep>/scripts/plot_highway.py
#!/usr/bin/env python
from matplotlib import pyplot as pp
def plot(path):
points = [tuple(float(s) for s in line.split(' ')[:2]) for line in open(path)]
(x, y) = zip(*points)
pp.plot(x, y, 'b.')
pp.show()
def main():
from sys import argv
plot(argv[1])
if __name__ == '__main__':
main()
<file_sep>/src/lane.h
#ifndef LANE_H
#define LANE_H
#include "state.h"
#include <cstddef>
#include <tuple>
#include <vector>
struct Lane: Waypoints {
double width;
/** Waypoint positions along the road. */
std::vector<double> s;
/** Waypoint orientations along the road. */
std::vector<double> o;
/**
* @brief Default constructor.
*/
Lane();
/**
* @brief Create a new Lane of given width.
*/
Lane(double width);
/**
* @brief Return the index of the lane waypoint closest to the given point.
*/
size_t closestIndex(double x, double y) const;
/**
* @brief Return the index of the lane waypoint closest to the given point.
*/
size_t closestIndex(double s) const;
/**
* @brief Return the index of the lane waypoint closest to the given point, and the square distance to it..
*/
std::tuple<size_t, double> closestIndexD2(double x, double y) const;
/**
* @brief Return the index of the closest waypoint in front of the given pose.
*/
size_t nextIndex(const State &state) const;
/**
* @brief Return a list of sample waypoints from the state's location.
*/
Waypoints sample(const State &state) const;
};
#endif
<file_sep>/README.md
# CarND-Path-Planning-Project
This project implements a _Navigator_ (composed of a _Behavior Planner_ and a _Path Planner_) to create smooth, safe paths for an autonomous car to drive along. It communicates with Udacity's simulator through a WebSocket interface, receiving as input the car state, obstacle data (i.e. data on other vehicles) and current path plan, and sending back a new sequence of waypoints describing the updated path plan. The diagram below summarizes the system architecture:
<img src="https://xperroni.github.io/CarND-Path-Planning-Project/architecture.jpg">
The WebSocket interface is implemented in file [src/main.cpp](src/main.cpp). It encapsulates a [Navigator](src/navigator.h) object, which by its turn encapsulates instances of [BehaviorPlanner](src/behavior_planner.h) and [PathPlanner](src/path_planner.h). `Navigator` and `BehaviorPlanner` together decode the WebSocket inputs to collect the current path plan, composed of a sequence of waypoints in global Cartesian coordinates `(x, y)`; the current car [State](src/state.h), composed of global Cartesian coordinates `(x, y)`, orientation `o`, Frenet coordinates `(s, d)`, speed `v` and current `lane` index; and [Obstacles](src/obstacles.h) data, containing the Cartesian and Frenet coordinates, speeds and lane index of all vehicles on the same side of the road as the car. A [HighwayMap](src/highway_map.h) is used to keep track of all vehicles along the highway. Updated path plans are sent back to the simulator through the WebSocket interface.
Because the Path Planner must react quickly to changing road conditions, the plan covers a period of only 0.3<i>s</i>; each turn the first 0.1<i>s</i> worth of waypoints from the current path plan is kept, and a new plan is constructed from the last kept waypoint onwards. Accordingly, the first step of the planning process is to update `State` and `Obstacles` objects to reflect expected conditions 0.1<i>s</i> into the future. The `BehaviorPlanner` then updates its internal Finite State Machine (FSM) according to predicted readings and its own rules, as illustrated below:
<img src="https://xperroni.github.io/CarND-Path-Planning-Project/behavior_fsm.jpg">
The FSM starts at the `START` state, which determines the initial lane and the switches into the `CRUISING` state. In this state the car moves at the reference speed of 20<i>m/s</i> (close to 44MPH); it also tries to keep the car on the middle lane, from where it can more easily move to avoid slower cars. If it finds a slower car ahead, it initially switches to the `TAILING` state where it will try to pair its speed to them, while watching for an opportunity to change lanes. When this comes the FSM selects a destination lane and switches to `CHANGING_LANES` state, returning to `CRUISING` state once the movement is complete.
Once the current behavior (composed of a reference speed `v` and a polynomial `route` roughly indicating whether to keep or change lanes) is determined, it's dispatched along the current `State` to the `PathPlanner`. It in turn uses the [CppAD interface to Ipopt](https://www.coin-or.org/CppAD/Doc/ipopt_solve.htm) to compute a sequence of waypoints approaching the route at the reference speed, while respecting acceleration limits.
## Dependencies
* cmake >= 3.5
* All OSes: [click here for installation instructions](https://cmake.org/install/)
* make >= 4.1
* Linux: make is installed by default on most Linux distros
* Mac: [install Xcode command line tools to get make](https://developer.apple.com/xcode/features/)
* Windows: [Click here for installation instructions](http://gnuwin32.sourceforge.net/packages/make.htm)
* gcc/g++ >= 5.4
* Linux: gcc / g++ is installed by default on most Linux distros
* Mac: same deal as make - [install Xcode command line tools]((https://developer.apple.com/xcode/features/)
* Windows: recommend using [MinGW](http://www.mingw.org/)
* [uWebSockets](https://github.com/uWebSockets/uWebSockets)
* Run either `install-mac.sh` or `install-ubuntu.sh`.
* If you install from source, checkout to commit `e94b6e1`, i.e.
```
git clone https://github.com/uWebSockets/uWebSockets
cd uWebSockets
git checkout e94b6e1
* [Ipopt](https://projects.coin-or.org/Ipopt)
* Mac: `brew install ipopt --with-openblas`
* Linux
* You will need a version of Ipopt 3.12.1 or higher. The version available through `apt-get` is 3.11.x. If you can get that version to work great but if not there's a script `install_ipopt.sh` that will install Ipopt. You just need to download the source from the Ipopt [releases page](https://www.coin-or.org/download/source/Ipopt/) or the [Github releases](https://github.com/coin-or/Ipopt/releases) page.
* Then call `install_ipopt.sh` with the source directory as the first argument, ex: `bash install_ipopt.sh Ipopt-3.12.1`.
* Windows: TODO. If you can use the Linux subsystem and follow the Linux instructions.
* [CppAD](https://www.coin-or.org/CppAD/)
* Mac: `brew install cppad`
* Linux `sudo apt-get install cppad` or equivalent.
* Windows: TODO. If you can use the Linux subsystem and follow the Linux instructions.
* [Eigen](http://eigen.tuxfamily.org/index.php?title=Main_Page). This is already part of the repo so you shouldn't have to worry about it.
* Simulator. Find the latest version [here](https://github.com/udacity/self-driving-car-sim/releases/tag/T3_v1.2).
## Basic Build Instructions
1. Clone this repo.
2. Make a build directory: `mkdir build && cd build`
3. Compile: `cmake .. && make`
4. Run it: `./path_planning`.
On BASH-enabled environments you may also run the `build.sh` script to build the project and create a symbolic link to the executable in the base project directory.
<file_sep>/build.sh
#!/bin/bash
mkdir -p build/release
cd build/release
cmake ../.. && make
cd -
ln -sf build/release/path_planning path_planning
<file_sep>/build_debug.sh
#!/bin/bash
mkdir -p build/debug
cd build/debug
cmake -DCMAKE_BUILD_TYPE=Debug ../.. && make
cd -
ln -sf build/debug/path_planning path_planning
<file_sep>/src/navigator.cpp
#include "navigator.h"
const Waypoints &Navigator::operator () (const nlohmann::json &json) {
path.plan.update(json);
behavior.update(path.plan, json);
return path(behavior);
}
| 11299278ac049828e906a666dd19a6340b4e91be | [
"Markdown",
"Python",
"C",
"C++",
"Shell"
] | 10 | Shell | beamiter/CarND-Path-Planning-Project-1 | 160ee3b73b11ea7ac69fd38f5ac7ca58d069dbcf | 8a57affd50fafc585e6a88d4609ae770d9cc968c |
refs/heads/master | <repo_name>lakshmi8/FamilyPremierLeague<file_sep>/app/src/main/java/com/lakshmibros/fpl/data/model/Match.java
package com.lakshmibros.fpl.data.model;
public class Match {
private int matchNumber;
private String date;
private String team1;
private String team2;
private String venue;
public Match(int matchNumber, String date, String team1, String team2, String venue) {
this.matchNumber = matchNumber;
this.date = date;
this.team1 = team1;
this.team2 = team2;
this.venue = venue;
}
public int getMatchNumber() {
return matchNumber;
}
public String getDate() {
return date;
}
public String getTeam1() { return team1; }
public String getTeam2() {
return team2;
}
public String getVenue() { return venue; }
}
<file_sep>/app/src/main/java/com/lakshmibros/fpl/utils/DatabaseHandler.java
package com.lakshmibros.fpl.utils;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.lakshmibros.fpl.data.constants.DBConstants;
import com.lakshmibros.fpl.data.model.DailyTeam;
import com.lakshmibros.fpl.data.model.Match;
import com.lakshmibros.fpl.data.model.Player;
import java.util.ArrayList;
public class DatabaseHandler extends SQLiteOpenHelper {
private String TAG = "DatabaseHandler";
public DatabaseHandler(Context context) {
super(context, DBConstants.DATABASE_NAME, null, DBConstants.DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FIXTURES_TABLE = "CREATE TABLE IF NOT EXISTS " + DBConstants.FIXTURES_TABLE_NAME + "("
+ "MATCH_NUM INTEGER PRIMARY KEY,"
+ "DATE TEXT,"
+ "TEAM1 TEXT,"
+ "TEAM2 TEXT,"
+ "VENUE TEXT"
+ ")";
db.execSQL(CREATE_FIXTURES_TABLE);
String CREATE_PLAYERS_TABLE = "CREATE TABLE IF NOT EXISTS " + DBConstants.PLAYERS_TABLE_NAME + "("
+ "NAME TEXT,"
+ "TEAM TEXT,"
+ "ROLE TEXT,"
+ "COUNTRY TEXT,"
+ "IS_UNCAPPED INT"
+ ")";
db.execSQL(CREATE_PLAYERS_TABLE);
String CREATE_DAILY_TEAM_TABLE = "CREATE TABLE IF NOT EXISTS " + DBConstants.DAILY_TEAM_TABLE_NAME + "("
+ "MATCH_NUM INTEGER PRIMARY KEY,"
+ "PLAYER_1 TEXT,"
+ "PLAYER_2 TEXT,"
+ "PLAYER_3 TEXT,"
+ "PLAYER_4 TEXT,"
+ "PLAYER_5 TEXT,"
+ "PLAYER_6 TEXT,"
+ "PLAYER_7 TEXT,"
+ "PLAYER_8 TEXT,"
+ "PLAYER_9 TEXT,"
+ "PLAYER_10 TEXT,"
+ "PLAYER_11 TEXT,"
+ "CAPTAIN TEXT,"
+ "POWER_PLAYER TEXT,"
+ "WINNING_TEAM TEXT,"
+ "FOREIGN KEY (MATCH_NUM) REFERENCES " + DBConstants.FIXTURES_TABLE_NAME + "(MATCH_NUM)"
+ ")";
db.execSQL(CREATE_DAILY_TEAM_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Dropping the relevant tables
db.execSQL("DROP TABLE IF EXISTS " + DBConstants.FIXTURES_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + DBConstants.PLAYERS_TABLE_NAME);
// Creating the tables again
onCreate(db);
}
public void insertMatches(ArrayList<Match> matches) {
if(matches == null) return;
SQLiteDatabase db = this.getWritableDatabase();
for (Match match: matches) {
ContentValues values = new ContentValues();
values.put("MATCH_NUM", match.getMatchNumber());
values.put("DATE", match.getDate());
values.put("TEAM1", match.getTeam1());
values.put("TEAM2", match.getTeam2());
values.put("VENUE", match.getVenue());
db.insert(DBConstants.FIXTURES_TABLE_NAME, null, values);
}
db.close();
}
public void insertPlayers(ArrayList<Player> players) {
if(players == null) return;
SQLiteDatabase db = this.getWritableDatabase();
for (Player player: players) {
ContentValues values = new ContentValues();
values.put("NAME", player.getName());
values.put("TEAM", player.getTeam());
values.put("ROLE", player.getRole());
values.put("COUNTRY", player.getCountry());
values.put("IS_UNCAPPED", player.isUncapped());
db.insert(DBConstants.PLAYERS_TABLE_NAME, null, values);
}
db.close();
}
public void insertDailySelection(DailyTeam ob) {
if(ob == null) return;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("MATCH_NUM", ob.getMatchNumber());
values.put("PLAYER_1", ob.getTeam().get(0));
values.put("PLAYER_2", ob.getTeam().get(1));
values.put("PLAYER_3", ob.getTeam().get(2));
values.put("PLAYER_4", ob.getTeam().get(3));
values.put("PLAYER_5", ob.getTeam().get(4));
values.put("PLAYER_6", ob.getTeam().get(5));
values.put("PLAYER_7", ob.getTeam().get(6));
values.put("PLAYER_8", ob.getTeam().get(7));
values.put("PLAYER_9", ob.getTeam().get(8));
values.put("PLAYER_10", ob.getTeam().get(9));
values.put("PLAYER_11", ob.getTeam().get(10));
values.put("CAPTAIN", ob.getCaptain());
values.put("POWER_PLAYER", ob.getPowerPlayer());
values.put("WINNING_TEAM", ob.getWinningTeam());
db.insert(DBConstants.DAILY_TEAM_TABLE_NAME, null, values);
db.close();
}
public ArrayList<Match> getMatchForCurrentDate(String currentDate) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Match> matches = new ArrayList<>();
String selectQuery = "SELECT * FROM " + DBConstants.FIXTURES_TABLE_NAME + " where DATE = '" + currentDate + "'";
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor != null) {
try {
while (cursor.moveToNext()) {
int matchNum = Integer.parseInt(cursor.getString(0));
String date = cursor.getString(1);
String team1 = cursor.getString(2);
String team2 = cursor.getString(3);
String venue = cursor.getString(4);
Match match = new Match(matchNum, date, team1, team2, venue);
matches.add(match);
}
} catch (Exception e) {
Log.e(TAG, "Exception while reading the cursor");
} finally {
try {
cursor.close();
db.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing the cursor/db");
}
}
}
return matches;
}
public ArrayList<Player> getPlayersForCurrentDate(String team1, String team2, String playerRole) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Player> players = new ArrayList<>();
String selectQuery =
"SELECT * FROM " + DBConstants.PLAYERS_TABLE_NAME + " where TEAM in ('" + team1 + "','" + team2 + "') and ROLE = '" + playerRole + "'";
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor != null) {
try {
while (cursor.moveToNext()) {
String name = cursor.getString(0);
String team = cursor.getString(1);
String role = cursor.getString(2);
String country = cursor.getString(3);
int isUncapped = cursor.getInt(4);
Player player = new Player(name, role, team, country, isUncapped);
players.add(player);
}
} catch (Exception e) {
Log.e(TAG, "Exception while reading the cursor");
} finally {
try {
cursor.close();
db.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing the cursor/db");
}
}
}
return players;
}
}
<file_sep>/app/src/main/java/com/lakshmibros/fpl/data/model/Player.java
package com.lakshmibros.fpl.data.model;
public class Player {
private String name;
private String team;
private String role;
private String country;
private int isUncapped;
public Player(String name, String team, String role, String country, int isUncapped) {
this.name = name;
this.team = team;
this.role = role;
this.country = country;
this.isUncapped = isUncapped;
}
public String getName() {
return name;
}
public String getTeam() { return team; }
public String getRole() {
return role;
}
public String getCountry() { return country; }
public int isUncapped() { return isUncapped; }
}
<file_sep>/app/src/main/java/com/lakshmibros/fpl/data/model/DailyTeam.java
package com.lakshmibros.fpl.data.model;
import java.util.ArrayList;
public class DailyTeam {
private int matchNumber;
private ArrayList<String> team;
private String captain;
private String powerPlayer;
private String winningTeam;
public DailyTeam(int matchNumber, ArrayList<String> team, String captain, String powerPlayer, String winningTeam) {
this.matchNumber = matchNumber;
this.team = team;
this.captain = captain;
this.powerPlayer = powerPlayer;
this.winningTeam = winningTeam;
}
public int getMatchNumber() {
return matchNumber;
}
public ArrayList<String> getTeam() { return team; }
public String getCaptain() {
return captain;
}
public String getPowerPlayer() {
return powerPlayer;
}
public String getWinningTeam() {
return winningTeam;
}
}
| 1aacc185d6a0f8ffe99cd733c7d1666d6bb921cd | [
"Java"
] | 4 | Java | lakshmi8/FamilyPremierLeague | 8d8484638fa4b3172850974c7bcc1f98451e1230 | 6e73e73bc702e4a7fa46b350d6620e4ce06f60da |
refs/heads/master | <file_sep>### SPRING BOOT CONTAINERIZED EXAMPLE
<file_sep>insert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)
values(10001,'USD','EUR',0.88,0);
insert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)
values(10002,'EUR','USD',1.13,0);
insert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)
values(10003,'EUR','AUD',1.57,0);
insert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)
values(10004,'AUD','EUR',0.64,0); | f4a6bb5dd3e1149b32b629a60b8ca16ef22f2de8 | [
"Markdown",
"SQL"
] | 2 | Markdown | devcrops-official/spring-boot-microservice-forex-service | bd86052a98f1f03f4ce4f21a1a2d1e51de38a5c5 | abc39be9f4db2feebef54224d3963d97ea47764b |
refs/heads/master | <file_sep>using NUnit.Framework;
using FluentAssertions;
using System.IO;
namespace Arthware.X937Parser.Tests
{
[TestFixture]
public abstract class X937ParserTests
{
private X937Parser _sut;
private Stream _stream;
[SetUp]
public void PrepareX937ParserTests()
{
_stream = new MemoryStream();
_sut = new X937Parser();
}
public sealed class GetX937ReturnsMethod : X937ParserTests
{
[Test]
public void Should_do_jack_when_there_are_no_bytes_in_the_stream()
{
//act
var result = _sut.GetX937Returns(_stream);
//assert
result.Should().BeEmpty();
}
}
}
}
<file_sep>namespace Arthware.X937Parser.Models
{
public sealed class X937Return
{
/*
Aba = PayorBankRoutingNumber + PayorBankRoutingNumberCheckDigit
OnUsReturnRecord:
The Payor’s account number as well as a check number or transaction code if present, separated by ‘/’
{Account Number}/{Trans Code or Check Number}
*/
public string PayorBankRoutingNumber { get; set; }
public string PayorBankRoutingNumberCheckDigit { get; set; }
public string OnUsReturnRecord { get; set; }
public string ItemAmount { get; set; }
public string ReturnReason { get; set; }
public string ExternalProcessingCode { get; set; }
public string AuxiliaryOnUs { get; set; }
}
}<file_sep>namespace Arthware.X937Parser.Models
{
public enum X937Record
{
CashLetterHeader10 = 10,
Return31 = 31,
ReturnAddendumB33 = 33,
BundleControl70 = 70,
CashLetterControl90 = 90,
FileControl99 = 99
}
public enum CashLetterHeaderRecord10Field
{
CollectionTypeIndicator = 2
}
public static class CollectionTypeIndicators
{
public const string FORWARD_PRESENTMENT = "01";
public const string RETURN = "03";
}
public enum ReturnRecord31Field
{
PayorBankRoutingNumber = 2,
PayorBankRoutingNumberCheckDigit = 3,
OnUsReturnRecord = 4,
ItemAmount = 5,
ReturnReason = 6,
ExternalProcessingCode = 11
}
public enum ReturnRecord33Field
{
AuxiliaryOnUs = 3
}
public enum Record90Field
{
BundleCount = 2
}
public enum Record99Field
{
CashLetterCount = 2
}
public enum Record70Field
{
ItemsWithinBundleCount = 2
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
//using System.Runtime;
namespace CFS.SkyNet.Common
{
/// <summary>
/// Helper for creating string enums.
/// Code from here: http://code.google.com/p/stringenums4dotnet/
/// License: Apache License 2.0: http://www.apache.org/licenses/LICENSE-2.0
/// </summary>
/// <code>
/// public class MyStringEnum : StringEnumBase
/// {
/// private MyStringEnum(string value) : base(value){}
///
/// public static readonly MyStringEnum IsNeeded = new MyStringEnum("needed");
/// public static readonly MyStringEnum NotNeeded = new MyStringEnum("notneeded");
/// }
///
/// Usage...
/// if (myenumvar == MyStringEnum.IsNeeded) ....
/// or
/// Console.WriteLine(myenumvar); //produces "needed"
/// </code>
public abstract class StringEnumBase : IComparable<StringEnumBase>
{
#region Const name to value mapping
private sealed class NameValueData
{
public string FieldName { get; set; }
public string StringValue { get; set; }
public StringEnumBase Value { get; set; }
}
private static readonly IDictionary<Type, IEnumerable<NameValueData>> TypeInfo = new Dictionary<Type, IEnumerable<NameValueData>>();
private static readonly object LockObject = new object();
private static IEnumerable<NameValueData> GetFieldDataForType(Type enumType)
{
if (TypeInfo.ContainsKey(enumType))
{
return TypeInfo[enumType];
}
lock (LockObject)
{
if (TypeInfo.ContainsKey(enumType))
{
return TypeInfo[enumType];
}
var fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
var fieldData = fields.Select(f => new NameValueData
{
FieldName = f.Name,
StringValue = f.GetValue(null).ToString(),
Value = (StringEnumBase) f.GetValue(null)
}).ToList();
TypeInfo[enumType] = fieldData;
return fieldData;
}
}
#endregion
private readonly string _value;
private readonly Lazy<string> _name;
/// <summary>
/// Initializes a new instance of the <see cref="StringEnumBase"/> class.
/// </summary>
/// <param name="value">The name.</param>
protected StringEnumBase(string value) : this()
{
_value = value;
}
private StringEnumBase()
{
_name = new Lazy<string>(() =>
{
var allEnumMembers = GetFieldDataForType(this.GetType());
return allEnumMembers.First(f => ReferenceEquals(f.Value, this)).FieldName;
});
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public sealed override string ToString()
{
return _value;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception>
public sealed override bool Equals(object obj)
{
if (obj is string)
return _value.Equals(obj);
if (obj is StringEnumBase)
return _value == obj.ToString();
return false;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public sealed override int GetHashCode()
{
return _value.GetHashCode();
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="first">The first.</param>
/// <param name="second">The second.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(StringEnumBase first, string second)
{
if ((object)first == null)
{
return second == null;
}
return (second == first.ToString());
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="first">The first.</param>
/// <param name="second">The second.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(StringEnumBase first, string second)
{
return !(first == second);
}
/// <summary>
/// Gets the names for a particular constant base type by reflection.
/// </summary>
/// <param name="constantType">Type of the constant.</param>
/// <returns></returns>
public static IEnumerable<string> GetNames(Type constantType)
{
if (constantType == null)
{
throw new ArgumentNullException("constantType");
}
//HACK - not equivalent
if (!constantType.IsAssignableFrom(typeof(StringEnumBase)))
//if (constantType.BaseType != typeof (StringEnumBase))
{
throw new ArgumentException("Must inherit from type StringConstantBase.", "constantType");
}
return GetFieldDataForType(constantType).Select(f => f.FieldName);
}
/// <summary>
/// Gets a string enum by string value
/// </summary>
/// <typeparam name="T">Type of the string enum</typeparam>
/// <param name="stringValue">The string value to lookup</param>
/// <returns>The string enum</returns>
/// <exception cref="ArgumentNullException">Thrown if the string parameter is null</exception>
/// <exception cref="ArgumentException">Thrown if the string value is not found</exception>
public static T GetByValue<T>(string stringValue) where T : StringEnumBase
{
if (stringValue == null)
{
throw new ArgumentNullException("stringValue");
}
var possibleValues = GetFieldDataForType(typeof(T));
var enumData = possibleValues.FirstOrDefault(e => e.StringValue == stringValue);
if (enumData == null)
{
throw new ArgumentException("Value not found: " + stringValue, "stringValue");
}
return enumData.Value as T;
}
/// <summary>
/// Gets a string enum by string value and enum type
/// </summary>
/// <param name="enumType">Type of the string enum</param>
/// <param name="name">The string name of the type of the enum</param>
/// <param name="ignoreCase">true to ignore case; false to regard case.</param>
/// <returns>The string enum</returns>
public static object Parse(Type enumType, string name, bool ignoreCase = false)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (enumType == null)
{
throw new ArgumentNullException("enumType");
}
if (!(typeof (StringEnumBase).IsAssignableFrom(enumType)))
{
throw new ArgumentException("Should inherit from StringEnumBase.", "enumType");
}
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("Should not be empty string.", "name");
}
var found = GetFieldDataForType(enumType).FirstOrDefault(t => Compare(t.FieldName, name, ignoreCase));
if (found == null)
{
throw new ArgumentException("Requested name '" + name + "' was not found.");
}
return found.Value;
}
private static bool Compare(string fieldName, string name, bool ignoreCase)
{
var comparer = ignoreCase
? StringComparison.OrdinalIgnoreCase
: StringComparison.CurrentCulture;
return string.Compare(fieldName, name, comparer) == 0;
}
/// <summary>
/// Attempts to parse a StringEnumBase, returning the result and a boolean indicating success
/// </summary>
/// <typeparam name="TEnum">The type of the enum being parsed to</typeparam>
/// <param name="value">The string value of the enum to parse</param>
/// <param name="result">The result of the parse</param>
/// <returns>Indication of successful parse</returns>
public static Boolean TryParse<TEnum>(string value, out TEnum result) where TEnum : StringEnumBase
{
try
{
result = (TEnum)Parse(typeof (TEnum), value);
}
catch (Exception)
{
result = default(TEnum);
return false;
}
return true;
}
/// <summary>
/// Gets all defined values for a string enum
/// </summary>
/// <typeparam name="T">The string enum</typeparam>
/// <returns>The string values</returns>
public static IEnumerable<string> GetAllValues<T>() where T : StringEnumBase
{
return GetFieldDataForType(typeof (T)).Select(f => f.StringValue);
}
/// <summary>
/// Gets the name of the enum as a string
/// </summary>
/// <returns>The string name of the enum</returns>
public string GetName()
{
return _name.Value;
}
public static implicit operator string(StringEnumBase value)
{
return value == null ? null : value.ToString();
}
/// <summary>
/// Returns all defined members for type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IEnumerable<T> GetAllDefinedMembers<T>()
where T : StringEnumBase
{
return GetFieldDataForType(typeof(T))
.Select(f => f.Value as T);
}
#region IComparable<StringStringEnumBase> Members
public int CompareTo(StringEnumBase other)
{
return String.Compare(_value, other.ToString(), StringComparison.Ordinal);
}
#endregion
}
}
<file_sep>using NUnit.Framework;
using System.IO;
using System.Linq;
using FluentAssertions;
namespace Arthware.X937Parser.Tests.Integration
{
public abstract class X937ParserTests
{
private const string SAMPLE_FORWARD_PRESENTMENT_X9_FILE = @"SampleX9ReturnFiles\Sample.x9";
//this file not included in version control: may contain production information
private const string SAMPLE_MULTIPLE_RETURN_X9_FILE = @"SampleX9ReturnFiles\BT302IMGBO.CACHETRETURN.20170208123227.x937";
private X937Parser _sut;
[SetUp]
public void PrepareX937ParserTests()
{
_sut = new X937Parser();
}
[TestFixture, Explicit]
public sealed class GetX937ReturnsMethod : X937ParserTests
{
[Test]
public void Should_interogate_the_file_and_emit_no_returns_when_the_X9_file_is_for_forward_presentment()
{
//arrange
using (var filestream = new FileStream(SAMPLE_FORWARD_PRESENTMENT_X9_FILE, FileMode.Open, FileAccess.Read, FileShare.Read))
{
//act
var returns = _sut.GetX937Returns(filestream).ToArray();
//assert
returns.Should().BeEmpty();
}
}
[Test]
public void Should_emit_all_the_returns_when_multiple_returns_are_present_on_the_X9_file()
{
//arrange
using (var filestream = new FileStream(SAMPLE_MULTIPLE_RETURN_X9_FILE, FileMode.Open, FileAccess.Read, FileShare.Read))
{
//act
var returns = _sut.GetX937Returns(filestream).ToArray();
//assert
returns.Count().Should().Be(2);
}
}
}
}
}
<file_sep>using System.Collections.Generic;
using System.IO;
using System;
using System.Linq;
using Arthware.X937Parser.Models;
using Thinktecture.IO;
using System.Text;
using Thinktecture.IO.Adapters;
using CFS.SkyNet.Common;
namespace Arthware.X937Parser
{
public sealed class X937Parser : IX937FileParser
{
private static int EBCDIC_ENCODING = 37;
public IEnumerable<X937Return> GetX937Returns(Stream stream)
{
var returns = new List<X937Return>();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
using (IBinaryReader binaryReader = new BinaryReaderAdapter(stream, Encoding.GetEncoding(EBCDIC_ENCODING)))
{
var recordLength = GetRecordLength(binaryReader);
while (recordLength > 0)
{
var recordTypeBytes = GetRecord(binaryReader, 2);
if (recordTypeBytes == X937RecordType.CashLetterHeader10)
{
var record = recordTypeBytes + GetRecord(binaryReader, recordLength - 2);
var collectionTypeIndicator = GetCollectionTypeIndicatorFromCashLetterHeader10(record);
if (collectionTypeIndicator == X937CollectionType.ForwardPresentment)
{
break; // Ok, yes that's crap
}
}
else if (recordTypeBytes == X937RecordType.ReturnRecord31)
{
var record = recordTypeBytes + GetRecord(binaryReader, recordLength - 2);
returns.Add(GetReturnFromReturnRecord31(record));
}
else if (recordTypeBytes == X937RecordType.ReturnAddendumB33)
{
// assume that a record 33 is always after a record 31
var mostRecentReturn = returns.LastOrDefault();
if (mostRecentReturn != null)
{
var record = recordTypeBytes + GetRecord(binaryReader, recordLength - 2);
mostRecentReturn.AuxiliaryOnUs = GetAuxiliaryOnUsFromReturnAddendumB33(record);
}
}
else
{
binaryReader.BaseStream.Seek(recordLength - 2, SeekOrigin.Current);
}
recordLength = GetRecordLength(binaryReader);
}
}
return returns;
}
private sealed class X937RecordType : StringEnumBase
{
private X937RecordType(string recordType)
: base(recordType)
{
}
public static readonly X937RecordType CashLetterHeader10 = new X937RecordType("10");
public static readonly X937RecordType ReturnRecord31 = new X937RecordType("31");
public static readonly X937RecordType ReturnAddendumB33 = new X937RecordType("33");
}
private sealed class X937CollectionType : StringEnumBase
{
private X937CollectionType(string recordType)
: base(recordType)
{
}
public static readonly X937CollectionType ForwardPresentment = new X937CollectionType("01");
public static readonly X937CollectionType Return = new X937CollectionType("03");
}
private static string GetAuxiliaryOnUsFromReturnAddendumB33(string record)
{
return record.Substring(20, 15);
}
private static string GetCollectionTypeIndicatorFromCashLetterHeader10(string record)
{
return record.Substring(2, 2);
}
private static X937Return GetReturnFromReturnRecord31(string record)
{
return new X937Return
{
OnUsReturnRecord = record.Substring(11, 20),
ExternalProcessingCode = record.Substring(68, 1),
ItemAmount = record.Substring(31, 10),
PayorBankRoutingNumber = record.Substring(2, 8),
PayorBankRoutingNumberCheckDigit = record.Substring(10, 1),
ReturnReason = record.Substring(41, 1)
};
}
private static string GetRecord(IBinaryReader input, int recordLength)
{
var recordBinary = input.ReadBytes(recordLength);
return Encoding.ASCII.GetString(ConvertEbcdicToAscii(recordBinary));
}
private static byte[] ConvertEbcdicToAscii(byte[] ebcdicData)
{
return Encoding.Convert(Encoding.GetEncoding(EBCDIC_ENCODING), Encoding.ASCII, ebcdicData);
}
private static int GetRecordLength(IBinaryReader input)
{
const int RECORD_LENGTH_BYTES = 4;
var recordLength = input.ReadBytes(RECORD_LENGTH_BYTES);
if (recordLength.Length == RECORD_LENGTH_BYTES)
{
Array.Reverse(recordLength);
return BitConverter.ToInt32(recordLength, 0);
}
return 0;
}
}
}
<file_sep># Arthware.X937Parser
At the office we had a requirement for a microservice to parse check returns from an X9.37 file and emit metadata about each return.
There is a commercial library/SDK for reading and writing X9.37 files.
I recommended against using the library for our requirement:
* For the purpose of interogating the X9.37 file for returns and returning an array of the discovered returns, we required only a very small subset of the libraries capabilities.
* The API is "high friction" for implementing our simple requirement. No pit of success here.
* The API is "file based", so it is necessary to copy the file to the server file system in order to read the contents.
* The library costs money
* The library is not ".NET Core ready", has a bizzare dependency on WinForms
* The library deployment to production requires installing a license manager Windows application and manually entery of licensing keys/codes.
* Deployment automation is ..er.. challenging
* For giggles, in my personal time, I built a demonstration proof of concept project in a few hours that has all the functionality we needed, suitable for .NET Core, and "stream based" instead of "file based"
Regardless, the management decision was to use the library. I won't expand on the reasoning there.
Since I built the demonstration project on my own time, I decided to open source it, in case anyone else has a similar requirement.
If this project proves to be interesting in the wild then we can expand the functionality to parse other information out of X9.37 files, or whatever seems to be in demand. If this project proves to be crickets, then there won't be any expansion of functionality.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
<file_sep>using Arthware.X937Parser.Models;
using System.Collections.Generic;
using System.IO;
namespace Arthware.X937Parser
{
public interface IX937FileParser
{
IEnumerable<X937Return> GetX937Returns(Stream stream);
}
}
| 849492dd5bbb9ba233d8e2af562c0e46c3bf0c9e | [
"Markdown",
"C#"
] | 8 | C# | arthg/Arthware.X937Parser | 3dcf7657f1d191d1fb01fc1d526216f75d2cf631 | 5b3c381be2f0113339c2d33a428162cfde574da4 |
refs/heads/main | <file_sep>#title: "HCCDataSurvivalPrediction"
#author: "<NAME>"
#date: "11/08/2021"
#Load Packages
library(data.table)
library(dplyr)
library(corrplot)
library(ggplot2)
library(gmodels)
library(caret)
library(rpart)
library(rpart.plot)
library(glmnet)
library(arm)
library(mltools)
#Set Work Directory
#setwd("directory")
#Read Dataset
hccdata <- read.csv("hcc-data.csv", h = TRUE, sep = ",", na.strings = "?", dec = '.',
col.names = c('Gender', 'Symptoms', 'Alcohol',
'HBsAg', 'HBeAg', 'HBcAb', 'HCVAb',
'Cirrhosis', 'Endemic','Smoking',
'Diabetes', 'Obesity','Hemochro',
'AHT', 'CRI', 'HIV', 'NASH',
'Varices', 'Spleno','PHT', 'PVT',
'Metastasis', 'Hallmark', 'Age',
'Grams_day', 'Packs_year', 'PS',
'Encephalopathy', 'Ascites', 'INR',
'AFP', 'Hemoglobin', 'MCV', 'Leucocytes',
'Platelets', 'Albumin', 'Total_Bil',
'ALT', 'AST', 'GGT', 'ALP', 'TP',
'Creatinine', 'Nodules','Major_Dim',
'Dir_Bil', 'Iron', 'Sat', 'Ferritin',
'Class'))
#Look at the Dataset Organization
#str(hccdata)
#summary(hccdata)
#dim(hccdata)
## Variables type
numeric.vars <- c('Grams_day', 'Packs_year', 'INR', 'AFP',
'Hemoglobin', 'MCV', 'Leucocytes', 'Platelets',
'Albumin', 'Total_Bil', 'ALT', 'AST', 'GGT', 'ALP',
'TP', 'Creatinine', 'Major_Dim', 'Dir_Bil',
'Iron', 'Sat', 'Ferritin')
categorical.vars <- c('Gender', 'Symptoms', 'Alcohol', 'HBsAg',
'HBcAb', 'HCVAb', 'Cirrhosis', 'Endemic', 'Smoking',
'Diabetes', 'Obesity', 'Hemochro', 'AHT', 'CRI',
'HIV', 'NASH', 'Varices', 'Spleno', 'PHT', 'PVT',
'Metastasis', 'Hallmark', 'Class', 'PS', 'Encephalopathy', 'Ascites', 'Nodules')
ordinal.vars <- c('PS', 'Encephalopathy', 'Ascites', 'Nodules')
#Check NAs
sapply(hccdata, function(x) sum(is.na(x)))
#Variables Distribution
cbind(freq=table(hccdata$Class), percentage=prop.table(table(hccdata$Class))*100)
#Density Distribution
par(mfrow=c(4,4))
for(i in 1:50) {
plot(density(na.omit(hccdata[,i])), main=names(hccdata)[i])
}
#Boxplot
par(mfrow=c(1,4))
for(i in 1:50) {
boxplot(na.omit(hccdata[,i]), main=names(hccdata)[i])
}
#Atributes by Class - Fazer por partes
jittered_x <- sapply(hccdata[,1:5], jitter)
pairs(jittered_x, names(hccdata[,1:5]), col=c('blue', 'red') )
par(mfrow=c(3,2))
for(i in 1:50) {
barplot(table(hccdata$Class,hccdata[,i]), main=names(hccdata)[i],)
}
#Removing column: HBeAg(0:124, 1:1, NA:39)
hccdata$HBeAg <- NULL
#Smoking and Packs_Year
for(i in 1:nrow(hccdata)){
if(is.na(hccdata$Packs_year[i]==TRUE)){
hccdata$Packs_year[i] <- sample(na.omit(hccdata$Packs_year), 1)
}
}
for(i in 1:nrow(hccdata)){
if(hccdata$Packs_year[i]>0){
hccdata$Smoking[i] <- 1
} else {
hccdata$Smoking[i] <- 0
}
}
### Splitting classes
dead <- filter(hccdata, hccdata$Class=='1')
notdead <- filter(hccdata, hccdata$Class=='0')
#Other variables
for(i in 1:nrow(dead)){
for(j in 1:ncol(dead)){
if(is.na(dead[i,j]==TRUE)){
dead[i,j] <- sample(na.omit(dead[,j]), 1)
}
}
}
for(i in 1:nrow(notdead)){
for(j in 1:ncol(notdead)){
if(is.na(notdead[i,j]==TRUE)){
notdead[i,j] <- sample(na.omit(notdead[,j]), 1)
}
}
}
hccdata <- rbind(dead, notdead)
rm(dead, notdead)
invisible(gc())
## Formatting columns to factors function
to.factors <- function(df, variables){
for (variable in variables){
df[[variable]] <- as.factor(df[[variable]])
}
return(df)
}
## Factor variables
hccdata <- to.factors(df = hccdata, variables = categorical.vars)
datatabledata <- as.data.table(hccdata)
hccdata <- one_hot(datatabledata , cols = c('Encephalopathy', 'PS', 'Ascites', 'Nodules'), dropCols = TRUE)
hccdata <- as.data.frame(hccdata)
factorsvar <- c('Nodules_1', 'Nodules_2', 'Nodules_3', 'Nodules_4', 'Nodules_5', 'Ascites_1', 'Ascites_2', 'Ascites_3', 'Encephalopathy_1', 'Encephalopathy_2', 'Encephalopathy_3', 'PS_0', 'PS_1', 'PS_2', 'PS_3', 'PS_4')
hccdata <- to.factors(df = hccdata, variables = factorsvar)
rm(datatabledata)
invisible(gc())
### Age
hccdata$Age <- hccdata$Age/max(hccdata$Age)
# Normalization function
scale.features <- function(df, variables){
for (variable in variables){
df[[variable]] <- scale(df[[variable]], center=T, scale=T)
}
return(df)
}
hccdata_scaled <- scale.features(hccdata, numeric.vars)
# Spliting train and test datasets
set.seed(123)
intrain<- createDataPartition(hccdata_scaled$Class,p=0.85,list=FALSE)
training<- hccdata_scaled[intrain,]
testing<- hccdata_scaled[-intrain,]
prop.table(table(testing$Class))
#class(training)
#training$Class
#View(training)
# Verifying correlation between numeric variables
numeric.var <- sapply(training, is.numeric)
corr.matrix <- cor(training[,numeric.vars])
corrplot::corrplot(corr.matrix, main="\n\n Correlation Between Numeric Variables", method="number")
# Feature Selection
training$Class <- as.factor(training$Class)
formula <- "Class ~ ."
formula <- as.formula(formula)
control <- trainControl(method = "repeatedcv", number = 10, repeats = 10)
model <- train(formula, data = training, method = "bayesglm", trControl = control)
importance <- varImp(model, scale = FALSE)
#print(model)
# Plot
plot(importance)
#Function to select variables using Random Forest
run.feature.selection <- function(num.iters=30, feature.vars, class.var){
set.seed(10)
variable.sizes <- 1:10
control <- rfeControl(functions = rfFuncs, method = "cv",
verbose = FALSE, returnResamp = "all",
number = num.iters)
results.rfe <- rfe(x = feature.vars, y = class.var,
sizes = variable.sizes,
rfeControl = control)
return(results.rfe)
}
rfe.results <- run.feature.selection(feature.vars = training[,-62],
class.var = training[,62])
#Visualization of results
#rfe.results
varImp((rfe.results))
# Train the Model
model <- "Class ~ ."
LogModel <- bayesglm(model, family=binomial,
data=training, drop.unused.levels = FALSE)
training$Class <- as.character(training$Class)
fitted.results <- predict(LogModel,newdata=training,type='response')
fitted.results <- ifelse(fitted.results > 0.5,1,0)
misClasificError <- mean(fitted.results != training$Class)
print(paste('Logistic Regression Accuracy',1-misClasificError))
testing$Class <- as.character(testing$Class)
fitted.results <- predict(LogModel,newdata=testing,type='response')
fitted.results <- ifelse(fitted.results > 0.5,1,0)
misClasificError <- mean(fitted.results != testing$Class)
print(paste('Logistic Regression Accuracy',1-misClasificError))
#Confusion Matrix of Logistic Regression
print("Confusion Matrix Para Logistic Regression")
table(testing$Class, fitted.results > 0.5)
# Train the Model
model <- "Class ~ Symptoms + Alcohol +
HBsAg + HCVAb +
Smoking +
Diabetes +
AHT + CRI + HIV +
NASH + Varices + Spleno +
PHT + PVT +
Age +
Packs_year + PS_1 +
PS_3 + PS_4 +
Encephalopathy_2 + Encephalopathy_3 +
Ascites_1 + Ascites_3 +
INR + AFP + Hemoglobin +
MCV + Leucocytes + Platelets +
Albumin + ALT +
AST + ALP +
TP + Creatinine +
Nodules_2 + Nodules_3 +
Major_Dim +
Dir_Bil + Iron + Sat +
Ferritin"
training$Class <- as.factor(training$Class)
LogModel <- bayesglm(model, family=binomial,
data=training, drop.unused.levels = FALSE)
training$Class <- as.character(training$Class)
fitted.results <- predict(LogModel,newdata=training,type='response')
fitted.results <- ifelse(fitted.results > 0.5,1,0)
misClasificError <- mean(fitted.results != training$Class)
print(paste('Logistic Regression Accuracy',1-misClasificError))
testing$Class <- as.character(testing$Class)
fitted.results <- predict(LogModel,newdata=testing,type='response')
fitted.results <- ifelse(fitted.results > 0.5,1,0)
misClasificError <- mean(fitted.results != testing$Class)
print(paste('Logistic Regression Accuracy',1-misClasificError))
#Confusion Matrix of Logistic Regression
print("Confusion Matrix Para Logistic Regression")
table(testing$Class, fitted.results > 0.5)<file_sep># :stethoscope: Hepatocellular Carcinoma Dataset (HCC dataset) Survival Prediction with Logistic Regression
The dataset used here was collected at a University Hospital in Portugal. It contains real clinical data of 165 patients diagnosed with HCC. It was downloaded from [Kaggle](https://www.kaggle.com/mrsantos/hcc-dataset). The goal is to predict if a person will survive or not one year after the diagnosis. It contains several information like symptons, alcohol, hepatitis, metastasis, gender, cirrhosis and etc. The main challenges on this dataset are the unballanced classes, high number of missing data and small sample.
Predicting cancer survival with Logistic Regression.
[HCCSurvivalPrediction.R](https://github.com/natmurad/cancersurvivalprediction/blob/main/HCCSurvivalPrediction.R) - code with data pre-processing, feature engineering, feature selection, training of the model, model evaluation.
[HCCSurvivalPrediction.html](https://rpubs.com/natmurad/hccdata) - html report with comments, graphic exploration, feature selection, treatment of missing values and training of the Logistic Regression Model.
| 32ceea5c23daede816490cd72d3de4e01d86120a | [
"Markdown",
"R"
] | 2 | R | natmurad/cancersurvivalprediction | 5f2f89e39047dfa3c6538350b18be9fe40fe55a7 | 05a0ca17a57bfa37e4fb4e1358c761d3c3bf15cb |
refs/heads/main | <file_sep># RecursiveFetch
Created with CodeSandbox
<file_sep>async function fetchPages({ page }) {
let url = `https://rickandmortyapi.com/api/character/?page=${page}`;
let req = await fetch(url);
let json = await req.json();
return json;
}
async function recursiveSequentialFetch({ page, data, maxCalls }) {
let json = await fetchPages({ page });
data.push(json);
console.log("Sequential Fetch", page, data);
if (page < maxCalls) {
return recursiveSequentialFetch({ page: page + 1, data, maxCalls });
} else {
return { page, data, maxCalls };
}
}
recursiveSequentialFetch({ page: 1, data: [], maxCalls: 3 })
.then(data => {
console.log("Sequential Fetch Done", data);
})
.catch(err => {
console.log(err);
});
| 34259a32b922d33b2994e0ec4cf986340bc0d087 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | marcelobento/RecursiveFetch | 3e726ee32b5851abf3b0c0c3ac3a74d5aac86f87 | 6d30f0158375a1af8e0c2ea4229428f83c34ed0b |
refs/heads/main | <file_sep>package cenarioCadeiaDeRequisicao;
public class ExportadorTeste {
public static void main(String[] args) {
Requisicao requisicao = new Requisicao(Formato.CSV);
Conta conta = new Conta(100, "Vitor");
Exportador exportador = new ExportaCSV(new ExportaXML(new ExportaJSON()));
System.out.println(exportador.exportar(requisicao, conta));
}
}
<file_sep>package cenarioRelatorios;
import java.math.BigDecimal;
public class RelatorioSimples extends AbstractRelatorio {
public RelatorioSimples(String nomeBanco, String telefone, String titularDaConta, BigDecimal saldo) {
super( nomeBanco, telefone, titularDaConta, saldo);
}
@Override
void geraCabecalho() {
System.out.println("Nome do banco: " + super.nomeBanco);
}
@Override
void geraRelatorio() {
System.out.println("Titular " + super.titularDaConta + " saldo da conta: " + super.saldo);
}
@Override
void geraRodape() {
System.out.println("Telefone " + super.telefone);
}
}
<file_sep>package cenarioCadeiaDeRequisicao;
public class ExportaCSV extends Exportador {
protected ExportaCSV(Exportador proximo) {
super(proximo);
}
@Override
protected String efetuaExport(Conta conta) {
return conta.getNomeTitular() + "%" + conta.getSaldo();
}
@Override
boolean deveAplicar(Requisicao requisicao) {
return requisicao.getFormato() == Formato.CSV;
}
}
| 5361d133e7a6b24f9b3de89b88b471a13d766727 | [
"Java"
] | 3 | Java | VitorMaverick/Etapa01Atividade02Strategy-Template-Chain | 9fdeb45bc8180de5afcddaa9988c9745726ee8f7 | 772a5aec565747088ff6e7feb786abcd6bef4561 |
refs/heads/master | <file_sep>import { Injectable } from '@angular/core';
import {Http} from "@angular/http";
import {CabinetInterface} from "./dataInterfaces/cabinet";
import {Adresse} from "./dataInterfaces/adress";
import {sexeEnum} from "./dataInterfaces/sexe";
import {PatientInterface} from "./dataInterfaces/patient";
@Injectable()
export class CabinetMedicalService {
private patient: PatientInterface;
constructor(private http: Http) {
}
getAdresseFrom(A :Element):Adresse{
let node :Element;
return {
étage:(node=A.querySelector("étage"))?node.textContent:"",
rue:A.querySelector("rue").textContent,
numéro:(node=A.querySelector("numéro"))?node.textContent:"",
ville:A.querySelector("ville").textContent,
codePostal:parseInt(A.querySelector("étage")?node.textContent:"",10),
lat:120,
lng:130,
};
}
getData(url: string): Promise<CabinetInterface> {
return this.http.get(url).toPromise().then(res => {
console.log(url, "=>", res);
const text = res.text();
const parser = new DOMParser();
const doc = parser.parseFromString(text, "text/xml");
const cabinet: CabinetInterface = {
infirmiers: [],
patientsNonAffectes: [],
adresse: this.getAdresseFrom(doc.querySelector("cabinet>adresse"))
};
//return cabinet
console.log(cabinet);
//les infirmiers
const infirmiersXML: Element[] = Array.from(
doc.querySelectorAll("infirmiers>infirmier")
);
cabinet.infirmiers = infirmiersXML.map(infirmiersXML => {
return {
id: infirmiersXML.getAttribute("id"),
nom:(infirmiersXML.querySelector("nom")).textContent,
prenom:(infirmiersXML.querySelector("prénom")).textContent,
photo:(infirmiersXML.querySelector("photo")).textContent,
patients: [],
adresse: this.getAdresseFrom(infirmiersXML.querySelector("adresse"))
};
});
const patientsXML = Array.from(
doc.querySelectorAll("patients > patient")
);
const patients: PatientInterface[] = patientsXML.map( patientXML => {
return {
nom: patientXML.querySelector("nom").textContent,
prenom:(patientXML.querySelector("prénom")).textContent,
adresse: this.getAdresseFrom(patientXML.querySelector("adresse")),
numeroSecuriteSociale: patientXML.querySelector("numéro").textContent,
sexe: (patientXML.querySelector("sexe").textContent==="M")?sexeEnum.M :sexeEnum.F,
};
});
// calcul du tableau des affectations
const affectation = patientsXML.map(patientXML => {
const idP = patientXML.querySelector('numéro').textContent;
const patient = patients.find(P => P.numeroSecuriteSociale === idP)
const intervenant = patientXML.querySelector('visite').getAttribute('intervenant');
const infirmier = cabinet.infirmiers.find(i => i.id === intervenant);
return {infirmier: infirmier, patient: patient};
});
//puis réaliser les affectations
affectation.forEach(A => {
if(A.infirmier){
A.infirmier.patients.push(A.patient);
}else {
cabinet.patientsNonAffectes.push(A.patient);
}
}
);
console.log(patients);
console.log(cabinet);
return cabinet;
});
}
public Addpatient(nom: string, prenom: string, sexe: string, numeroSecuriteSociale: string, rue: string, codepostal: string, ville: string, numero: string, etage: string, date: string) {
let se;
if ( sexe === "M") {
se = sexeEnum.M;
}else {se = sexeEnum.F;}
const adress: Adresse = {
étage: etage,
numéro: numero,
rue: rue,
codePostal: Number(codepostal),
ville: ville,
lat: null,
lng: null,
};
const patient: PatientInterface = {
prenom: prenom ,
nom: nom,
sexe: se,
numeroSecuriteSociale: numeroSecuriteSociale,
adresse: adress,
};
this.ajouter(patient);
}
public ajouter(patient: PatientInterface) {
this.http.post('/addPatient', {
patientName: patient.nom,
patientForname: patient.prenom,
patientNumber: patient.numeroSecuriteSociale,
patientSex: patient.sexe,
patientBirthday: 'AAAA-MM-JJ',
patientFloor: patient.adresse.étage,
patientStreetNumber: patient.adresse.numéro,
patientStreet: patient.adresse.rue,
patientPostalCode: patient.adresse.codePostal,
patientCity: patient.adresse.ville
}).toPromise().then(
res => console.log(res),
err => console.error(err)
);
}
public affectation(numéroSécuritéSociale:string,infirmierId:string){
this.http.post( "/affectation", {
infirmier: infirmierId,
patient: numéroSécuritéSociale
}).toPromise().then(
res => console.log(res),
err => console.error(err)
);
}
public desaffectation(numéroSécuritéSociale:string){
this.http.post( "/affectation", {
infirmier: "none",
patient: numéroSécuritéSociale
}).toPromise().then(
res => console.log(res),
err => console.error(err)
);
}
onClick(event: any){
this
console.log(event); //you can explore the event object and use the values as per requirement
}
}
<file_sep>import {Component, Input, OnInit, ViewEncapsulation} from '@angular/core';
import {CabinetMedicalService} from "../cabinet-medical.service";
import {CabinetInterface} from "../dataInterfaces/cabinet";
@Component({
selector: 'app-patient',
templateUrl: './patient.component.html',
styleUrls: ['./patient.component.css'],
encapsulation: ViewEncapsulation.None
})
export class PatientComponent implements OnInit {
@Input() data;
private cabinet: CabinetInterface;
a: boolean;
constructor(private cs: CabinetMedicalService){
this.a = false;
cs.getData('/data/cabinetInfirmier.xml').then(
cabinet => this.cabinet = cabinet);
}
ngOnInit() {
}
public Addpatient(nom: string, prenom: string, sexe: string, numeroSecuriteSociale: string, rue: string, codepostal: string, ville: string, numero: string, etage: string, date: string)
{
if(nom==="" || prenom==="" || numeroSecuriteSociale==="" || codepostal==="" || ville==="" ){
alert("veuillez remplir tous les champs obligatoires");
let e1=document.querySelector("input[name='nom']") as HTMLElement; e1.style.borderColor="red"
let e2=document.querySelector("input[name='prenom']")as HTMLElement; e2.style.borderColor="red"
let e3=document.querySelector("input[name='secu']")as HTMLElement; e3.style.borderColor="red"
let e4=document.querySelector("input[name='postal']")as HTMLElement; e4.style.borderColor="red"
let e5=document.querySelector("input[name='ville']")as HTMLElement; e5.style.borderColor="red"
}else {
this.cs.Addpatient(nom, prenom, sexe, numeroSecuriteSociale, rue, codepostal, ville, numero, etage, date);
this.a = true;
}
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { CabinetMedicalService } from './cabinet-medical.service';
import { SecretaryComponent } from './secretary/secretary.component';
import { PatientComponent } from './patient/patient.component';
import { InfirmierComponent } from './infirmier/infirmier.component';
import {FormsModule} from "@angular/forms";
import {RouterModule,Router} from "@angular/router";
import {CommonModule} from "@angular/common";
import { MaterielModule } from './material';
import { HomeComponent } from './home/home.component'
@NgModule({
declarations: [
AppComponent,
SecretaryComponent,
PatientComponent,
InfirmierComponent,
HomeComponent
],
imports: [
BrowserAnimationsModule,
MaterielModule,
CommonModule,
BrowserModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
{path: '', component: HomeComponent},
{path: 'home', component: HomeComponent},
{path: 'secretary', component: SecretaryComponent},
{path: 'infirmier', component: InfirmierComponent},
{path: 'patient', component: PatientComponent},
] ) ],
providers: [CabinetMedicalService],
bootstrap: [AppComponent],
exports: [CommonModule]
})
export class AppModule { }
<file_sep># ProjetIIHM
Projet réalisé par ESSAKKAY <NAME> DAEF
<file_sep>export interface Adresse {
ville: string;
codePostal: number;
rue: string;
numéro: string;
étage: string;
lat: number;
lng: number;
}
<file_sep>import {Component, Input, OnInit, ViewEncapsulation} from '@angular/core';
import {CabinetMedicalService} from "../cabinet-medical.service";
import {CabinetInterface} from "../dataInterfaces/cabinet";
import {InfirmierInterface} from "../dataInterfaces/nurse";
import {PatientInterface} from "../dataInterfaces/patient";
@Component({
selector: 'app-secretary',
templateUrl: './secretary.component.html',
styleUrls: ['./secretary.component.css'],
encapsulation: ViewEncapsulation.None
})
export class SecretaryComponent implements OnInit {
@Input() data;
cabinet: CabinetInterface;
nonaffecter: string [];
infirmies: InfirmierInterface [] ;
mypatient: PatientInterface [];
selected: string [] ;
constructor(private cs: CabinetMedicalService) {
this.selected=[];
this.nonaffecter=[];
cs.getData('/data/cabinetInfirmier.xml').then(
cabinet => this.cabinet = cabinet);
}
ngOnInit() {
}
getinfirmiers(): InfirmierInterface[] {
return this.infirmies = this.cabinet ? this.cabinet.infirmiers : [];
}
getinfPatient(idf:string): PatientInterface[] {
if(typeof idf== null ){
idf="001"
}else{
let inf=this.getinfirmiers();
inf= inf.filter(e=>e.id==idf);
this.mypatient=inf[0].patients;}
return this.mypatient;
}
public affectation(numéroSécuritéSociale:string,infirmierId:string){
this.cs.affectation(numéroSécuritéSociale,infirmierId);
}
public desaffectation(numéroSécuritéSociale:string){
this.cs.desaffectation(numéroSécuritéSociale);
}
onClick1(event: any,idp:string) {
if (idp === 'infirmiers'){
}else {
this.getinfPatient(idp);
}
}
onClick(event: any) {
let a = event.target.value.toString();
if (event.target.checked === true) {
this.selected.push(a);
} else {
this.selected = this.selected.filter( e => e != a )
}
}
onClick3(event: any) {
let a = event.target.value.toString();
let e1=document.querySelector("button[name='affect']") as HTMLButtonElement;
if (event.target.checked === true) {
this.nonaffecter.push(a);
e1.disabled=false;
} else {
this.nonaffecter = this.nonaffecter.filter( e => e != a );
if(this.nonaffecter[0]===null){
e1.disabled=true;
}
}
}
onClick4(idf:string) {
if(this.nonaffecter[0]!== 'undefined'){
this.nonaffecter.forEach(e=>this.affectation(e,idf));
}
if(this.selected[0]!== 'undefined'){
this.selected.forEach(e=>this.desaffectation(e));
}
document.location.reload()
}
}
| 14e11fbc549815629e40ba1dd4ae29c5051f6fa0 | [
"Markdown",
"TypeScript"
] | 6 | TypeScript | l3miage-ADF/ProjetIIHM | 42eadbc9fff84dabd703762ec173854a5370a406 | e0e77088fd8d58a7178741ffff440b389c4b73b6 |
refs/heads/main | <repo_name>VVariychuk/goit-react-hw-03-image-finder<file_sep>/src/components/ImageGallery/ImageGalleryItem/ImageGalleryItem.js
import s from './ImageGalleryItem.module.css'
const ImageGalleryItem = ({ smallImg, bigImg, id }) => (
<li className={s.ImageGalleryItem} >
<img src={smallImg} data-img={bigImg} alt={id} className={s.ImageGalleryItemImage} />
</li>
);
export default ImageGalleryItem;
<file_sep>/src/App.js
/* eslint-disable jsx-a11y/img-redundant-alt */
import React, { Component } from 'react';
import Loader from "react-loader-spinner";
import s from './App.module.css'
import Searchbar from './components/Searchbar';
import ImageGallery from './components/ImageGallery';
import Button from './components/Button';
import Modal from './components/Modal';
import imageAPI from './services/imageAPI';
class App extends Component {
state = {
pictures: [],
currentPicture: '',
searchQuery: '',
currentPage: 1,
perPage: 12,
isLoading: false,
error: null,
openModal:false,
}
componentDidMount() { }
componentDidUpdate(prevProps, prevState) {
if (prevState.searchQuery !== this.state.searchQuery) {
this.fetchPictures()
.catch(error => console.log(error))
.finally(this.setState({isLoading: false}))
;
}
}
fetchPictures = () => {
const options = {
query: this.state.searchQuery,
page: this.state.page,
perPage: this.state.perPage,
}
this.setState({ isLoading: true })
return imageAPI.getImage(options).then(pictures => {
this.setState(prevState => ({
pictures: [...prevState.pictures, ...pictures],
page: prevState.page + 1,
}))
})
}
onSubmit = (query) => {
this.setState({
searchQuery: query,
page: 1,
pictures: [],
error:null
})
}
toggleModal = () => {
this.setState((prevState) => (
{openModal: !prevState.openModal}
))
}
onImgClick = (e) => {
if (e.target.nodeName !== 'IMG') {
return
}
console.log(e);
this.setState({
currentPicture: e.target.dataset.img,
})
this.toggleModal()
}
onLoadMoreClick = () => {
this.fetchPictures()
.then(() =>
window.scrollTo({
top: document.documentElement.scrollHeight,
behavior: "smooth",
})
)
.catch(error => console.log(error))
.finally(this.setState({isLoading: false}))
}
render() {
const {pictures, isLoading, openModal, currentPicture} = this.state;
return (
<div className={s.App}>
{isLoading &&
<Loader
type="Puff"
color="#00BFFF"
height={100}
width={100}
timeout={3000}
/>}
<Searchbar onSubmit={this.onSubmit}/>
<ImageGallery pictures={pictures} imgClickHandler={this.onImgClick}/>
{pictures.length > 0 && <Button onBtnClick={this.onLoadMoreClick} text={isLoading ? "Загружаем" : "Загрузить еще"} />}
{openModal && (
<Modal onClose={this.toggleModal}>
<img src={currentPicture} alt="This is a big picture" />
</Modal>
)}
</div>
)
};
}
export default App;<file_sep>/src/components/ImageGallery/ImageGallery.js
import ImageGalleryItem from './ImageGalleryItem'
import s from './ImageGallery.module.css'
const ImageGallery = ({pictures, imgClickHandler}) => {
return (
<ul onClick={imgClickHandler}
className={s.ImageGallery}>
{pictures.map(({ id, webformatURL, largeImageURL }) => (
<ImageGalleryItem
key={id}
smallImg={webformatURL}
bigImg={largeImageURL}
id={id}
/>
))}
</ul>
)
}
export default ImageGallery | a0ea6bad09354fab5b20534e7635b447c8a720a1 | [
"JavaScript"
] | 3 | JavaScript | VVariychuk/goit-react-hw-03-image-finder | ffa0a013290a7bf8a04cc63155ad31e5cbca87a9 | d36aacd8dae204a73c7db52eb8e53236645adae4 |
refs/heads/master | <file_sep><!DOCTYPE html>
<html>
<head>
<title>Taskwezom - <?=$title;?></title>
<!-- Bootstrap -->
<link href="../../../bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<style>
body {
padding-top: 65px;
}
#news{
padding-bottom: 20px;
}
.inside {
background-color: beige;
border-radius: 7px;
/*display: inline-block;*/
padding: 2px 50px;
/* width: inherit;*/
}
#review{
height: 100px;
width: 400px;
resize: none;
}
form[name=add_review]
{
max-width: 400px;
}
#more
{
margin-bottom: 10px;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<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="<?php echo URL::base(true); ?>">taskwezom</a>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li <?if ($current_uri=='admin') {?>class="active"<?}?> ><a href="<?= URL::site('/admin'); ?>"> <span class="glyphicon glyphicon-cog"> </span> Home</a></li>
<li <?if ($page_ctrlr=='news') {?>class="active"<?}?> ><a href="<?= URL::site('admin/news');?>"> <span class="glyphicon glyphicon-cog"> </span> News</a></li>
<li <?if ($page_ctrlr=='reviews') {?>class="active"<?}?> ><a href="<?= URL::site('admin/reviews');?>"> <span class="glyphicon glyphicon-cog"> </span> Guest book</a></li>
</ul>
<form class="navbar-form navbar-right" method="post" action="<?=URL::site('/login')?>">
<span class="brand" name="logginuser" style="color: snow; padding: 10px 15px;"> <span class="glyphicon glyphicon-user"> </span> <?if (isset($user)) echo $user;?> </span>
<input hidden="" name="exit">
<button type="submit" class="btn btn-success"><span class="glyphicon glyphicon-log-out"> </span> Sign out</button>
</form>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="well"><h4>Панель администрирования (admin panel)</h4> </div>
<?=$content?>
<hr>
<footer>
<p>© Company 2015</p>
</footer>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../../bootstrap/js/bootstrap.min.js"></script>
</body>
</html><file_sep><?php defined('SYSPATH') or die('No direct script access.');
class Controller_Admin_Reviews extends Controller_Reviews {
public $template = 'admin/admin_template';
}<file_sep><?php defined('SYSPATH') or die('No direct script access.');
class Model_User extends Model_Auth_User
{
protected $_tableUser = 'user';
}<file_sep><h3>Все новости
<?if ($is_admin){?> <a class="btn pull-right btn-large btn-success" href="<?= URL::site('admin/news/add');?>"> <span class="glyphicon glyphicon-plus" aria-hidden="true"> </span> Добавить новость</a><?}?>
</h3>
<br>
<div class="row">
<? foreach ($news as $n) {
$n = $n->as_array();?>
<div class="col-sm-6" id="news">
<?if ($is_admin) {?>
<span class="pull-right"><a class="btn btn-success" href="<?= URL::site('admin/news/edit/'. $n['id']); ?>" title="Edit"><span class="glyphicon glyphicon-edit"> </span></a> <a class="btn btn-danger" href="<?= URL::site('admin/news/delete/'. $n['id']); ?>" title="Delete"><span class="glyphicon glyphicon-trash"> </span></a></span>
<?}?>
<div class="inside">
<h4><?=$n['title'];?></h4>
<p><?//=$n['content'];?></p>
<p id="more"><a class="btn btn-info" href="<?= URL::site('news/'. $n['id']); ?>"><span class="glyphicon glyphicon-eye-open"> </span> View details</a></p>
</div>
</div>
<?}?>
</div>
<!--<p>Всего новостей <?//=$totalnews;?></p>-->
<p><? if (isset ($pagination))echo $pagination; ?></p><file_sep><?php defined('SYSPATH') or die('No direct script access.');
class Model_Role extends Model_Auth_User
{
protected $_tableRole = 'role';
}<file_sep><h3><? if ($page_act=='edit') {?>Редактирование Новости #<?=$id?><?} else if ($page_act=='add') {?>Добавление новости<?}?>
<a class="btn pull-right btn-large btn-info" href="<?
//if ($is_admin)
echo URL::site($is_admin.'/news');
?>"><span class="glyphicon glyphicon-list-alt"> </span> Вернуться к новостям</a>
</h3>
<form action="<? if ($page_act=='edit'){ echo URL::site('admin/news/edit/'.$news->id);} else if ($page_act=='add') {echo URL::site('admin/news/add');}?>" method="POST" name="add_news" enctype="multipart/form-data">
<div class="form-group">
<label for="news_title">Заголовок *</label>
<input type="text" class="form-control" id="news_title" name="news_title" placeholder="Введите заголовок статьи" maxlength="50"
value="<?if (isset($_POST['news_title'])){ echo HTML::chars(Arr::get($_POST, 'news_title')); } else if (isset($news->title)){ echo $news->title; }?>">
<?php if(isset($errors['news_title'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['news_title'].'</div>'; ?>
</div>
<div class="form-group">
<label for="news_content">Контент *</label>
<textarea class="form-control" id="news_content" name="news_content" maxlength="1000"><?if (isset($_POST['news_content'])){ echo HTML::chars(Arr::get($_POST, 'news_content')); } else if (isset($news->content)){ echo $news->content; }?></textarea>
<?php if(isset($errors['news_content'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['news_content'].'</div>'; ?>
</div>
<?if (isset($news->image)){ ?>
<div class="form-group">
<label for="image_old">Предыдущее фото</label>
<img name="image_old" id="image_old" style="width:150px;height: auto;" src="/uploads/<?=$news->image;?>">
</div>
<?}?>
<div class="form-group">
<label for="image">Выберите фото:</label>
<p><input type="file" name="image" id="image"> не более 1Mb.</p>
<?php if(isset($errors['image'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['image'].'</div>'; ?>
</div>
<br>
<button class="btn btn-large btn-success" type="submit"><?if (!$is_admin){?><span class="glyphicon glyphicon-send"> </span> Отправить <?}
else {?><span class="glyphicon glyphicon-floppy-disk"> </span> Сохранить<?}?></button> <a href="<?= URL::site($is_admin.'/news');?>" class="btn btn-large btn-danger" ><span class="glyphicon glyphicon-remove"> </span> Отмена</a>
</form>
<file_sep><?php defined('SYSPATH') or die('No direct script access.');
class Controller_Admin_Main extends Controller_Admin_Base {
public function action_index()
{
if (Auth::instance()->logged_in())
{
$user=Auth::instance()->get_user()->username;
$content = View::factory('/admin/main')
->bind('user',$user);
$this->template->title = 'Admin pannel';
$this->template->user = $user;
$this->template->page_ctrlr=$this->page_ctrlr;
$this->template->content = $content;
}
else {
$this->redirect(URL::site('/login'));
}
}
}<file_sep><?php defined('SYSPATH') or die('No direct script access.');
class Controller_Admin_News extends Controller_News {
public $template = 'admin/admin_template';
}<file_sep><form class="form-signin" method="post" action="<?=URL::site('/login')?>">
<?php if(isset($errors['username'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['username'].'</div>'; ?>
<?php if(isset($error)) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$error.'</div>'; ?>
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Login</label>
<input type="text" id="inputLogin" class="form-control" placeholder="Login" name="username" required="" maxlength
="25" autofocus="" value="<?php echo HTML::chars(Arr::get($_POST, 'username')); ?>">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="<PASSWORD>" name="password" maxlength
="15" required="">
<!-- <div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>-->
<button class="btn btn-lg btn-success btn-block" type="submit"><span class="glyphicon glyphicon-log-in"> </span> Sign in</button>
<p> or if you don't have an account you can </p>
<a href="<?=URL::site('/registration')?>" class="btn btn-lg btn-primary btn-block" > <span class="glyphicon glyphicon-plus-sign"> </span> Sign up</a>
</form><file_sep><h3>Приветсвуем, Администатор <strong><?=$user?></strong></h3>
<p>Это Админпанель - в ней можно добавлять и редактировать новости, а также редактировать отзывы Гостевой книги</p><file_sep><div class="row">
<a class="btn pull-right btn-large btn-info" href="<?= URL::site($is_admin.'/news');?>">Все новости</a>
<h2><?=$news['title'];?></h2>
<?if ((isset ($news['image']))&&($news['image']!='')) {echo '<img style="width:100%;height:auto" src="/uploads'.URL::site($news['image']).'">';}?>
<p><?=$news['content'];?></p>
</div><file_sep><?php defined('SYSPATH') or die('No direct script access.');
abstract class Controller_Admin_Base extends Controller_Base {
public $template = 'admin/admin_template';
}<file_sep><?php defined('SYSPATH') or die('No direct script access.');
class Model_News extends ORM
{
protected $_tableNews = 'news';
}<file_sep><?php defined('SYSPATH') or die('No direct script access.');
class Controller_News extends Controller_Base {
//public $template = 'template';
public function action_index()
{
$id = $this->request->param('id');
//$current_uri= Request::current()->uri();
//var_dump($current_uri);
//$this->template->current_uri = Request::current()->uri();
if ($id) {
$content = View::factory('/pages/news')
->bind('current_uri',$this->current_uri)
->bind('is_admin', $this->is_admin)
->bind('news',$news);
$content->news = $id;
$news = ORM::factory('News',$id)->as_array();
$this->template->page_ctrlr=$this->page_ctrlr;
$this->template->title = ' News'.$id;
}
else
{
$content = View::factory('/pages/all_news')
->bind('news',$news)
->bind('current_uri',$this->current_uri)
->bind('is_admin', $this->is_admin)
// ->bind('totalnews',$totalnews)
/*->bind('page',$page)*/;
$this->template->title = 'All News';
$this->template->page_ctrlr=$this->page_ctrlr;
if (!$this->is_admin) {
$totalnews=ORM::factory('News')->count_all();
$per_page=6;
$offset= $per_page * (($this->request->param('page'))-1);
//var_dump($this->request->param('page'));
$news = ORM::factory('News')->limit($per_page)->offset($offset)->find_all();
$content->pagination = Pagination::factory(array('total_items' => $totalnews, 'items_per_page' => $per_page,));
}
else{
$news = ORM::factory('News')->find_all();
}
}
$this->template->content = $content;
}
public function action_delete()
{
$id = $this->request->param('id');
if ($id)
{
$news = ORM::factory('News',$id)->delete();
$this->redirect(URL::site('admin/news'));
}
}
public function action_edit()
{
$content = View::factory('pages/add_news')
->bind('id', $id)
->bind('page_act', $this->page_act)
->bind('news', $news)
->bind('is_admin', $this->is_admin)
->bind('errors', $errors);
$this->template->title = 'Добавление новости';
$this->template->page_ctrlr=$this->page_ctrlr;
$id = $this->request->param('id');
if ($id)
{
$news=ORM::factory('News',$id);
$errors=$this->_edit_add_common($this->request->post(),$_FILES,$id);
$this->template->content = $content;
}
}
public function action_add()
{
$content = View::factory('pages/add_news')
->bind('page_act', $this->page_act)
->bind('is_admin', $this->is_admin)
->bind('errors', $errors);
$this->template->title = 'Добавление новости';
$this->template->page_ctrlr=$this->page_ctrlr;
$errors=$this->_edit_add_common($this->request->post(),$_FILES);
$this->template->content = $content;
}
protected function _edit_add_common($post_data,$file_data,$id='')
{
if ($post = $post_data) {
$post = Arr::map('trim', $post);
$post_val = Validation::factory($post);
$post_val->rule('news_title', 'not_empty')
->rule('news_title', 'min_length', array(':value', 5))
->rule('news_title', 'max_length', array(':value', 50))
->rule('news_content', 'not_empty')
->rule('news_content', 'min_length', array(':value', 10))
->rule('news_content', 'max_length', array(':value', 1000));
$file_val=Validation::factory($file_data);
$file_val->rule('image', 'Upload::type', array(':value', array('jpg', 'png', 'gif')))//;
->rule('image', 'Upload::size', array(':value', '1M'));
if (($post_val->check())&&($file_val->check())) {
if ($filename=Upload::save($file_data['image'], NULL, $this->uploads_dir()))
{
$filename_arr=explode('/',$filename);
$filename=end($filename_arr);
}
try {
if($id==''){
$newRec = ORM::factory('News');
}
else
{
$newRec = ORM::factory('News',$id);
}
$newRec->title = strip_tags($_POST['news_title']);
$newRec->content = strip_tags($_POST['news_content']);
if ((isset($filename))&&($filename!=FALSE)) {
//var_dump($filename);
//$old_pic=$newRec->image;
if (($newRec->image!=0)&&($newRec->image!=''))
{
$path=$this->uploads_dir();
$path.=$newRec->image;
if (file_exists($path)) {
unset($path);
}
}
$newRec->image = $filename;
}
$newRec->save();
}
catch(ORM_Validation_Exception $e)
{
return $errors = $e->errors('models');
}
Controller::redirect(URL::site('admin/news'));
} else {
$errors = $post_val->errors('comments');
$errors = $file_val->errors('comments');
//var_dump($errors);
return $errors;
}
}
}
private function uploads_dir()
{
return DOCROOT . 'uploads' . DIRECTORY_SEPARATOR;
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<title>Taskwezom - <?=$title;?></title>
<!-- Bootstrap -->
<link href="../../bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<style>
body {
padding-top: 65px;
}
.inside {
background-color: beige;
padding: 2px 50px;
border-radius: 7px;
}
#news{
padding-bottom: 20px;
}
#review{
height: 100px;
width: 400px;
resize: none;
}
form[name=add_review]
{
max-width: 400px;
}
#more
{
margin-bottom: 10px;
}
<?if (($current_uri=='registration')||($current_uri=='login')) {?>
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #eee;
}
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
/* border-bottom-right-radius: 0;
border-bottom-left-radius: 0;*/
width: 100%;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
/* border-top-left-radius: 0;
border-top-right-radius: 0;*/
width: 100%;
}
.form-signin input[type="text"] {
margin-bottom: -1px;
/* border-top-left-radius: 0;
border-top-right-radius: 0;*/
width: 100%;
}
<?}?>
.pagination.pagination-sm li.active a
{
background-color: #5bc0de;
border-color: #46b8da;
color: #fff;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<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="<?php echo URL::site(); ?>">taskwezom</a>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<!--<li <?//if ($current_uri=='/') {?>class="active"<?//}?> ><a href="<?//= URL::site(); ?>">Home</a></li>-->
<li <?if (preg_match('/news/',$current_uri)) {?>class="active"<?}?> ><a href="<?= URL::site('/news');?>"><span class="glyphicon glyphicon-list"> </span> News</a></li>
<li <?if (preg_match('/reviews/',$current_uri)) {?>class="active"<?}?> ><a href="<?= URL::site('/reviews');?>"><span class="glyphicon glyphicon-book"> </span> Guest book</a></li>
<li <?if ($current_uri=='about') {?>class="active"<?}?> ><a href="<?= URL::site('/about');?>" ><span class="glyphicon glyphicon-info-sign"> </span> About</a></li>
<li <?if ($current_uri=='contacts') {?>class="active"<?}?> ><a href="<?= URL::site('/contacts');?>"><span class="glyphicon glyphicon-briefcase"> </span> Contact</a></li>
<? if ($user) {?><li><a href="<?=URL::site('/admin')?>"> <span class="glyphicon glyphicon-cog"> </span> Admin panel</a></li><?}?>
</ul>
<form class="navbar-form navbar-right" method="post" action="<?=URL::site('/login')?>">
<? if (!$user) {?>
<a href="<?=URL::site('/login')?>" class="btn btn-success"><span class="glyphicon glyphicon-log-in"> </span> Sign in</a>
<? } else { ?>
<span class="active" name="logginuser" style="color: snow; padding: 10px 15px;"> <span class="glyphicon glyphicon-user"> </span> <?=$user;?> </span>
<input name="exit" hidden="">
<button class="btn btn-success" type="submit"><span class="glyphicon glyphicon-log-out"> </span> Sign out</button>
<?}?>
</form>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<?=$content?>
<hr>
<?if (($current_uri!='registration')&&($current_uri!='login')) {?>
<footer>
<p>© Company 2015</p>
</footer>
<?}?>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../bootstrap/js/bootstrap.min.js"></script>
</body>
</html><file_sep><? defined('SYSPATH') or die('No direct script access.');
class Controller_Registration extends Controller_Base {
//public $template = 'auth_template';
public function action_index()
{
$content = View::factory('pages/registration_form')
->bind('errors',$errors);
if ($post = $this->request->post())
{
$post = Arr::map('trim', $post);
$post_val = Validation::factory($post);
$post_val -> rule('username', 'not_empty')
-> rule('username', 'min_length', array(':value', 2))
-> rule('username', 'max_length', array(':value', 20))
-> rule('username', 'alpha_numeric', array(':value', FALSE))
-> rule('email', 'not_empty')
-> rule('email', 'email')
-> rule('email', 'max_length', array(':value', 25))
-> rule('password', '<PASSWORD>')
-> rule('password', 'min_length', array(':value', 8))
//-> rule('password_confirm', 'not_empty')
-> rule('password_confirm', 'matches', array(':validation', 'password_confirm', 'password'));
if ($post_val -> check()) {
try {
$user=ORM::factory('User');
$user->create_user($_POST, array('username', 'email', 'password'));
$user->add('roles', ORM::factory('Role', array('name' => 'login')));
mail($post['email'], 'Регистрация на сайте taskwezom.esy.es', 'Вы были зерегестрированы на сайте taskwezom.esy.es, ваш логин: ' . $post['username'] . ' Ваш пароль: ' . $post['password']);
$this->redirect(URL::site('/login'));
} catch (ORM_Validation_Exception $e) {
$errors = $e->errors('models');
}
}
else {
$errors = $post_val->errors('comments');
}
}
// Registration Form
$this->template->title = 'Registration';
$this->template->content = $content;
}
}<file_sep><form class="form-signin" method="post" action="<?=URL::site('/registration')?>">
<?php if(isset($errors['username'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['username'].'</div>'; ?>
<h2 class="form-signin-heading">Sign up form</h2>
<label for="inputEmail" class="sr-only">Name</label>
<input type="text" id="inputName" class="form-control" placeholder="username" required="" name="username" maxlength
="25" autofocus="" value="<?php echo HTML::chars(Arr::get($_POST, 'username')); ?>">
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" name="email" maxlength
="25" value="<?php echo HTML::chars(Arr::get($_POST, 'email')); ?>">
<?php if(isset($errors['email'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['email'].'</div>'; ?>
<label for="inputPassword" class="sr-only">Password</label>
<input type="<PASSWORD>" id="inputPassword" class="form-control" placeholder="<PASSWORD>" maxlength
="15" name="password" required="true">
<?php if(isset($errors['password'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['password'].'</div>'; ?>
<label for="inputPassword" class="sr-only">Password check</label>
<input type="password" id="inputPassword" class="form-control" placeholder="<PASSWORD>" maxlength
="15" name="password_confirm" required="true">
<?php if(isset($errors['password_confirm'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['password_confirm'].'</div>'; ?>
<button class="btn btn-lg btn-success btn-block" type="submit"> <span class="glyphicon glyphicon-plus-sign"> </span> Sign up</button>
<p> or if you have an account you can </p>
<a href="<?=URL::site('/login')?>" class="btn btn-lg btn-primary btn-block" ><span class="glyphicon glyphicon-log-in"> </span> Sign in</a>
</form><file_sep><?php defined('SYSPATH') or die('No direct script access.');
abstract class Controller_Base extends Controller_Template {
public $template = 'template';
public function before()
{
parent::before();
$current_uri = Request::current()->uri();
$this->template->current_uri = $current_uri;
$this->current_uri=$current_uri;
if(Auth::instance()->logged_in()) {
$user=Auth::instance()->get_user()->username;
$lu_email=Auth::instance()->get_user()->email;
$this->template->user = $user;
$this->user=$user;
$this->lu_email=$lu_email;
}
else {
$user= FALSE;
$this->template->user = $user;
}
$is_admin_arr=explode('/',$current_uri);
if ($is_admin_arr[0]=='admin')
{
$this->is_admin='admin';
if (isset($is_admin_arr[2])) {
$this->page_act = $is_admin_arr[2];
}
if (isset($is_admin_arr[1])) {
$this->page_ctrlr = $is_admin_arr[1];
}
else {$this->page_ctrlr='';}
}
else
{
$this->is_admin='';
$this->page_ctrlr=$is_admin_arr[0];
}
$this->template->content = '';
}
}<file_sep><?php defined('SYSPATH') or die('No direct script access.');
class Controller_Reviews extends Controller_Base {
public $template = 'template';
public function action_index()
{
$content = View::factory('pages/reviews')
->bind('reviews', $reviews)
->bind('user',$this->user)
->bind('current_uri',$this->current_uri);
$this->template->title = 'Guest Book';
$this->template->page_ctrlr=$this->page_ctrlr;
if (!$this->is_admin) {
$totalnews=ORM::factory('Review')->count_all();
$per_page=6;
$offset= $per_page * (($this->request->param('page'))-1);
//var_dump($this->request->param('page'));
$reviews = ORM::factory('Review')->limit($per_page)->offset($offset)->find_all();
$content->pagination = Pagination::factory(array('total_items' => $totalnews, 'items_per_page' => $per_page,));
}
else{
$reviews = ORM::factory('Review')->find_all();
}
$this->template->content = $content;
}
public function action_add()
{
$content = View::factory('pages/add_review')
->bind('user',$this->user)
->bind('logged_email', $this->lu_email)
->bind('current_uri',$this->current_uri)
->bind('kapcha',$kapcha)
->bind('is_admin',$is_admin)
->bind('errors',$errors);
$this->template->title = 'Guest Book. Add review';
$kapcha=Captcha::instance('default')->render();
$this->template->page_ctrlr=$this->page_ctrlr;
if($_POST)
{
$_POST = Arr::map('trim', $_POST);
$post = Validation::factory($_POST);
$post -> rule('username', 'not_empty')
-> rule('username', 'min_length', array(':value', 2))
-> rule('username', 'max_length', array(':value', 20))
-> rule('username', 'alpha_numeric', array(':value', FALSE))
-> rule('usermail', 'not_empty')
-> rule('usermail', 'email')
-> rule('review', 'not_empty')
-> rule('review', 'max_length', array(':value', 100))
->rule('kapcha','not_empty');
if(($post -> check()) && (Captcha::valid($_POST['kapcha'])))
{
$newRec=ORM::factory('Review');
$newRec->name = strip_tags($_POST['username']);
$newRec->review = strip_tags($_POST['review']);
$newRec->email = strip_tags($_POST['usermail']);
$newRec->save();
Controller::redirect(URL::site('reviews'));
}
else
{
$errors = $post -> errors('comments');
if ((!Captcha::valid($_POST['kapcha']))&&(!isset($errors['kapcha']))) {
$content->set('kapchaerror', 'captcha is not valid');
}
}
}
$this->template->content = $content;
}
public function action_delete()
{
$id = $this->request->param('id');
if ($id)
{
try{
ORM::factory('Review',$id)->delete();
}
catch(ORM_Validation_Exception $e)
{
$errors = $e->errors('models');
}
$this->redirect(URL::site('admin/reviews'));
}
}
public function action_edit()
{
$is_admin_arr=explode('/',$this->current_uri);
if ($is_admin_arr[0]=='admin')
{
$is_admin='admin';
}
else
{
$is_admin='';
}
//var_dump($is_admin);
$id = $this->request->param('id');
$content = View::factory('pages/add_review')
->bind('is_admin',$is_admin)
->bind('id',$id)
->bind('review',$review)
->bind('errors',$errors);
$this->template->title = 'Edit review '.$id;
$this->template->page_ctrlr=$this->page_ctrlr;
if ($id)
{
$review=ORM::factory('Review',$id);
if ($post = $this->request->post()) {
$post = Arr::map('trim', $post);
$post_val = Validation::factory($post);
$post_val->rule('username', 'not_empty')
->rule('username', 'min_length', array(':value', 2))
->rule('username', 'max_length', array(':value', 20))
->rule('username', 'alpha_numeric', array(':value', FALSE))
->rule('review', 'not_empty')
->rule('review', 'max_length', array(':value', 100));
if ($post_val->check()) {
try {
$review = ORM::factory('Review', $id);
$review->name = strip_tags($post['username']);
$review->review = strip_tags($post['review']);
$review->save();
} catch (ORM_Validation_Exception $e) {
$errors = $e->errors('models');
}
$this->redirect(URL::site('admin/reviews'));
} else {
$errors = $post_val->errors('comments');
}
}
$this->template->content=$content;
}
}
}<file_sep><?php defined('SYSPATH') or die('No direct script access.');
class Controller_Login extends Controller_Base
{
public function action_index()
{
$this->template->title='Login';
$content=View::factory('pages/form_login')
->bind('error',$error)
->bind('title',$title);
if ($post = $this->request->post())
{
if (isset($post['exit']))
{
Auth::instance()->logout();
$this->redirect(URL::base(true));
}
$user = ORM::factory('User');
$success = Auth::instance()->login($post['username'],$post['password']);
if($success)
{
$this->redirect(URL::site('/admin'));
}
else
{
$error='Fail to log in';
echo $success;
$this->template->content = $content;
}
if (Auth::instance()->logged_in())
{
$this->redirect(URL::site('/admin'));
}
} else {
$this->template->content = $content;
}
}
}<file_sep><h3><?if ($is_admin) {?>Редактирование отзыва #<?=$id?><?} else {?>Добавление отзыва<?}?>
<a class="btn pull-right btn-large btn-info" href="<?
//if ($is_admin)
echo URL::site($is_admin.'/reviews');
?>"><span class="glyphicon glyphicon-list-alt"> </span> Вернуться к отзывам</a>
</h3>
<?//print_r($_POST);?>
<?//if (isset($errors)) print_r($errors);?>
<form action="<? if ($is_admin){ echo URL::site('admin/reviews/edit/'.$review->id);} else {echo URL::site('/reviews/add');}?>" method="POST" name="add_review">
<div class="form-group">
<label for="username">Ваше имя *</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Введите имя" maxlength="30"
value="<?if (isset($_POST['username'])){ echo HTML::chars(Arr::get($_POST, 'username')); } else if (isset($review->name)){ echo $review->name; } else if (isset($user)) { echo $user;}?>">
<?php if(isset($errors['username'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['username'].'</div>'; ?>
</div>
<div class="form-group">
<label for="usermail">Ваше Email address *</label>
<input type="email" class="form-control" id="usermail" name="usermail" placeholder="Введите email" maxlength
="30" value="<?if (isset($_POST['usermail'])){echo HTML::chars(Arr::get($_POST, 'usermail'));} else if (isset($review->email)){ echo $review->email; } else if (isset($logged_email)){ echo $logged_email;} ?>" >
<?php if(isset($errors['usermail'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['usermail'].'</div>'; ?>
</div>
<div class="form-group">
<label for="review">Ваш отзыв *</label>
<textarea class="form-control" id="review" name="review" placeholder="Введите Ваш отзыв" maxlength="100"
><?if (isset($_POST['review'])){ echo HTML::chars(Arr::get($_POST, 'review'));} else if (isset($review->review)){ echo $review->review; } ?></textarea>
<?php if(isset($errors['review'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['review'].'</div>'; ?>
</div>
<?if (!$is_admin){?>
<div class="form-group">
<label for="kapchaw">Подтвердите что Вы не робот)</label>
<p>
<?=$kapcha;?>
<!--<img src = "<?//=$kapcha;?>" />-->
<input class="form-inline" type = "text" id="kapcha" name = "kapcha" ></p>
<?php if(isset($errors['kapcha'])) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$errors['kapcha'].'</div>'; ?>
<?php if(isset($kapchaerror)) echo '<div class="alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"> </span> '.$kapchaerror.'</div>'; ?>
</div>
<?}?>
<br>
<button class="btn btn-large btn-success" type="submit"><?if (!$is_admin){?><span class="glyphicon glyphicon-send"> </span> Отправить <?}
else {?><span class="glyphicon glyphicon-floppy-disk"> </span> Сохранить<?}?></button> <a href="<?= URL::site($is_admin.'/reviews');?>" class="btn btn-large btn-danger" ><span class="glyphicon glyphicon-remove"> </span> Отмена</a>
</form>
<file_sep><h3>Гостевая книга
<? if ($current_uri!='admin/reviews') {?>
<a class="btn pull-right btn-large btn-success" href="<?= URL::site('/reviews/add');?>"> <span class="glyphicon glyphicon-plus" aria-hidden="true"> </span> Добавить отзыв</a>
<?}?>
</h3>
<br>
<div class="row">
<?foreach ($reviews as $r) {
$r=$r->as_array();
?>
<div class="col-sm-6">
<div class="panel panel-warning">
<div class="panel-heading">
<!--<div class="inside">-->
<?if (($user)&&($current_uri=='admin/reviews')){?>
<span class="pull-right"><a class="btn btn-success" href="<?= URL::site('admin/reviews/edit/'. $r['id']); ?>" title="Edit"><span class="glyphicon glyphicon-edit"> </span></a> <a class="btn btn-danger" href="<?= URL::site('admin/reviews/delete/'. $r['id']); ?>" title="Delete"><span class="glyphicon glyphicon-trash"> </span></a></span>
<?}?>
<p><strong><?=$r['name']?> (<?=$r['update_time']?>)</strong></p>
</div>
<div class="panel-body">
<p><strong><?=$r['review']?></strong></p>
</div>
</div>
</div>
<?}?>
</div>
<p><? if (isset ($pagination))echo $pagination; ?></p><file_sep><?php defined('SYSPATH') or die('No direct script access.');
class Controller_Static extends Controller_Base {
public function action_index()
{
$content = View::factory('pages/home');
$this->template->title = 'Home page';
$this->template->description = 'Home page';
$this->template->content = $content;
}
public function action_about()
{
$content = View::factory('pages/about');
$this->template->title = 'About';
$this->template->description = 'Страница о сайте';
$this->template->content = $content;
}
public function action_contacts()
{
$content = View::factory('pages/contacts');
$this->template->title = 'Contacts';
$this->template->description = 'Страница для связи со мной';
$this->template->content = $content;
}
} | e31181bc691c29b735dede6700ddfdf4fd581282 | [
"PHP"
] | 23 | PHP | eidicon/taskwezom | a37a73c0bad0376608423fb8cf0d294194fa7313 | cb0c519d445e31d5c91c78a34b1695900689296b |
refs/heads/master | <repo_name>tsyrya/appercode<file_sep>/src/services/auth.js
import {http} from '../services/request'
import {router} from '../router'
import toastr from 'toastr'
export default {
login(userName, password, redirect = null) {
http.post('login', {username: userName, password: <PASSWORD>, generateRefreshToken: true},({ data }) => {
localStorage.setItem('jwt-token', data.sessionId)
localStorage.setItem('jwt-refresh-token', data.refreshToken)
if (redirect) {
router.push(redirect)
}
}, error => {
var status = error.response.status;
if (status == 401){
toastr.error('Credentials are not valid')
}
})
},
checkAuth() {
var jwt = localStorage.getItem('jwt-token')
return jwt ? true : false
},
logout() {
localStorage.removeItem('jwt-token')
localStorage.removeItem('jwt-refresh-token')
router.push('/login')
},
}
<file_sep>/src/main.js
import Vue from 'vue'
import App from './App'
import {router} from './router'
import VueResource from 'vue-resource'
import VeeValidate from 'vee-validate'
import {http} from './services/request'
Vue.config.productionTip = false
Vue.use(VueResource)
Vue.use(VeeValidate)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
created() {
http.init();
},
components: { App }
})
| d77859d15e77bf8ef9533ca882df71f671c8067a | [
"JavaScript"
] | 2 | JavaScript | tsyrya/appercode | 86967f994d9e134e185d2a16f8a7577cad7ad3e2 | 79e229e88ff290d06c7f0db9265d80717cac2ae0 |
refs/heads/master | <repo_name>bacongravy/giphy-anywhere<file_sep>/test/app_tests.swift
import XCTest
class GIPHY_Anywhere_UI_Tests: XCTestCase {
override func setUp() {
continueAfterFailure = false
XCUIApplication().launch()
}
override func tearDown() {
}
func testInitialState() {
XCUIApplication().activate()
let menuBarsQuery = XCUIApplication().menuBars
XCTAssert(menuBarsQuery.menuItems["Copy GIF URL"].isEnabled == false)
XCTAssert(menuBarsQuery.menuItems["Copy GIF URL (GitHub Markdown)"].isEnabled == false)
let quitItem = menuBarsQuery.menuItems["Quit"]
XCTAssert(quitItem.isEnabled == true)
quitItem.click()
}
}
<file_sep>/DEVELOPMENT.md
# Development
This project is configured to use [GitHub Actions](https://github.com/features/actions) for continuous integration and deployment. The project is rebuilt on every commit and a signed, notarized disk image is published as a GitHub release on every tag. After the app is pubished, a cask in a Homebrew tap is updated to point to the new version.
## CI integration
Secrets for signing, notarizing, and deploying must be set in order for the workflow to run successfully.
### Signing
1. Create and download a Developer ID certificate from developer.apple.com
1. Install the .cer file in Keychain Access
1. Find the certificate and private key in Keychain Access and export them in .p12 format
1. Set a password for the p12 file
1. Base64-encode the p12 file: `base64 -i Certificates.p12`
1. Set the SIGNING_CERTIFICATE_P12_DATA secret with the data
1. Set the SIGNING_CERTIFICATE_PASSWORD secret with the password
### Notarizing
1. Generate an [application specific password](https://support.apple.com/en-us/HT204397) for your developer account
1. Set the NOTARIZE_USERNAME secret to your developer account username
1. Set the NOTARIZE_PASSWORD secret to the generated application specific password
### Deploying
1. Generate a GitHub OAuth token that has access to a Homebrew tap repository
1. Set the CASK_REPO secret to the name of the tap repository (e.g. `bacongravy/homebrew-tap`)
1. Set the CASK_REPO_TOKEN secret to the generated OAuth token
<file_sep>/app/main.swift
MainController.run()
<file_sep>/helper/main.swift
#!/usr/bin/swift
import Foundation
import Cocoa
let runningApps = NSWorkspace.shared.runningApplications
let isRunning = runningApps.contains {
$0.bundleIdentifier == "net.bacongravy.giphy-anywhere"
}
if !isRunning {
var path = Bundle.main.bundlePath as NSString
for _ in 1...4 {
path = path.deletingLastPathComponent as NSString
}
NSWorkspace.shared.launchApplication(path as String)
}
<file_sep>/app/ServiceManagement.swift
import CoreFoundation
import ServiceManagement
func setLoginItem(enabled: Bool) {
SMLoginItemSetEnabled("net.bacongravy.giphy-anywhere-helper" as CFString, enabled)
}
<file_sep>/app/MainController.swift
import Cocoa
import WebKit
let GIPHY_BASE_URL = "https://giphy.com/"
let GIPHY_TRENDING_GIFS_URL = "https://giphy.com/trending-gifs/"
let GIPHY_FAVICON_URL = "https://giphy.com/favicon.ico"
let GIPHY_GIF_IDENTIFIER_REGEX = "^https://giphy.com/gifs/(.*-)?([^-\n]+)$"
let GIPHY_GIF_URL_PREFIX = "https://media.giphy.com/media/"
let GIPHY_GIF_URL_SUFFIX = "/giphy.gif"
let MARKDOWN_PREFIX = ""
let IPHONE_USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Mobile/15E148 Safari/604.1"
let STATUS_ITEM_TITLE = "GIPHY Anywhere"
let COPY_URL_MENU_ITEM_TITLE = "Copy GIF URL"
let COPY_MARKDOWN_MENU_ITEM_TITLE = "Copy GIF URL (GitHub Markdown)"
let QUIT_MENU_ITEM_TITLE = "Quit"
let URL_KEY_PATH = "URL"
func gifIdentifier(url: URL?) -> String? {
return url?.absoluteString.matchingStrings(regex: GIPHY_GIF_IDENTIFIER_REGEX).first?[2]
}
func gifURL(url: URL?) -> String? {
guard let identifier = gifIdentifier(url: url) else { return nil }
return GIPHY_GIF_URL_PREFIX + identifier + GIPHY_GIF_URL_SUFFIX
}
func gifMarkdown(url: URL?) -> String? {
guard let url = gifURL(url: url) else { return nil }
return MARKDOWN_PREFIX + url + MARKDOWN_SUFFIX
}
func getGiphyImage() -> NSImage {
return NSImage.init(byReferencing: URL.init(string: GIPHY_FAVICON_URL)!)
}
func getiPhoneWebView() -> WKWebView {
let webViewRect = NSMakeRect(0, 0, 360, 640)
let webViewConf = WKWebViewConfiguration.init()
webViewConf.preferences.plugInsEnabled = true
let webView = WKWebView.init(frame: webViewRect, configuration: webViewConf)
webView.customUserAgent = IPHONE_USER_AGENT
return webView
}
func setPasteboard(string: String?) {
guard let string = string else { NSSound.beep(); return }
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(string, forType: .string)
}
class MainController: NSObject, NSApplicationDelegate, WKNavigationDelegate {
class func run() {
let app = NSApplication.shared
let mainController = MainController.init()
app.delegate = mainController
app.run()
}
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
let statusMenu = NSMenu.init()
let url = URL.init(string: GIPHY_TRENDING_GIFS_URL)!
let webView = getiPhoneWebView()
let webViewItem = NSMenuItem.init()
let copyURLItem = NSMenuItem.init()
let copyMarkdownItem = NSMenuItem.init()
let quitItem = NSMenuItem.init()
override init() {
super.init()
setLoginItem(enabled: true)
setupStatusItem()
setupStatusMenu()
setupWebView()
}
func setupStatusItem() {
let giphyImage = getGiphyImage()
giphyImage.isValid ?
(statusItem.button?.image = giphyImage) :
(statusItem.button?.title = STATUS_ITEM_TITLE)
statusItem.button?.target = self
statusItem.button?.action = #selector(MainController.statusItemClicked(_:))
statusItem.button?.highlight(false)
}
func setupStatusMenu() {
webViewItem.view = webView
copyURLItem.title = COPY_URL_MENU_ITEM_TITLE
copyURLItem.target = self
copyURLItem.action = #selector(MainController.copyURL(_:))
copyMarkdownItem.title = COPY_MARKDOWN_MENU_ITEM_TITLE
copyMarkdownItem.target = self
copyMarkdownItem.action = #selector(MainController.copyMarkdown(_:))
quitItem.title = QUIT_MENU_ITEM_TITLE
quitItem.target = self
quitItem.action = #selector(MainController.quit(_:))
statusMenu.addItem(webViewItem)
statusMenu.addItem(NSMenuItem.separator())
statusMenu.addItem(copyURLItem)
statusMenu.addItem(copyMarkdownItem)
statusMenu.addItem(NSMenuItem.separator())
statusMenu.addItem(quitItem)
}
func setupWebView() {
webView.navigationDelegate = self
webView.addObserver(self, forKeyPath: URL_KEY_PATH, options: .new, context: nil)
reloadWebView()
}
func reloadWebView() {
webView.load(URLRequest.init(url: url))
}
func hideUseOurAppButton() {
webView.evaluateJavaScript("""
var aTags = document.getElementsByTagName('a');
var searchText = 'Use Our App';
var foundElement;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].textContent == searchText) {
foundElement = aTags[i];
break;
}
}
if (foundElement) {
foundElement.style = "display: none;";
}
"""
) { (_, _) in }
}
func popUpStatusItem() {
statusItem.menu = statusMenu
statusItem.button?.performClick(self)
statusItem.menu = nil
}
func applicationDidBecomeActive(_ notification: Notification) {
popUpStatusItem()
}
@objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
switch menuItem.action {
case #selector(MainController.copyURL(_:)),
#selector(MainController.copyMarkdown(_:)):
return gifIdentifier(url: webView.url) != nil
default:
return true
}
}
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
switch keyPath {
case URL_KEY_PATH:
switch webView.url?.absoluteString {
case GIPHY_BASE_URL:
reloadWebView()
default:
let enabled = gifIdentifier(url: webView.url) != nil
copyURLItem.isEnabled = enabled
copyMarkdownItem.isEnabled = enabled
}
hideUseOurAppButton()
default: break
}
}
@objc func webView(_ webView: WKWebView,
didFinish navigation: WKNavigation!) {
hideUseOurAppButton()
}
@objc func statusItemClicked(_ sender: AnyObject) {
NSApp.isActive ?
popUpStatusItem() : NSApp.activate(ignoringOtherApps: true)
}
@objc func copyURL(_ sender: AnyObject) {
setPasteboard(string: gifURL(url: webView.url))
}
@objc func copyMarkdown(_ sender: AnyObject) {
setPasteboard(string: gifMarkdown(url: webView.url))
}
@objc func quit(_ sender: AnyObject) {
setLoginItem(enabled: false)
NSApp.terminate(sender)
}
}
<file_sep>/app/String.swift
import Foundation
// from https://stackoverflow.com/a/40040472/5829298
extension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.range(at: $0).location != NSNotFound
? nsString.substring(with: result.range(at: $0))
: ""
}
}
}
}
<file_sep>/README.md
# GIPHY Anywhere
Sometimes you're composing a chat message or commenting on a pull request, and the need to insert a gif strikes, but opening a new browser window would totally break your flow. *GIPHY Anywhere* to the rescue!
*GIPHY Anywhere* is a status bar item which allows you to quickly browse GIPHY for gifs.
<p align=center>
<img src="https://raw.githubusercontent.com/bacongravy/giphy-anywhere/images/screenshot.gif">
</p>
## Installation
*GIPHY Anywhere* requires macOS, and is installed using [Homebrew](https://brew.sh):
```bash
brew cask install bacongravy/tap/giphy-anywhere
```
Open *GIPHY Anywhere* and the GIPHY icon will appear in the system menu bar. It will remain there across logouts and restarts until the status bar item is quit.
## Usage
Whenever the urge to gif strikes, open *GIPHY Anywhere* by clicking on the GIPHY icon in the system menu bar, search or browse for a gif to fit your mood, and then copy the URL of the found gif using one of the menu items. You can copy either the plain URL, ready for sending in a chat message, or the URL wrapped in Markdown, ready for insertion in a GitHub comment. Once you've copied, just paste and go.
## Acknowledgements
Huge thanks to GIPHY for providing a great service. This project is not affiliated with GIPHY in any way.
This project was inspired by https://github.com/cknadler/vim-anywhere, and by the rich gif culture at my place of work.
## Why?
I use the GIPHY keyboard on iOS every day, and I miss it whenever I'm using macOS. Seeing *vim-anywhere* on *Hacker News* gave me the motivation to solve my problem in a similar way. After prototyping a solution using an Automator workflow service and gathering feedback, I rewrote the project as a JavaScript for Automation (JXA) applet to provide a more reliable and consistent user experience across applications. When JXA stopped working in Mojave, I rewrote the project in Swift 4.
| 68cf9da80fd0bc88365cd726d925f99772391879 | [
"Swift",
"Markdown"
] | 8 | Swift | bacongravy/giphy-anywhere | 8a20b9431dfa94c88c62b0fbd17d059745534eed | 5ad4a5c6fe8c3fd46ac6fbba6cabff6519b13779 |
refs/heads/master | <file_sep><?php
namespace Engage\EagleEyeService;
class Reward
{
protected $api;
protected $key;
public function setBrand($identifier, $credentials)
{
$credentials = $credentials[$identifier];
$auth = new Auth($credentials['username'], $credentials['password']);
$this->key = $credentials['key'];
$this->api = new Client($auth);
}
public function sendWalletReward($wallet, $campaignName)
{
$data = [
'pushMessage' => [
'campaignName' => $campaignName,
'title' => null,
'message' => $wallet['message'],
'data' => [
'screen' => 'WALLET',
'screenTitle' => '',
'resource' => $wallet['key'],
]
],
'segments' => [
[
'segmentType' => 'MATCHING',
'lower' => $wallet['email']
]
],
];
$params = [
'accountKey' => $this->key,
'sendPush' => 'true'
];
return $this->api->post('https://api.podifi.com/qualifi/report/consumer', $data, $params);
}
}
<file_sep><?php
namespace Engage\EagleEyeService;
use GuzzleHttp\Client as HttpClient;
class Client
{
protected $base;
protected $options;
protected $methods = ['GET', 'POST'];
protected $auth;
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
public function get()
{
return $this->request('GET', $endpoint);
}
public function post($endpoint, $payload = [], $queryParams = [])
{
return $this->request('POST', $endpoint, $payload, $queryParams);
}
protected function request($method, $endpoint, $payload = [], $queryParams = [])
{
if (!in_array($method, $this->methods))
{
throw new EagleEyeException($method . ' is not a valid method [Use: ' . implode(', ', $this->methods) . ']');
}
$client = $this->getHttpClient();
if ($method == 'POST')
{
$this->setJsonBody($payload);
}
if ($queryParams)
{
$this->setQueryParameters($queryParams);
}
$this->setHeaders();
$this->setAuthentication();
return $client->request($method, $endpoint, $this->options);
}
protected function getHttpClient()
{
return new HttpClient([
'base_uri' => $this->base,
]);
}
protected function setHeaders()
{
$this->options['headers'] = [
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/json'
];
}
protected function setAuthentication()
{
$this->options['auth'] = $this->auth->getAuth();
}
protected function setQueryParameters($queryParams)
{
$this->options['query'] = $queryParams;
}
protected function setJsonBody($payload)
{
$this->options['body'] = json_encode($payload);
}
}
<file_sep><?php
namespace Engage\EagleEyeService;
class Auth
{
protected $username;
protected $password;
public function __construct($username, $password)
{
$this->setUsername($username);
$this->setPassword($password);
}
public function setUsername($username)
{
$this->username = $username;
}
public function setPassword($password)
{
$this->password = $<PASSWORD>;
}
public function getAuth()
{
return [
$this->username,
$this->password,
];
}
}
<file_sep><?php
namespace Engage\EagleEyeService;
use Exception;
class EagleEyeException extends Exception
{
//
}
<file_sep># eagle-eye-service | 12b1aadeed93c85753e129a4a2bf971c9d850913 | [
"Markdown",
"PHP"
] | 5 | PHP | engageinteractive/eagle-eye-service | 5402e5d5ba9c24a4dc62266d133cb87a471991be | b75639e60520c7c3d132978c8479bd076f84c024 |
refs/heads/main | <repo_name>SiyanGuo/zookeeper<file_sep>/README.md
# zookeepr
week 11 module projects
<file_sep>/routes/apiRoutes/animalRoutes.js
//start an instance of Router
const router = require('express').Router();
const {filterByQuery, findById, createNewAnimal, validateAnimal} = require('../../lib/animals');
const {animals} = require ('../../data/animals');
//create data using POST route
//remove api/ from url & change app.post to router.get
router.post('/animals', (req, res) => {
//req.body is where our incoming content will be
//set id based on what the next index of the array will be
req.body.id = animals.length.toString();
//if any data in req.body is incorrect, send 400 error back
if (!validateAnimal(req.body)) {
//where to find send msg????
res.status(400).send('The animal is not properly formatted.')
} else {
//add animal to JSON file
const animal = createNewAnimal(req.body, animals);
//sending JS obj in JSON format (response)
res.json(animal);
}
});
//handle requests for animals
router.get('/animals', (req, res) => {
let results = animals;
if (req.query) {
results = filterByQuery(req.query, results);
console.log('req.query',req.query);
}
res.json(results);
});
//handle requests for a specific animal
router.get('/animals/:id', (req, res) => {
console.log('req.params',req.params);
const result = findById(req.params.id, animals);
if (result) {
res.json(result);
} else {
res.sendStatus(404)
}
});
module.exports = router; | 20763ef14502b274473f4d35c2be935d6f309294 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | SiyanGuo/zookeeper | 55967bc8df829a75714e361ca7621b95a25fe0c3 | 8a8a5e95927aafb4182aa9d150ddbf105f420393 |
refs/heads/master | <repo_name>Gardiano/object.js<file_sep>/README.md
# object.js
orientação a objetos - javascript puro.
<file_sep>/scripts.js
// Orientação a objetos;
function Funcionario() {
this.nome = ''
this.salario = null;
this.horaExtra = null;
this.ValorHoraExtra = null;
this.Parcela13 = null;
this.salarioTotal = null;
}
// criando novo objeto apartir do metodo 'new' operator;
var funcionario1 = new Funcionario();
funcionario1.nome = 'Paulo'
funcionario1.salario = 1000;
funcionario1.horaExtra = 12;
funcionario1.ValorHoraExtra = 20;
funcionario1.Parcela13 = 2200;
funcionario1.salarioTotal = null;
var funcionario2 = new Funcionario();
funcionario2.nome = 'Gardiano'
funcionario2.salario = 15000;
funcionario2.horaExtra = 25;
funcionario2.ValorHoraExtra = 20;
funcionario2.Parcela13 = 3000;
funcionario2.salarioTotal = null;
function calcularSalarioTotal(funcionario1,funcionario2){
funcionario1.salarioTotal = funcionario1.salario + (funcionario1.horaExtra * funcionario1.ValorHoraExtra);
funcionario2.salarioTotal = funcionario2.salario + (funcionario2.horaExtra * funcionario2.ValorHoraExtra);
console.log('Funcionario: '+ funcionario1.nome + ', Salário Total: ' + funcionario1.salarioTotal +' Reais');
console.log('Funcionario: '+ funcionario2.nome + ', Salário Total: ' + funcionario2.salarioTotal +' Reais');
if(funcionario1.salarioTotal >= funcionario2.salarioTotal) {
console.log('Salário de: '+funcionario1.nome+', ' + funcionario1.salarioTotal+'R$,' + ' salario de ' +funcionario1.nome +' é maior que salario de: '+ funcionario2.nome +' ' + funcionario2.salarioTotal+'R$')
}
if (funcionario1.salarioTotal <= funcionario2.salarioTotal) {
console.log('Salário de: '+funcionario1.nome+', ' + funcionario1.salarioTotal+'R$,' + ' salario de ' +funcionario1.nome +' é menor que salario de: '+ funcionario2.nome +' ' + funcionario2.salarioTotal+'R$')
}
}
| 145b5ef1fecfcb54101b2f5fe637d1441404812f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Gardiano/object.js | 436aadc3fa2c43f1ef9b487d841752b823199b94 | b9b08471b7d295d96c3df00ffd813eef87c0a46e |
refs/heads/master | <file_sep>package rockwell.tasks;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
public class GenerateDashboard
{
public static StringBuffer htmlReport = new StringBuffer("<!DOCTYPE html><html><head><title> Result Dashboard</title><body bgcolor=\"#E7E7E7\"><meta name=\"viewport\" content=\"width=device-width, initial-scale= 1\">" +
"<style>.collapsible { background-color:#4B515D ; box-shadow: 5px 10px 18px #263238; font-family: Arial, Helvetica, sans-serif; color: white; cursor: pointer; padding:8px; width: 97%; border-style: groove; height: 20px; border-radius: 1px; text-align: left; outline: none; font-size: 15px;" +
"}"+
".active, .collapsible:hover { background-color:#263238;}"+
".content {padding: 0 10px; width: 96%; max-height: 0; font-family: Arial, Helvetica, sans-serif; font-size: 13px; overflow: auto; border-radius: 1px; border-style: inset; resize: both; border-width: 1px; transition: max-height 1s ease-out;background-color: #A1A1A1;}"+ "mark {" +
" background-color: #4B515D;" +
" color: black;" +
"body {" +
" margin: 0;" +
"}"+
"}"+ "header {" +
" background-color: #4B515D;" +
" position: inherit;" +
" left: 0;" +
" top: 0;" +
" padding: 5px;" +
" width: 100%;" +
" height: 40px;"+
" text-align: center;" +
" font-size: 12px;" +
" color: white;" +
"}"+
".footer {" +
" position: fixed;" +
" left: 0;" +
" bottom: 0;" +
" width: 100%;" +
" background-color: #000000;" +
" color: white;" +
" height: 35px;"+
" text-align: center;" +
"}"
+"a {" +
"color: white;"+
//"target:_blank;"+
"text-decoration: none;"+
"}" +
"a:hover {" +
" color: #000000;" +
"}"
+ "}"+
"nav {" +
" float: left; /* for the Collaps */" +
" width: 40%;" +
// " height: 550px;"+
" padding: 8px;" +
" border-style: groove;"+
" text-align: left;" +
" border-radius: 8px;"+
" box-shadow: 5px 10px 18px #888888;"+
" font-family: Arial, Helvetica, sans-serif;"+
" font-size: 13px;"+
"}" +
".nav4 {" +
" float: left;/* for the DIF file */" +
" position: relative;"+
" width: 40%;" +
" padding: 8px;" +
//" top: 50px;"+
" text-align: left;" +
"}"+
".nav6 {" +
" float: left;/* for the SUC file */" +
" position: relative;"+
" width: 40%;" +
" padding: 8px;" +
" text-align: left;" +
"}"+
".nav1{" +
" float: right;" +
" box-shadow: 5px 10px 18px #263238;"+
" width: 24.0%;" +
" height: 150px; /* for the total test test case om right side */\r\n" +
" background: #4B515D;" +
" padding: 10px;" +
" border-radius: 1px;"+
" border-style: groove;"+
" text-align: left;" +
" color: white;"+
" margin-top: 10px;" +
" margin-right: 5px;" +
" font-family: Arial, Helvetica, sans-serif;"+
" font-size: 15px;"+
"}"+
".nav2{" +
" float: right;" +
" width: 50.5%;" +
" height: 426px; /* for the total test test case om right side and chart */\r\n" +
" background: #ffffff;" +
" padding: 5px;" +
" border-radius: 1px;"+
" border-style: groove;"+
" box-shadow: 5px 10px 18px #263238;"+
" margin-top: 1%;" +
"}"+
".nav3{" +
" float: right;" +
" width: 35%;" +
" height: 20px; /* for the total test test case om right side */\r\n" +
" background: #ccc;" +
" padding: 5px;" +
" border-radius: 1px;"+
" border-style: groove;"+
"}"+
".nav5{"+
" left: 0;" +
" width: 40%;" +
" height: 25px; /* For the file inside suite */" +
" padding: 0px;"+
" background: #FF6D64;"+
" border-style: groove;"+
"}"+
".ul1 {" +
" list-style-type: none; /* for the total pass and fail test case sutite wise */" +
" margin: 0;" +
" padding: 0;" +
" border-style: groove;"+
" background-color: #616161;" +
"}"+
".li1 {" +
" /* for the total pass and fail test case sutite wise */" +
" color: white;" +
" text-align: center;" +
" padding: 0px;" +
" text-decoration: none;" +
" border-width: 0.5px;"+
" border-style: hidden;"+
" height: 15px;"+
"}"+
"#overflowTest {" +
" padding: 1%;" +
" position: relative;"+
" width: auto;" +
" height: -webkit-fill-available;" +
" overflow: auto;" +
" color: #FF7835;" +
//" resize: vertical;"+
"}"+
".div1{"+
" margin-top: 0px;" +
//" margin-bottom: 65px;" +
" /* For the file inside suite */" +
"}"+
".button {\r\n" +
" background-color: #CE0000;" +
" float: right;" +
" border: none;" +
" color: white;" +
" padding: 7px 20px;" +
" text-align: center;" +
" text-decoration: none;" +
" display: inline-block;" +
" font-size: 10px;" +
" width: 15%;" +
"}"+
".button1 {" +
" background-color: #01579b;" +
" width: 15%;" +
" float: right;" +
" border: none;"+
" color: white;" +
" padding: 7px 20px;" +
" text-align: center;" +
" text-decoration: none;" +
" display: inline-block;" +
" font-size: 10px;" +
"}"+
".button4 {" +
" background-color: #9033ff ;" +
" width: 15%;" +
" float: right;" +
" border: none;" +
" color: white;n" +
" padding: 7px 20px;" +
" text-align: center;" +
" text-decoration: none;" +
" display: inline-block;" +
" font-size: 10px;"+
" height: 25px;" +
" }"+
".button3 {" +
" background-color: #ff8d33;" +
" width: 15%;" +
" float: right;" +
" border: none;" +
" color: white;n" +
" padding: 7px 20px;" +
" text-align: center;" +
" text-decoration: none;" +
" display: inline-block;" +
" font-size: 10px;"+
" height: 25px;" +
" }"+
".button2 {" +
" background-color: #007B1D;" +
" width: 15%;" +
" float: right;" +
" border: none;" +
" color: white;n" +
" padding: 7px 20px;" +
" text-align: center;" +
" text-decoration: none;" +
" display: inline-block;" +
" font-size: 10px;"+
" height: 25px;" +
" }"+
".tooltip {" +
" position: relative;" +
" display: inline-block;" +
"}"+
".tooltip .tooltiptext {" +
" visibility: hidden;" +
" width: 310px;" +
//" height: 2000%"+
" background-color: #FFFFFF;" +
" color: #fff;" +
" text-align: center;" +
" border-radius: 6px;" +
" padding: 5px 0;\r\n" +
" /* Position the tooltip */" +
" position: absolute;" +
" z-index: 5;" +
"}" +
".tooltip:hover .tooltiptext {" +
" visibility: visible;" +
"}"+
"</style></body></head><body><header><h2><p><mark><font color=\"red\">ROCKWELL</font><font color=\"#B3B3B3\">AUTOMATION</font></mark></h2></header>");
//+ "<div class=\"footer\"><p>Report V2.1</p></div>");
static BufferedWriter bw;
// Start of AutomationTestReport()
static void AutomationTestReport(File[] arr,int index,int level) throws IOException
{
GenerateDashboard dv = new GenerateDashboard();
//String SuiteName = null;
// terminate condition
if(index == arr.length) {
return;
}
// tabs for internal levels
for (int i = 0; i <= level; i++)
System.out.print("\t");
htmlReport.append("<nav><div class=\"content\" >");
htmlReport.append("\t");
htmlReport.append("<script> var coll = document.getElementsByClassName(\"collapsible\");");
htmlReport.append("var i;for (i = 0; i < coll.length; i++) { coll[i].addEventListener(\"click\", function() { this.classList.toggle(\"active\"); var content = this.nextElementSibling; if (content.style.maxHeight){");
htmlReport.append("content.style.maxHeight = null; } else { content.style.maxHeight = content.scrollHeight + \"px\"; } });}</script>");
htmlReport.append("");
htmlReport.append("</body></html>");
dv.writeToReport(maindirpath);
//dv.closeReport();
// for Test files in side suite
if(arr[index].isFile()) {
//For console output
//System.out.println(arr[index].getName());
//Append on HTML page for report
String ext = null;
int i = arr[index].getName().lastIndexOf('.');
if (i > 0) {
ext = arr[index].getName().substring(i + 1);
//System.out.println("EXT-----------------"+ ext);
}
htmlReport.append("</nav>");
htmlReport.append("<a id=\"my_link3\" href=" + dv.getRelativePath(arr[index].toString()) + " \ttarget=\"_blank\" >");
// if(arr[index].getName().startsWith("ftaDataView") && ext.equalsIgnoreCase("log") )
//SuiteName=arr[index].getName();
//System.out.println("File name for dif extension*********************"+ SuiteName);
if (ext.equalsIgnoreCase("log"))
htmlReport.append("<nav>" + arr[index].getName() + "<button class=\"button1\">Log</button></nav>");
//htmlReport.append("<nav><nav class=\"tooltip\">"+ arr[index].getName()+ "<span class=\"tooltiptext\" ><iframe src="+arr[index].toString()+"></iframe></span></nav><button class=\"button1\">Log</button></nav>");
if (ext.equalsIgnoreCase("dif"))
//System.out.println("File name for dif extension*********************"+ arr[index].getName());
htmlReport.append("<nav><nav class=\"tooltip\"><font color=\"#CE0000\">" + arr[index].getName() + "</font><span class=\"tooltiptext\" ><iframe src=file:///" + arr[index].toString() + "></iframe></span></nav><button class=\"button\">Fail Test</button></nav>");
if(ext.equalsIgnoreCase("suc"))
htmlReport.append("<nav>"+ arr[index].getName()+ "<button class=\"button2\">Passed Test</button></nav>");
//htmlReport.append("<nav><nav class=\"tooltip\">"+ arr[index].getName()+ "<span class=\"tooltiptext\" ><iframe src=file:///"+arr[index].toString()+"></iframe></span></nav><button class=\"button2\">Passed Test</button></nav>");
if(ext.equalsIgnoreCase("png"))file:///
htmlReport.append("<nav>" + arr[index].getName() + "</nav>");
//htmlReport.append("<nav><nav class=\"tooltip\">"+ arr[index].getName()+ "<span class=\"tooltiptext\" ><iframe src="+arr[index].toString()+"></iframe></span></nav></nav>");
htmlReport.append("</nav>");
htmlReport.append("<script> var coll = document.getElementsByClassName(\"collapsible\");");
htmlReport.append("var i;for (i = 0; i < coll.length; i++) { coll[i].addEventListener(\"click\", function() { this.classList.toggle(\"active\"); var content = this.nextElementSibling; if (content.style.maxHeight){");
htmlReport.append("content.style.maxHeight = null; } else { content.style.maxHeight = content.scrollHeight + \"px\"; } });}</script>");
htmlReport.append("");
dv.writeToReport(maindirpath);
dv.closeReport();
}//End of if()
// for Suite name
else if(arr[index].isDirectory())
{
String suiteTime="";
Collection<?> propfile= dv.getFiles(arr[index],"properties");
for(Iterator<File> _iterator = (Iterator<File>) propfile.iterator();_iterator.hasNext();){
String path=_iterator.next().toString();
if(path.contains("testsuite.properties"))
{
String text;
try {
text = new String(Files.readAllBytes(Paths.get(path)));
suiteTime = text.substring(text.indexOf("testsuite.duration")+32,text.length());
System.out.println("Got the suite time " + suiteTime);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Collection<?> successfiles= dv.getFiles(arr[index],"suc");
Collection<?> failfiles= dv.getFiles(arr[index],"dif");
// System.out.println("[" + arr[index].getName() + "]");
htmlReport.append("</nav>");
htmlReport.append("<nav class=\"collapsible\">");
htmlReport.append("<a id=\"my_link1\" href=" + dv.getRelativePath(arr[index].toString()) + " \ttarget=\"_blank\">");
htmlReport.append("<b>" + arr[index].getName() + "</b></a>");
htmlReport.append("</nav><div class=\"content\">");
if (!(arr[index].getName().equals("screenshots"))){
htmlReport.append("<div class=\"collapsible\"> Result Statistics "+ "<button class=\"button3\">"+(float)((successfiles.size()*100))/(successfiles.size()+ failfiles.size() ) +"%</button> <button class=\"button4\"> "+ suiteTime +"</button></div><div class=\"content\">");
htmlReport.append("<b><ul class=\"ul1\"><li class=\"li1\"> Suite Log-<a id=\"my_link2\" href=" + dv.getRelativePath(arr[index].toString()) +"/"+arr[index].getName() +"_run.log"+ " \ttarget=\"_blank\"> "+arr[index].getName()+"</a></li></ul></b>");
htmlReport.append("<b><ul class=\"ul1\"><li class=\"li1\"><font color=\"#fafafa\"> Total Tests- "+(successfiles.size()+ failfiles.size() )+ "</font></li></ul></b>");
htmlReport.append("<b><ul class=\"ul1\"><li class=\"li1\"><font color=\"#00e676\"> Passed Test- "+successfiles.size()+ "</font></li></ul></b>");
htmlReport.append("<b><ul class=\"ul1\"><li class=\"li1\"><font color=\"#CE0000\"> Failed Test- "+failfiles.size()+"</font></li></ul></b>");
htmlReport.append("</div>");
}
htmlReport.append("<script> var coll = document.getElementsByClassName(\"collapsible\");");
htmlReport.append("var i;for (i = 0; i < coll.length; i++) { coll[i].addEventListener(\"click\", function() { this.classList.toggle(\"active\"); var content = this.nextElementSibling; if (content.style.maxHeight){");
htmlReport.append("content.style.maxHeight = null; } else { content.style.maxHeight = content.scrollHeight + \"px\"; } });}</script>");
// recursion for sub-directories in side Suite
AutomationTestReport(arr[index].listFiles(), 0, level +1);
htmlReport.append("</div>");
dv.writeToReport(maindirpath);
} //End of if()
// recursion for Suite directory
dv.writeToReport(maindirpath);
AutomationTestReport(arr, ++index, level);
}//End of AutomationTestReport()
public void closeReport()
{
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// End of closeReport()
//public static String maindirpath="C:\\Users\\npandey\\Desktop\\results";
public void writeToReport(String maindirpath)
{
try {
String filepath=maindirpath+"/newDashboard.html";
//bw = new BufferedWriter(new FileWriter(new File("C:\\rockwell\\work\\results\\Automation_Report.html")));
//System.out.println("The result would be generated at "+filepath);
bw = new BufferedWriter(new FileWriter(new File(filepath)));
bw.write(htmlReport.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//End of writeToReport()
public Collection<?> getFiles(File dir, String ext)
{
return FileUtils.listFiles(dir,
new RegexFileFilter("^.*\\.("+ext+")"),
DirectoryFileFilter.DIRECTORY);
}
private String getRelativePath(String filePath)
{
Path p = Paths.get(maindirpath);
File f = new File(filePath);
Path relPath = p.relativize(f.toPath());
return relPath.toString();
}
private static String maindirpath;
private static String startTime;
private static String endTime;
private static String title;
private static String timerProp;
// Main Method
public static void main(String[] args) throws IOException
{
GenerateDashboard dv = new GenerateDashboard();
//maindirpath="C:\\Users\\npandey\\Desktop\\results";
//**************************************************************************
for (int i = 0; i < args.length; i++ ) {
if (args[i].equalsIgnoreCase("-resultDir")) maindirpath=args[++i];
else if (args[i].equalsIgnoreCase("-starttime")) startTime=args[++i];
else if (args[i].equalsIgnoreCase("-endTime")) endTime=args[++i];
else if (args[i].equalsIgnoreCase("-title")) title=args[++i];
else if (args[i].equalsIgnoreCase("-timerProp")) timerProp=args[++i];
}
//***************************************************************************
Properties prop = new Properties();
FileReader reader = null;
String totalExtime=null;
String filename = "C:\\rockwell\\work\\timer.properties";
reader=new FileReader(filename);
prop.load(reader);
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
if(key.contains("comp")) {
totalExtime=value;
//System.out.println(" Value : " + totalExtime);
}
}
//***************************************************************************
// File object
File maindir = new File(dv.maindirpath);
if(maindir.exists() && maindir.isDirectory())
{
File arr[] = maindir.listFiles();
float PassPercentage;
float failPercentage;
Collection<?> successfiles= dv.getFiles(maindir,"suc");
Collection<?> failfiles= dv.getFiles(maindir,"dif");
Collection<?> applogfiles= dv.getFiles(maindir,"text");
//----------------------------------------------------------------------------------------------
String logfilepath=null;
String logfile=null;
for(Iterator<File> _iterator = (Iterator<File>) applogfiles.iterator();_iterator.hasNext();){
logfilepath=_iterator.next().toString();
//To-Do include this for multiple logs (multipe Application)
if(logfilepath.contains("_log.text"))
{
logfile=logfilepath;
//System.out.println(logfile);
}
// if(logfilepath.contains("sjc_ftaDataFlowML_log.text")) {
//
// logfile=logfilepath;
// //System.out.println(logfile);
// }
}
//-----------------------------------------------------------------------------------------------
int total1 = successfiles.size()+ failfiles.size();
int pass1 = successfiles.size();
int fail1 = failfiles.size();
float total = successfiles.size()+ failfiles.size();
float pass = successfiles.size();
float fail = failfiles.size();
PassPercentage =(int)((pass/total)*100);
failPercentage = (int)((fail/total)*100);
htmlReport.append("<b><nav class=\"nav1\"><ul><li id=\"total\" value= "+total1+">"+"<font color=\"#fafafa\">Total tests -"+(successfiles.size()+ failfiles.size() )+
"</font></li></ul>" + "<ul><li id=\"pass\" value="+pass1+ "><font color=\"#00e676\">Passed Tests -" +successfiles.size()
+"</font></li></ul>"+ "<ul><li id=\"fail\" value= "+fail1+"><font color=\"#CE0000\">Failed Tests-"+failfiles.size() +"</font></li></ul></nav></b>");
htmlReport.append("<b><nav class=\"nav1\"><ul><li> <a href="+ dv.getRelativePath(logfilepath) +" \ttarget=\"_blank\"> Application Log</a></li></ul>"+"<ul><li><font color=\"#00e676\"> Success Percentage- "+PassPercentage+ " % </font></li></ul>" + "<ul><li><font color=\"#CE0000\"> Faliure Percentage- "+failPercentage + " %</font> </li></ul>" + "<ul><li> Elapsed Time - " + totalExtime + "</li></ul></nav></b>");
//htmlReport.append("<nav class=\"nav1\"><ul><li> Total tests -"+(successfiles.size()+ failfiles.size() )+ "</li></ul>" + "<ul><li> Passed Tests -"+successfiles.size()+ "</li></ul>"+ "<ul><li> Failed Tests-"+failfiles.size() + "</li></ul></nav>");
htmlReport.append("<nav id=\"piechart\" class=\"nav2\"></nav>");
htmlReport.append("<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>");
htmlReport.append("<script type=\"text/javascript\">\r\n" +
"// Load google charts\r\n" +
"google.charts.load('current', {'packages':['corechart']});\r\n" +
"google.charts.setOnLoadCallback(drawChart);\r\n" +
"\r\n" +
"// Draw the chart and set the chart values\r\n" +
"function drawChart() {\r\n" +
"var x = document.getElementById(\"total\").value;"+
"var y = document.getElementById(\"pass\").value;"+
"var z = document.getElementById(\"fail\").value;"+
" var data = google.visualization.arrayToDataTable([\r\n" +
" ['Task', 'Chart View'],\r\n" +
" ['Total Test', 0],\r\n" +
" ['Failed Tests', z],\r\n" +
" ['Scepd', 0],"+
" ['Passed Tests',y]\r\n" +
"]);\r\n" +
"\r\n" +
" // Optional; add a title and set the width and height of the chart\r\n" +
" var options = {'title':'Tests Run Result Chart', 'width':580, 'height':400};\r\n" +
"\r\n" +
" // Display the chart inside the <div> element with id=\"piechart\"\r\n" +
" var chart = new google.visualization.PieChart(document.getElementById('piechart'));\r\n" +
" chart.draw(data, options);\r\n" +
"}" +
"</script>");
//Calling AutomationTestReport()
//dv.writeToReport();
htmlReport.append("<div id=\"overflowTest\" class=\"div1\">");
AutomationTestReport(arr,1,0);
htmlReport.append("</div>");
htmlReport.append("</script></body></html>");
dv.writeToReport(maindirpath);
dv.closeReport();
} //End of if()
} //End of main()
}//End of class
<file_sep># helloWorld
MyFirstGitProject
hello world
| afeaa303b67232bbb9974f5b153a1d9b18009430 | [
"Markdown",
"Java"
] | 2 | Java | akshay-sanganwar/helloWorld | 6528dd8323628e19eeefffeef4386d323ccdddd8 | 5c71761f322ab4d67d8d5f482462ef38b2754abd |
refs/heads/master | <repo_name>germancodes/selenium<file_sep>/src/main/java/DataExtractor.java
import java.sql.*;
import java.util.*;
public class DataExtractor {
public Connection conn;
private String strSQL;
private String strErrMsg;
private final List<String> webIDList = new ArrayList<>();
private final List<String> elementTypeList = new ArrayList<>();
private final List<String> columNameList = new ArrayList<>();
private final List<String> mappingColumns = new ArrayList<>();
public void loadDBConn(String strDBPath) throws SQLException{
strSQL = "";
webIDList.clear();
elementTypeList.clear();
columNameList.clear();
mappingColumns.clear();
conn = DriverManager.getConnection("jdbc:ucanaccess://" + strDBPath);
}
public boolean checkTables() throws SQLException {
Statement stmt2 = conn.createStatement();
try{
ResultSet recordSet = stmt2.executeQuery("SELECT * FROM tblMappings");
if(!(recordSet.isBeforeFirst())){
return false;
} else {
recordSet.close();
recordSet = stmt2.executeQuery("SELECT * FROM tblValues");
if(!(recordSet.isBeforeFirst())){
return false;
} else {
return true;
}
}
} catch (SQLException e) {
strErrMsg = e.getMessage();
return false;
}
}
public boolean checkDataStructure() throws SQLException {
Statement stmt3 = conn.createStatement();
try {
ResultSet recordSet = stmt3.executeQuery("SELECT executionOrder, fieldID, elementType, columnName FROM tblMappings");
while(recordSet.next()){
mappingColumns.add(recordSet.getString("columnName"));
}
createSQL();
recordSet.close();
recordSet = stmt3.executeQuery(strSQL);
recordSet.close();
return true;
} catch (SQLException e) {
strErrMsg = e.getMessage();
return false;
}
}
private void createSQL() {
String strTemp = "";
for(int x = 0; x < mappingColumns.size(); x++){
strTemp = strTemp + mappingColumns.get(x) + ", ";
}
strSQL = "SELECT ID, " + strTemp + "Status FROM tblValues";
System.out.println(strSQL);
}
public void getDBValues() throws SQLException{
int x = 0;
Statement stmt = conn.createStatement();
ResultSet recordSet = stmt.executeQuery("SELECT * FROM tblMappings ORDER BY executionOrder");
//webIDList = (List<String>) recordSet.getArray("fieldID");
while(recordSet.next()){
webIDList.add(recordSet.getString("fieldID"));
elementTypeList.add(recordSet.getString("elementType"));
columNameList.add(recordSet.getString("columnName"));
System.out.println(webIDList.get(x) + " - " + elementTypeList.get(x) + " - " + columNameList.get(x));
x++;
}
recordSet.close();
stmt.close();
}
public boolean executeDataEntry(String strURL) throws SQLException{
int intArrySize, x;
boolean boolResult;
boolResult = false;
Statement stmt = conn.createStatement();
ResultSet recordSet = stmt.executeQuery("SELECT * FROM tblValues");
try {
while(recordSet.next()){
WebsiteFiller testItem = new WebsiteFiller();
testItem.loadSite(strURL);
intArrySize = webIDList.size();
for (x = 0; x < intArrySize; x++){
switch(elementTypeList.get(x)){
case "TB":
if(!empty(recordSet.getString(columNameList.get(x)))){
testItem.populateTextBox(webIDList.get(x), recordSet.getString(columNameList.get(x)));
}
break;
case "DD":
if(!empty(recordSet.getString(columNameList.get(x)))){
testItem.populateDropDown(webIDList.get(x), recordSet.getString(columNameList.get(x)));
}
break;
case "UP":
if(!empty(recordSet.getString(columNameList.get(x)))){
testItem.uploadFile(webIDList.get(x), recordSet.getString(columNameList.get(x)));
}
break;
case "RAD":
if("Y".equals(recordSet.getString(columNameList.get(x)))){
testItem.selectRadio(webIDList.get(x));
}
break;
case "BUTT":
if("Y".equals(recordSet.getString(columNameList.get(x)))){
testItem.clickButton(webIDList.get(x));
}
break;
case "xTB":
if(!empty(recordSet.getString(columNameList.get(x)))){
testItem.populateSpecialTextBox(webIDList.get(x), recordSet.getString(columNameList.get(x)));
}
break;
case "xBUTT":
if("Y".equals(recordSet.getString(columNameList.get(x)))){
testItem.SpecialClickButton(webIDList.get(x));
}
break;
default:
break;
}
}
//testItem.closeSite();
testItem = null;
boolResult = true;
}
} catch (Exception err) {
boolResult = false;
strErrMsg = err.getMessage();
}
return boolResult;
}
public String getErrorMsg(){
return strErrMsg;
}
private static boolean empty( final String s ) {
return s == null || s.trim().isEmpty();
}
}
<file_sep>/src/main/java/WebsiteFiller.java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.*;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebsiteFiller implements MainInterface{
private final WebDriver driver = new FirefoxDriver();
@Override
public void loadSite(String strSiteURL) {
//WebDriver driver = new FirefoxDriver();
driver.get(strSiteURL);
WebDriverWait wait = new WebDriverWait(driver, 10);
}
@Override
public void populateDropDown(String strElemID, String strValue) {
Select dropdown = new Select(driver.findElement(By.id(strElemID)));
if (dropdown.isMultiple()) {
dropdown.deselectAll();
}
dropdown.selectByVisibleText(strValue);
}
@Override
public void uploadFile(String strElemID, String strValue) {
WebElement textBoxElem = driver.findElement(By.id(strElemID));
textBoxElem.sendKeys(strValue);
}
@Override
public void populateTextBox(String strElemID, String strValue) {
WebElement textBoxElem = driver.findElement(By.id(strElemID));
textBoxElem.clear();
textBoxElem.sendKeys(strValue);
}
@Override
public void selectRadio(String strElemID){
WebElement radioElem = driver.findElement(By.id(strElemID));
radioElem.click();
}
@Override
public void clickButton(String strElemID) {
WebElement buttElem = driver.findElement(By.id(strElemID));
buttElem.click();
}
@Override
public void populateSpecialTextBox(String strXPath, String strValue) {
WebElement specialElem = driver.findElement(By.xpath(strXPath));
specialElem.sendKeys(strValue);
}
@Override
public void SpecialClickButton(String strXPath) {
WebElement specialElem = driver.findElement(By.xpath(strXPath));
specialElem.click();
}
@Override
public void closeSite(){
driver.close();
driver.quit();
System.out.println("Done w/ automation");
}
}
<file_sep>/src/main/java/TestClass.java
/*
Student: <NAME>
Date: 10/23/2016
Class: CSCI-4316
QUIZ 3
*/
import java.sql.SQLException;
public class TestClass {
public static void main(String[] args){
WebsiteFiller webTestItem = new WebsiteFiller();
//Testing site loader functionality
webTestItem.loadSite("http://www.pvamu.edu/ece/students/current/prerequisite-override-request/");
//Testing drop down filler functionality
webTestItem.populateDropDown("input_15_71", "Prerequisite Override");
//Testing text box filler functionality
webTestItem.populateTextBox("input_15_6_3", "German");
System.out.println("Done");
System.exit(0);
}
}
| 58c165f712221e95840fce3df43a1f5d50187ef0 | [
"Java"
] | 3 | Java | germancodes/selenium | babb43275271e1c4ebea510f5637dd7be1def335 | be38e6721762b9a3220f8f2e4f484aeb267c5ea8 |
refs/heads/main | <file_sep>
export type Todo = {
id: string,
todo: string,
completed: boolean
} | 787120c9272b59db83815d56b011dd62d0d688b6 | [
"TypeScript"
] | 1 | TypeScript | resendiz0x/todo-react-app | d869012d2ded3f3ae710b93b7e6b85387379a982 | 6880c71efc9d546f878a18561faa5231e5a3b685 |
refs/heads/main | <repo_name>jron82/viewer-demo<file_sep>/src/Excel/index.jsx
import React from 'react';
import './excel.css';
import Viewer from './../Viewer.jsx';
export default function Excel() {
const file = 'https://hypergraph.space/SimpleSpreadsheet.xlsx';
const type = 'xlsx';
return (
<section className="excel-preview">
<h1 style={{ textAlign: 'center' }}>Excel Preview</h1>
<Viewer file={file} type={type} />
</section>
);
}
<file_sep>/src/Home/index.jsx
import React from 'react';
import './home.css';
import { useLocation } from 'wouter';
export default function Home() {
const [location, setLocation] = useLocation();
console.log(location);
return (
<section className="home">
<div>
<button className="button" onClick={() => setLocation('/audio')}>
MP3 Audio
</button>
</div>
<div>
<button className="button" onClick={() => setLocation('/excel')}>
Excel
</button>
</div>
<div>
<button className="button" onClick={() => setLocation('/pdf')}>
PDF
</button>
</div>
<div>
<button className="button" onClick={() => setLocation('/powerpoint')}>
PowerPoint
</button>
</div>
<div>
<button className="button" onClick={() => setLocation('/video')}>
MP4 Video
</button>
</div>
<div>
<button className="button" onClick={() => setLocation('/wexbim')}>
Wexbim
</button>
</div>
<div>
<button className="button" onClick={() => setLocation('/word')}>
MS Word
</button>
</div>
</section>
);
}
<file_sep>/src/Word/index.jsx
import React from 'react';
import './word.css';
import Viewer from '../Viewer.jsx';
export default function Word() {
const file = 'https://hypergraph.space/SampleSpec.docx';
const type = 'docx';
return (
<section className="word-preview">
<h1 style={{ textAlign: 'center' }}>MS Word Preview</h1>
<Viewer file={file} type={type} />
</section>
);
}
<file_sep>/src/Viewer.jsx
import React from 'react';
import FileViewer from 'react-file-viewer';
export default function Viewer(props) {
return (
<FileViewer
fileType={props.type}
filePath={props.file}
errorComponent={() => {}}
onError={(e) => console.log(e)}
/>
);
}
<file_sep>/src/App.jsx
import React from 'react';
import './App.css';
import { Router, Route, Switch } from 'wouter';
import Audio from './Audio';
import Excel from './Excel';
import Home from './Home';
import PowerPoint from './PowerPoint';
import PDF from './PDF';
import Video from './Video';
import Wexbim from './Wexbim';
import Word from './Word';
function App() {
return (
<main className="main-grid">
<div className="header">
<h1
className="header-title"
onClick={() => history.pushState('', 'Home', '/')}
>
React File Viewer
</h1>
</div>
<div className="examples">
<Router>
<Switch>
<Route path="/">
<Home />
</Route>
<Route path="/audio">
<Audio />
</Route>
<Route path="/excel">
<Excel />
</Route>
<Route path="/pdf">
<PDF />
</Route>
<Route path="/powerpoint">
<PowerPoint />
</Route>
<Route path="/video">
<Video />
</Route>
<Route path="/wexbim">
<Wexbim />
</Route>
<Route path="/word">
<Word />
</Route>
<Route path="/:rest*">
{(params) => `404, Sorry the page ${params.rest} does not exist!`}
</Route>
</Switch>
</Router>
</div>
</main>
);
}
export default App;
<file_sep>/src/PDF/index.jsx
import React from 'react';
import './pdf.css';
import Viewer from '../Viewer.jsx';
export default function PDF() {
const file = 'https://hypergraph.space/sample.pdf';
const type = 'pdf';
return (
<section className="pdf-preview">
<h1 style={{ textAlign: 'center' }}>PDF Preview</h1>
<Viewer file={file} type={type} />
</section>
);
}
<file_sep>/src/Audio/index.jsx
import React from 'react';
import './audio.css';
import Viewer from './../Viewer.jsx';
export default function Audio() {
const file = 'https://hypergraph.space/sample.mp3';
const type = 'mp3';
return (
<section className="audio-preview">
<h1 style={{ textAlign: 'center' }}>Audio Preview</h1>
<Viewer file={file} type={type} />
</section>
);
}
| 151859742895492fdfba4a1da406b8f11776087a | [
"JavaScript"
] | 7 | JavaScript | jron82/viewer-demo | b5b520fbc3049aedce88d985969df7ac0082c57c | 0b1ff8132e05868662ed4d239de48d0ac521a769 |
refs/heads/master | <file_sep>package shared;
/**
* An attribute type specifies what type an attribute
* within a data set is
* @author <NAME> <EMAIL>
* @version 1.0
*/
public class AttributeType {
/**
* The binary type
*/
public static final AttributeType BINARY = new AttributeType(1);
/**
* The integer / discrete type
*/
public static final AttributeType DISCRETE = new AttributeType(2);
/**
* The continuous type
*/
public static final AttributeType CONTINUOUS = new AttributeType(3);
/**
* The type of the attribute
*/
private final int type;
/**
* Make a new attribute type
* @param t the type of the attribute
*/
private AttributeType(int t) {
type = t;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final AttributeType that = (AttributeType) o;
return type == that.type;
}
@Override
public int hashCode() {
return type;
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
if (this == BINARY) {
return "BINARY";
} else if (this == DISCRETE) {
return "DISCRETE";
} else if (this == CONTINUOUS) {
return "CONTINUOUS";
} else {
return "UNKNOWN";
}
}
}
| 3e85df3017abb06526aac4e990446ac74de474dd | [
"Java"
] | 1 | Java | klittlepage/ABAGAIL | a60115f10f5cb95d0de59585611d2083c54a531e | 886c20fc67c2162120d583d0e75bdee1736a29ed |
refs/heads/master | <repo_name>hhatefi/sc_planner<file_sep>/README.md
Supply Chain Planner
====================
This project solves planning problem on a supply chain graph. The
chain should be defined in a text file with specific format. This
document briefly describe how to install the planner, define a supply
chain and solve it.
## Method
The planner models a supply chain as a maximum flow problem, which is
then formulated as a mixed integer linear program and fed into the LP
solver. If you need a deeper look into the algorithm used for planning
see [this document](docs/planning.pdf).
## Prerequisite
To run the planner, pythen 3.6 and above is required. Since the
planner formulates the problem as an MILP (mixed integer linear
program), it also requires an MILP solver. It uses
[PuLP](https://pypi.org/project/PuLP/) as the linear programming
modeler, which can call several external
solvers. [CBC](http://www.coin-or.org/) solver, which is bundled with
PuLP should be enough for test purposes. PuLP can be installed via
`pip`, i.e.
```SHELL
pip install pulp
```
or using `make` (at project root directory):
```SHELL
make init
```
## Usage
The usage of the planner is as follows:
```SHELL
python planner.py <model> [<lp>]
```
- `model` is the chain described by the input format (see [examples](examples)).
- `lp` is the name of output file containing the mixed linear integer
program corresponding to the model. This argument is optional.
## Model specification
A supply chain specification comprises of *component* and
*product*. Products are at the final stage denoting the result of a
chain. An example of product declaration can be as follows.
```SHELL
product p1, p2=30;
```
As we want to maximize the production, the above line puts their sum
in the objective function. That is to say, the objective of this
supply chain will contain `p1+p2`. In addition, it imposes constraint
`p2<=30` on the plan to ensure the number of product `p2` is not above
30. Suppose the above line defines the whole chain, the induced MILP
looks like:
```SHELL
max p1 + p2
subject to
p2 <= 30
p1 and p2 are integer
```
It is indeed not a realistic chain, since a chain usually trace the
products back to suppliers and depots via components. Components
can be seen as the intermediate products between suppliers and
depots and the final products. They are defined in a similar way
as products. For instance,
```SHELL
component c1, c2=10;
```
defines component `c1` and `c2`, with `c2` being fed by an depot
of size 10. The semantics of this definition is constraint `c2<=10`,
which makes sure the number of component `c2` never goes above the
capacity of the depot. It is possible to connect the a component
directly to a supplier, e.g. by
```SHELL
c1<-supplier;
```
This means the supplier can deliver any number of `c1` required for
the plan. Components and products can be connected to each other to
produce other components and products. Operator `+` combines two or
more components and produces a result. As an example,
```SHELL
p1<-c1+c2
```
combines `n` items of component `c1` with `n` items of component `c2`
and yields `n` items of product `p1`. The semantics of this operator
is similar to **AND** gate, considering it obligates the same quantity
of `c1` and `c2` be available at the time. In the induced MILP, it
introduces the following constrains:
```SHELL
p1=c1
p1=c2
```
Components can likewise be combined by an **OR** gate.
```SHELL
p1<-c1|c2
```
In this case, `p1` is produced either of `c1` or `c2`, exclusively. It
introduces the following constrains:
```SHELL
x1 + x2 = 1
x1 * c1 + x2 * c2 = p1
x1 and x2 are binary
```
Binary variables `x1` and `x2` determine which component `c1` or
respectively `c2` is selected to produce `p1`. The constraints involve
multiplication of two variables and thereby not linear. Their
linearization is explain in detail [here](docs/planning.pdf).
<file_sep>/tests/Statement_test.py
import unittest
from context import parser as pr
from context import entities as en
class StatementTest(unittest.TestCase):
def test_factory(self):
# a single product
p=pr.Statement.factory("product p1=10 high")
self.assertEqual(p.get_type(), pr.StatementType.PROD_DEF)
# a single component
p=pr.Statement.factory("component c1=7")
self.assertEqual(p.get_type(), pr.StatementType.COMP_DEF)
# an AND transition
p=pr.Statement.factory("p1<-c1+c2")
self.assertEqual(p.get_type(), pr.StatementType.TRAN_DEF)
# an invalid statement
with self.assertRaises(ValueError):
pr.Statement.factory(":p1<-c1+c2")
# another invalid statement
with self.assertRaises(ValueError):
pr.Statement.factory(".")
def test_product_parsing(self):
# an empty product definition
with self.assertRaises(ValueError):
pr.Statement.factory("product")
# another empty product definition
with self.assertRaises(ValueError):
pr.Statement.factory("product\n\t")
# a single product
p=pr.Statement.factory("product p1=10 high")
self.assertEqual(p.get_type(), en.EntityType.PROD)
self.assertEqual(len(p._products), 1)
self.assertEqual(p._products[0]._name, 'p1')
self.assertEqual(p._products[0]._order_size, 10)
self.assertEqual(p._products[0]._priority, en.ProductPriority.HIGH)
# two products
p=pr.Statement.factory("product\n _pp1=5 high,_pp2=3")
self.assertEqual(p.get_type(), en.EntityType.PROD)
self.assertEqual(len(p._products), 2)
self.assertEqual(p._products[0]._name, '_pp1')
self.assertEqual(p._products[0]._order_size, 5)
self.assertEqual(p._products[0]._priority, en.ProductPriority.HIGH)
self.assertEqual(p._products[1]._name, '_pp2')
self.assertEqual(p._products[1]._order_size, 3)
self.assertEqual(p._products[1]._priority, en.ProductPriority.LOW)
def test_component_parsing(self):
# an empty component definition
with self.assertRaises(ValueError):
pr.Statement.factory("component")
# another empty component definition
with self.assertRaises(ValueError):
pr.Statement.factory("component\n\t")
# a single component
p=pr.Statement.factory("component c1=7")
self.assertEqual(p.get_type(), en.EntityType.COMP)
self.assertEqual(len(p._components), 1)
self.assertEqual(p._components[0]._name, 'c1')
self.assertEqual(p._components[0]._stock, 7)
# two products
p=pr.Statement.factory("component\n _cc1=9 \t,_ccc,dd")
self.assertEqual(p.get_type(), en.EntityType.COMP)
self.assertEqual(len(p._components), 3)
self.assertEqual(p._components[0]._name, '_cc1')
self.assertEqual(p._components[0]._stock, 9)
self.assertEqual(p._components[1]._name, '_ccc')
self.assertEqual(p._components[1]._stock, 0)
self.assertEqual(p._components[2]._name, 'dd')
self.assertEqual(p._components[2]._stock, 0)
def test_transition_parsing(self):
# an invalid transition
with self.assertRaises(ValueError):
pr.Statement.factory('1p1<-')
# another invalid transition
with self.assertRaises(ValueError):
pr.Statement.factory('pp4p_1 <<')
# an OR transition
p=pr.Statement.factory("p1 <- a | c2")
self.assertEqual(p._transition._target, 'p1')
self.assertEqual(len(p._transition._sources), 2)
self.assertEqual(p._transition._sources[0],'a')
self.assertEqual(p._transition._sources[1],'c2')
self.assertEqual(p._transition._tr_type, en.TransitionType.OR)
# an AND transition
p=pr.Statement.factory("ppp1<-_cc1+_c2")
self.assertEqual(p._transition._target, 'ppp1')
self.assertEqual(len(p._transition._sources), 2)
self.assertEqual(p._transition._sources[0],'_cc1')
self.assertEqual(p._transition._sources[1],'_c2')
self.assertEqual(p._transition._tr_type, en.TransitionType.AND)
# direct connection to supplier
p=pr.Statement.factory("cc1 <- supplier")
self.assertEqual(p._transition._target, 'cc1')
self.assertEqual(p._transition._sources, None)
self.assertEqual(p._transition._tr_type, en.TransitionType.DIR)
# another AND transition
p=pr.Statement.factory("""__p1<-r+_c2+
dd1+dd4
+cc2""")
self.assertEqual(p._transition._target, '__p1')
self.assertEqual(len(p._transition._sources), 5)
self.assertEqual(p._transition._sources[0],'r')
self.assertEqual(p._transition._sources[1],'_c2')
self.assertEqual(p._transition._sources[2],'dd1')
self.assertEqual(p._transition._sources[3],'dd4')
self.assertEqual(p._transition._sources[4],'cc2')
self.assertEqual(p._transition._tr_type, en.TransitionType.AND)
if __name__=='__main__':
unittest.main()
<file_sep>/tests/SupplyChain_test.py
import os
import unittest
from context import parser as pr
from context import supply_chain as sc
from context import entities as en
class SupplyChainTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(SupplyChainTest, self).__init__(*args, **kwargs)
self._examples_dir=os.path.join(os.path.dirname(__file__), '..', 'examples')
self._test_model_dir=os.path.join(os.path.dirname(__file__), 'test_models')
def _run_an_example(self, model_fname):
p=pr.Parser(os.path.join(self._examples_dir, model_fname))
statements=p.parse()
return sc.SupplyChain(statements)
def _run_a_test_model(self, model_fname):
p=pr.Parser(os.path.join(self._test_model_dir, model_fname))
statements=p.parse()
return sc.SupplyChain(statements)
def test_extraction1(self):
spch=self._run_an_example('example1.txt')
self.assertTrue(spch._products)
self.assertTrue(spch._components)
self.assertTrue(spch._transitions)
# len
self.assertEqual(len(spch._products),2)
self.assertEqual(len(spch._components),2)
self.assertEqual(len(spch._transitions),3)
# products
self.assertEqual(spch._products[0]._name,'p1')
self.assertEqual(spch._products[1]._name,'p2')
self.assertEqual(spch._products[0]._order_size,10)
self.assertEqual(spch._products[1]._order_size,10)
self.assertEqual(spch._products[0]._priority,en.ProductPriority.HIGH)
self.assertEqual(spch._products[1]._priority,en.ProductPriority.LOW)
# components
self.assertEqual(spch._components[0]._name,'c1')
self.assertEqual(spch._components[1]._name,'c2')
self.assertEqual(spch._components[0]._stock,0)
self.assertEqual(spch._components[1]._stock,10)
# transitions
self.assertEqual(spch._transitions[0]._target,'c1')
self.assertEqual(spch._transitions[1]._target,'p1')
self.assertEqual(spch._transitions[2]._target,'p2')
self.assertTrue(spch._transitions[0]._sources is None)
self.assertTrue(spch._transitions[1]._sources)
self.assertTrue(spch._transitions[2]._sources)
self.assertEqual(len(spch._transitions[1]._sources),2)
self.assertEqual(len(spch._transitions[2]._sources),1)
self.assertEqual(spch._transitions[1]._sources[0],'c1')
self.assertEqual(spch._transitions[1]._sources[1],'c2')
self.assertEqual(spch._transitions[2]._sources[0],'c2')
self.assertEqual(spch._transitions[0]._tr_type,en.TransitionType.DIR)
self.assertEqual(spch._transitions[1]._tr_type,en.TransitionType.OR)
self.assertEqual(spch._transitions[2]._tr_type,en.TransitionType.AND)
def test_extraction2(self):
spch=self._run_an_example('example2.txt')
self.assertTrue(spch._products)
self.assertTrue(spch._components)
self.assertTrue(spch._transitions)
# len
self.assertEqual(len(spch._products),1)
self.assertEqual(len(spch._components),4)
self.assertEqual(len(spch._transitions),4)
# products
self.assertEqual(spch._products[0]._name,'p')
self.assertEqual(spch._products[0]._order_size,20)
self.assertEqual(spch._products[0]._priority,en.ProductPriority.LOW)
# components
self.assertEqual(spch._components[0]._name,'c1')
self.assertEqual(spch._components[1]._name,'c2')
self.assertEqual(spch._components[2]._name,'c3')
self.assertEqual(spch._components[3]._name,'c4')
self.assertEqual(spch._components[0]._stock,0)
self.assertEqual(spch._components[1]._stock,0)
self.assertEqual(spch._components[2]._stock,0)
self.assertEqual(spch._components[3]._stock,20)
# transitions
self.assertEqual(spch._transitions[0]._target,'p')
self.assertEqual(spch._transitions[1]._target,'c1')
self.assertEqual(spch._transitions[2]._target,'c2')
self.assertEqual(spch._transitions[3]._target,'c3')
self.assertTrue(spch._transitions[0]._sources)
self.assertTrue(spch._transitions[1]._sources)
self.assertTrue(spch._transitions[2]._sources)
self.assertTrue(spch._transitions[3]._sources is None)
self.assertEqual(len(spch._transitions[0]._sources),2)
self.assertEqual(len(spch._transitions[1]._sources),2)
self.assertEqual(len(spch._transitions[2]._sources),1)
self.assertEqual(spch._transitions[0]._sources[0],'c1')
self.assertEqual(spch._transitions[0]._sources[1],'c2')
self.assertEqual(spch._transitions[1]._sources[0],'c3')
self.assertEqual(spch._transitions[1]._sources[1],'c4')
self.assertEqual(spch._transitions[2]._sources[0],'c4')
self.assertEqual(spch._transitions[0]._tr_type,en.TransitionType.AND)
self.assertEqual(spch._transitions[1]._tr_type,en.TransitionType.AND)
self.assertEqual(spch._transitions[2]._tr_type,en.TransitionType.AND)
self.assertEqual(spch._transitions[3]._tr_type,en.TransitionType.DIR)
def test_verify_the_chain(self):
# product duplicate
with self.assertRaises(ValueError):
self._run_a_test_model('dup_prod.txt')
# component duplicate
with self.assertRaises(ValueError):
self._run_a_test_model('dup_comp.txt')
# component/product duplicate
with self.assertRaises(ValueError):
self._run_a_test_model('dup_prod_comp.txt')
# transition duplicate (from comp/product to comp/product)
with self.assertRaises(ValueError):
self._run_a_test_model('dup_tran1.txt')
# transition duplicate (from comp/product to supplier)
with self.assertRaises(ValueError):
self._run_a_test_model('dup_tran2.txt')
# non existing target
with self.assertRaises(KeyError):
self._run_a_test_model('non_existing_target.txt')
# non existing source
with self.assertRaises(KeyError):
self._run_a_test_model('non_existing_source.txt')
# self loop
with self.assertRaises(ValueError):
self._run_a_test_model('self_loop.txt')
def test_build_outgoings(self):
spch=self._run_a_test_model('build_outgoings.txt')
for p in spch._products:
self.assertTrue(p not in spch._outgoings) # Products have no outgoing transition
self.assertEqual(len(spch._outgoings['c1']),3)
self.assertTrue(spch._outgoings['c1'][0] is spch._transitions[0])
self.assertTrue(spch._outgoings['c1'][1] is spch._transitions[1])
self.assertTrue(spch._outgoings['c1'][2] is spch._transitions[2])
self.assertEqual(len(spch._outgoings['c2']),2)
self.assertTrue(spch._outgoings['c2'][0] is spch._transitions[0])
self.assertTrue(spch._outgoings['c2'][1] is spch._transitions[3])
self.assertEqual(len(spch._outgoings['c3']),2)
self.assertTrue(spch._outgoings['c3'][0] is spch._transitions[0])
self.assertTrue(spch._outgoings['c3'][1] is spch._transitions[2])
self.assertEqual(len(spch._outgoings['c4']),2)
self.assertTrue(spch._outgoings['c4'][0] is spch._transitions[2])
self.assertTrue(spch._outgoings['c4'][1] is spch._transitions[3])
self.assertTrue('c2' in spch._leaves)
self.assertTrue('c3' in spch._leaves)
if __name__ == '__main__':
unittest.main()
<file_sep>/lib/solver.py
import pulp
import lib.entities as en
class Solver:
"""The solver class solves a problem on supply chain
"""
def __init__(self, supply_chain):
self._supply_chain=supply_chain
self._initialize()
def _initialize(self):
"""initializes the problem before solving"""
pass
def _solve(self):
"""solves the problem"""
pass
class PlanningSolver(Solver):
"""The solver class for supply chain planning"""
def __init__(self, supply_chain):
super(PlanningSolver, self).__init__(supply_chain)
def _initialize(self):
self._prob=pulp.LpProblem("Supply chain planning", pulp.LpMaximize) # creating the problem
spch=self._supply_chain # the supply chain
prods=spch._products # the products in the supply chain
comps=spch._components # the components in the supply chain
trans=spch._transitions # the transitions in the supply chain
### variable definition ###
# a variable for each product
prod_vars=dict([(p._name,pulp.LpVariable(p._name,0,p._order_size)) for p in prods])
# a variable for each inventory with positive stock
inv_vars=dict([("_i_"+c._name,pulp.LpVariable("_i_"+c._name,0,c._stock)) for c in comps if c._stock > 0])
# a variable for each supplier with is connected to an entity
sup_vars=dict([("_s_"+t._target,pulp.LpVariable("_s_"+t._target,0)) for t in trans if t._tr_type == en.TransitionType.DIR])
# a variable for each transition between two entities
trans_var_pairs=[]
for t in trans:
if t._sources:
trans_var_pairs.extend([(f"_{s}_{t._target}",pulp.LpVariable(f"_{s}_{t._target}",0)) for s in t._sources])
trans_vars=dict(trans_var_pairs)
# a variable for each branch of or operators
or_var_list=dict([(t._target, [pulp.LpVariable(f"_x_{s}_{t._target}",0,1,pulp.LpInteger) for s in t._sources]) for t in trans if t._tr_type == en.TransitionType.OR])
### constraints ###
# or variable constraints: sum of or variables must be 1
for _,or_vars in or_var_list.items():
self._prob += pulp.lpSum(or_vars) == 1
# computing the upper bound of inflow into entities
upper_bounds=self._compute_upper_bounds()
# conservation law constraints
for t in trans:
target=t._target
# computing outflow
if self.is_product(target): # if the transition target is a product, the outflow goes all into the product
outflow=prod_vars[target]
else: # otherwise the transition target is a component, so we need to find the outflow
outgoing_trans=spch._outgoings[target] #the outgoing transitions
outflow=pulp.lpSum([trans_vars[f"_{target}_{ot._target}"] for ot in outgoing_trans])
### computing inflow and adding conservation law contraint
# add the inventory to the inflow if its stock is positive
inflow=inv_vars[f"_i_{target}"] if self.has_positive_stock(target) else 0
if t._tr_type == en.TransitionType.AND: # if transition is an AND transition
if t._sources:
for s in t._sources:
self._prob+=outflow==trans_vars[f"_{s}_{target}"]+inflow
elif t._tr_type == en.TransitionType.OR: # if transition is an OR transition
if t._sources:
for n,s in enumerate(t._sources):
self._prob+=outflow-inflow <= trans_vars[f"_{s}_{target}"]+(1-or_var_list[target][n])*upper_bounds[target]
self._prob+=outflow-inflow >= trans_vars[f"_{s}_{target}"]-(1-or_var_list[target][n])*upper_bounds[target]
else: # the transition is a direct transition from supplier to an entity
inflow+=sup_vars[f"_s_{target}"]
self._prob+=outflow==inflow
# add leaf contrains
for leaf in spch._leaves:
# computing outflow
if self.is_product(leaf): # if the transition target is a product, the outflow goes all into the product
outflow=prod_vars[leaf]
else: # otherwise the transition target is a component, so we need to find the outflow
outgoing_trans=spch._outgoings[leaf] #the outgoing transitions
outflow=pulp.lpSum([trans_vars[f"_{leaf}_{ot._target}"] for ot in outgoing_trans])
# add the inventory to the inflow if its stock is positive
inflow=inv_vars[f"_i_{leaf}"] if self.has_positive_stock(leaf) else 0
self._prob+=outflow==inflow
# the objective: Maximize the sum of products and the sum of inventory outflows
self._prob += pulp.lpSum([v for _,v in prod_vars.items()]) + pulp.lpSum([inv for _,inv in inv_vars.items()])
def _compute_upper_bounds(self):
"""computes upper bound on inflow into any entity.
It is essential for linearization of OR constraints.
It returns a dictionary mapping an entity name into its upper bound flow.
"""
spch=self._supply_chain # the supply chain
prods=spch._products # the products in the supply chain
trans=spch._transitions # the transitions in the supply chain
upper_bound_dict=dict([(p._name,p._order_size) for p in prods])
# keep updating the upper bound until reaching a fixed point
done=False
while not done:
done=True
for t in trans:
if t._target not in upper_bound_dict:
ub=0
updated=True
for out_tr in spch._outgoings[t._target]:
if out_tr._target in upper_bound_dict:
ub += upper_bound_dict[out_tr._target]
else:
updated=False
break
if updated:
upper_bound_dict[t._target]=ub
done=False
else:
continue
return upper_bound_dict
def solve(self):
self._prob.solve()
def write_lp(self, filename):
self._prob.writeLP(filename)
def is_product(self, name):
return self._supply_chain._entity_dict[name].get_type() == en.EntityType.PROD
def has_positive_stock(self, name):
ent=self._supply_chain._entity_dict[name]
return ent.get_type() == en.EntityType.COMP and ent._stock > 0
def objective(self):
"""returns the optimal value"""
return pulp.value(self._prob.objective)
def __str__(self):
prob=self._prob
status=f"Status: {pulp.LpStatus[prob.status]}"
obj=f"Objective={self.objective()}"
opt_vals='\n'.join([f"{v.name}={v.varValue}" for v in prob.variables()])
return f"{status}\n\n{obj}\n\n{opt_vals}"
<file_sep>/tests/context.py
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import lib.entities as entities
import lib.parser as parser
import lib.supply_chain as supply_chain
import lib.solver as solver
<file_sep>/tests/PlanningSolver_test.py
import os
import unittest
from context import parser as pr
from context import supply_chain as sc
from context import solver as sl
class PlanningSolverTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(PlanningSolverTest, self).__init__(*args,**kwargs)
self._examples_dir=os.path.join(os.path.dirname(__file__), '..', 'examples')
self._test_model_dir=os.path.join(os.path.dirname(__file__), 'test_models')
def _get_solver(self, path_to_model):
par=pr.Parser(path_to_model)
stmts=par.parse()
spch=sc.SupplyChain(stmts)
return sl.PlanningSolver(spch)
def _get_solver_example(self, model_fname):
return self._get_solver(os.path.join(self._examples_dir,model_fname))
def _get_solver_testmodel(self, model_fname):
return self._get_solver(os.path.join(self._test_model_dir,model_fname))
def test_compute_upper_bounds(self):
slvr=self._get_solver_testmodel('upper_bound.txt')
uppper_bound_dict=slvr._compute_upper_bounds()
self.assertEqual(uppper_bound_dict['p1'],3)
self.assertEqual(uppper_bound_dict['p2'],8)
self.assertEqual(uppper_bound_dict['c1'],3)
self.assertEqual(uppper_bound_dict['c2'],11)
self.assertEqual(uppper_bound_dict['c3'],11)
self.assertEqual(uppper_bound_dict['c4'],8)
self.assertEqual(uppper_bound_dict['c5'],14)
if __name__=='__main__':
unittest.main()
<file_sep>/tests/Parser_test.py
import os
import unittest
from context import parser as pr
from context import entities as en
class ParserTest(unittest.TestCase):
"""Parser test"""
def __init__(self, *args, **kwargs):
super(ParserTest, self).__init__(*args, **kwargs)
self._examples_dir=os.path.join(os.path.dirname(__file__), '..', 'examples')
def _run_test(self, model_fname):
p=pr.Parser(os.path.join(self._examples_dir, model_fname))
return p.parse()
def test_model1(self):
stmts=self._run_test('example1.txt')
self.assertTrue(stmts)
self.assertEqual(len(stmts),5)
# checking types
self.assertEqual(stmts[0].get_type(), pr.StatementType.PROD_DEF)
self.assertEqual(stmts[1].get_type(), pr.StatementType.COMP_DEF)
self.assertEqual(stmts[2].get_type(), pr.StatementType.TRAN_DEF)
self.assertEqual(stmts[3].get_type(), pr.StatementType.TRAN_DEF)
self.assertEqual(stmts[4].get_type(), pr.StatementType.TRAN_DEF)
### checking the product defintion
self.assertTrue(stmts[0]._products)
self.assertEqual(len(stmts[0]._products), 2)
self.assertEqual(stmts[0]._products[0]._name, 'p1')
self.assertEqual(stmts[0]._products[0]._order_size, 10)
self.assertEqual(stmts[0]._products[0]._priority, en.ProductPriority.HIGH)
self.assertEqual(stmts[0]._products[1]._name, 'p2')
self.assertEqual(stmts[0]._products[1]._order_size, 10)
self.assertEqual(stmts[0]._products[1]._priority, en.ProductPriority.LOW)
### checking the component defintion
self.assertTrue(stmts[1]._components)
self.assertEqual(len(stmts[1]._components), 2)
self.assertEqual(stmts[1]._components[0]._name, 'c1')
self.assertEqual(stmts[1]._components[0]._stock, 0)
self.assertEqual(stmts[1]._components[1]._name, 'c2')
self.assertEqual(stmts[1]._components[1]._stock, 10)
### checking transitions
self.assertTrue(stmts[2]._transition)
self.assertTrue(stmts[3]._transition)
self.assertTrue(stmts[4]._transition)
# tr
self.assertEqual(stmts[2]._transition._target, 'c1')
self.assertTrue(stmts[2]._transition._sources is None)
self.assertEqual(stmts[2]._transition._tr_type, en.TransitionType.DIR)
# tr
self.assertEqual(stmts[3]._transition._target, 'p1')
self.assertTrue(stmts[3]._transition._sources)
self.assertEqual(len(stmts[3]._transition._sources), 2)
self.assertEqual(stmts[3]._transition._sources[0], 'c1')
self.assertEqual(stmts[3]._transition._sources[1], 'c2')
self.assertEqual(stmts[3]._transition._tr_type, en.TransitionType.OR)
# tr
self.assertEqual(stmts[4]._transition._target, 'p2')
self.assertTrue(stmts[4]._transition._sources)
self.assertEqual(len(stmts[4]._transition._sources), 1)
self.assertEqual(stmts[4]._transition._sources[0], 'c2')
self.assertEqual(stmts[4]._transition._tr_type, en.TransitionType.AND)
def test_model2(self):
stmts=self._run_test('example2.txt')
self.assertTrue(stmts)
self.assertEqual(len(stmts),7)
# checking types
self.assertEqual(stmts[0].get_type(), pr.StatementType.PROD_DEF)
self.assertEqual(stmts[1].get_type(), pr.StatementType.COMP_DEF)
self.assertEqual(stmts[2].get_type(), pr.StatementType.COMP_DEF)
self.assertEqual(stmts[3].get_type(), pr.StatementType.TRAN_DEF)
self.assertEqual(stmts[4].get_type(), pr.StatementType.TRAN_DEF)
self.assertEqual(stmts[5].get_type(), pr.StatementType.TRAN_DEF)
self.assertEqual(stmts[6].get_type(), pr.StatementType.TRAN_DEF)
### checking the product defintion
self.assertTrue(stmts[0]._products)
self.assertEqual(len(stmts[0]._products), 1)
self.assertEqual(stmts[0]._products[0]._name, 'p')
self.assertEqual(stmts[0]._products[0]._order_size, 20)
self.assertEqual(stmts[0]._products[0]._priority, en.ProductPriority.LOW)
### checking the first component defintion
self.assertTrue(stmts[1]._components)
self.assertEqual(len(stmts[1]._components), 2)
self.assertEqual(stmts[1]._components[0]._name, 'c1')
self.assertEqual(stmts[1]._components[0]._stock, 0)
self.assertEqual(stmts[1]._components[1]._name, 'c2')
self.assertEqual(stmts[1]._components[1]._stock, 0)
### checking the second component defintion
self.assertTrue(stmts[2]._components)
self.assertEqual(len(stmts[2]._components), 2)
self.assertEqual(stmts[2]._components[0]._name, 'c3')
self.assertEqual(stmts[2]._components[0]._stock, 0)
self.assertEqual(stmts[2]._components[1]._name, 'c4')
self.assertEqual(stmts[2]._components[1]._stock, 20)
### checking transitions
self.assertTrue(stmts[3]._transition)
self.assertTrue(stmts[4]._transition)
self.assertTrue(stmts[5]._transition)
self.assertTrue(stmts[6]._transition)
# tr
self.assertEqual(stmts[3]._transition._target, 'p')
self.assertTrue(stmts[3]._transition._sources)
self.assertEqual(len(stmts[3]._transition._sources), 2)
self.assertEqual(stmts[3]._transition._sources[0], 'c1')
self.assertEqual(stmts[3]._transition._sources[1], 'c2')
self.assertEqual(stmts[3]._transition._tr_type, en.TransitionType.AND)
# tr
self.assertEqual(stmts[4]._transition._target, 'c1')
self.assertTrue(stmts[4]._transition._sources)
self.assertEqual(len(stmts[4]._transition._sources), 2)
self.assertEqual(stmts[4]._transition._sources[0], 'c3')
self.assertEqual(stmts[4]._transition._sources[1], 'c4')
self.assertEqual(stmts[4]._transition._tr_type, en.TransitionType.AND)
# tr
self.assertEqual(stmts[5]._transition._target, 'c2')
self.assertTrue(stmts[5]._transition._sources)
self.assertEqual(len(stmts[5]._transition._sources), 1)
self.assertEqual(stmts[5]._transition._sources[0], 'c4')
self.assertEqual(stmts[5]._transition._tr_type, en.TransitionType.AND)
# tr
self.assertEqual(stmts[6]._transition._target, 'c3')
self.assertTrue(stmts[6]._transition._sources is None)
self.assertEqual(stmts[6]._transition._tr_type, en.TransitionType.DIR)
if __name__ == '__main__':
unittest.main()
<file_sep>/tests/AllTestsSuite.py
import unittest
import Statement_test
import Parser_test
import SupplyChain_test
import PlanningSolver_test
loader=unittest.TestLoader()
suite=unittest.TestSuite()
suite.addTest(loader.loadTestsFromModule(Statement_test))
suite.addTest(loader.loadTestsFromModule(Parser_test))
suite.addTest(loader.loadTestsFromModule(SupplyChain_test))
suite.addTest(loader.loadTestsFromModule(PlanningSolver_test))
runner=unittest.TextTestRunner(verbosity=3)
result=runner.run(suite)
<file_sep>/Makefile
init:
pip install -r requirements.txt
test:
python3 tests/AllTestsSuite.py
.PHONY: init test
<file_sep>/lib/entities.py
class EntityType:
PROD=0
COMP=1
TRAN=2
class ProductPriority:
LOW=0
HIGH=1
class Entity:
""" An entity in supply chain"""
def __init__(self, entity_type):
self._entity_type=entity_type
def get_type(self):
return self._entity_type
class Product(Entity):
"""The product class"""
def __init__(self, name, order_size, priority=ProductPriority.LOW):
"""constructs a product"""
super(Product, self).__init__(EntityType.PROD)
self._name=name
self._order_size=order_size
self._priority=priority
class Component(Entity):
"""The component class"""
def __init__(self, name, stock):
"""constructs a component"""
super(Component, self).__init__(EntityType.COMP)
self._name=name
self._stock=stock
class TransitionType:
"""The type of transition"""
AND=0
OR=1
DIR=2 # the target can be supplied directly by a supplier
class Transition(Entity):
"""The transition class"""
def __init__(self, sources, target, tr_type):
"""constructs a transition"""
super(Transition, self).__init__(EntityType.TRAN)
self._sources=sources
self._target=target
self._tr_type=tr_type
if self._tr_type == TransitionType.DIR:
self._sources=None
<file_sep>/lib/parser.py
import re
import lib.entities as en
class Pattern:
"""The pattern class defines the keywords and patterns accepted in the
grammar of supply chain description format
"""
KEYWORDS={'PROD_DEF': 'product', 'COMP_DEF': 'component', 'PR_HIGH': 'high', 'PR_LOW': 'low', 'SUPP': 'supplier'}
ID="[a-zA-Z_][a-zA-Z0-9_]*"
PRODUCT_DEF=f"\\s{KEYWORDS['PROD_DEF']}\\s"
class StatementType:
"""The type of statements are defined in this class
"""
PROD_DEF=0
COMP_DEF=1
TRAN_DEF=2
class Statement:
"""The Statement class constructs a valid statement of supply chain
description format
"""
def __init__(self, stmt_type):
self._stmt_type=stmt_type
@classmethod
def factory(cls, stmt_str):
# parse the first token
result=re.match(f"\s*(?P<first_token>{Pattern.ID})\s*(?P<the_rest>(?s:.*))",stmt_str)
if result:
if result['first_token'] == Pattern.KEYWORDS['PROD_DEF']:
return ProductDef(result['the_rest'])
elif result['first_token'] == Pattern.KEYWORDS['COMP_DEF']:
return ComponentDef(result['the_rest'])
else:
return TransitionDef(stmt_str)
else:
raise ValueError(f'Invalid statement: "{stmt_str}"')
def get_type(self):
"""returns the statement type"""
return self._stmt_type
def _tokenize_def_body(self, def_body):
def_list=def_body.split(',')
if len(def_list) == 1 and def_list[0] == '':
raise ValueError('Definition body is empty')
return def_list
def _parse(self,stmt_body):
pass
class ProductDef(Statement):
def __init__(self, stmt_body):
super(ProductDef, self).__init__(StatementType.PROD_DEF)
self._parse(stmt_body)
def _parse(self, stmt_body):
"""parses a product definition statement"""
prod_list=self._tokenize_def_body(stmt_body)
pattern=f"^(\s*(?P<pname>{Pattern.ID})\s*=\s*(?P<ord_sz>[0-9]+)(\s+(?P<priority>({Pattern.KEYWORDS['PR_HIGH']})|({Pattern.KEYWORDS['PR_LOW']})))?)$"
matcher=re.compile(pattern)
self._products=[]
for p in prod_list:
res=matcher.match(p)
if res is None:
raise ValueError('[Err] Invalid product definition.')
priority=en.ProductPriority.HIGH if res['priority'] == Pattern.KEYWORDS['PR_HIGH'] else en.ProductPriority.LOW
self._products.append(en.Product(res['pname'], int(res['ord_sz']), priority))
class ComponentDef(Statement):
def __init__(self, stmt_body):
super(ComponentDef, self).__init__(StatementType.COMP_DEF)
self._parse(stmt_body)
def _parse(self, stmt_body):
"""parses a component definition statement"""
comp_list=self._tokenize_def_body(stmt_body)
pattern=f"^(\s*(?P<cname>{Pattern.ID})\s*(=\s*(?P<stock>[0-9]+)\s*)?)$"
matcher=re.compile(pattern)
self._components=[]
for p in comp_list:
res=matcher.match(p)
if res is None:
raise ValueError('[Err] Invalid component definition.')
stock=int(res['stock']) if res['stock'] else 0
self._components.append(en.Component(res['cname'], stock))
class TransitionDef(Statement):
"""The transition definiton class
It holds information about a transition. The correct format is as follows:
{target} <- {source1} + {source2} + ...
or
{targe}: <- {source1} | {source2} | ...
or
{target} <- supplier
where {target} and {source1} ... are valid identifiers.
"""
def __init__(self, stmt_body):
super(TransitionDef, self).__init__(StatementType.TRAN_DEF)
self.parse(stmt_body)
def parse(self, stmt_body):
"""parses a tarnsition definition"""
res=re.match(f"\s*(?P<target>{Pattern.ID})\s*<-(?P<sources>(?s:.*))", stmt_body)
if res is None:
raise ValueError('[ERR] Invalid transition.')
matcher=re.compile(f"^(\s*(?P<source>{Pattern.ID})\s*)$")
if res['sources'].find('|') > 0:
tr_type=en.TransitionType.OR
source_list=res['sources'].split('|')
elif res['sources'].find('+') > 0:
tr_type=en.TransitionType.AND
source_list=res['sources'].split('+')
else:
source_list=[res['sources']]
tr_type=None
sources=[]
for src in source_list:
res_src=matcher.match(src)
if res_src is None:
raise ValueError(f'[ERR] Invalid identifier is given for transition "{src}".')
sources.append(res_src['source'])
if tr_type is None:
if sources[0] == Pattern.KEYWORDS['SUPP']:
tr_type=en.TransitionType.DIR
else:
tr_type=en.TransitionType.AND
self._transition=en.Transition(sources,res['target'],tr_type)
class Parser:
"""
The Parser class parses and an input file describing a supply chain into
a set of syntactically correct statements, each describing the definition
of either a set of products, a set of componnents or a transition.
"""
def __init__(self, modelfile):
self._modelfile=modelfile
def parse(self):
"""parses an input file describing a supply chain into a list of statements.
It returns the list of statements.
"""
empty_stmt=re.compile('^(\s*)$') # matches an empty statement
with open(self._modelfile,"r") as reader:
stmt_list=reader.read().split(';') # statements are delimited by ';'
statements=[]
for s in stmt_list:
if empty_stmt.match(s) is None: # parses only if it is not an empty statement
try:
stmt=Statement.factory(s)
statements.append(stmt)
except Exception as e:
print(f'Error when parsing statement {s}')
print(f'More details:\n{e}')
return None
return statements
<file_sep>/lib/supply_chain.py
import lib.parser as pr
class SupplyChain:
"""Supply chain class represents a supply chain
"""
def __init__(self, statements):
"""constructs a supply chain from the statements parsed from a supply chain
description.
"""
self._extract_entities(statements)
self._verify_the_chain()
self._build_outgoings()
def _extract_entities(self, statements):
"""extracts different entities (products, components and transitions) from
@param statements
"""
self._products=[]
self._components=[]
self._transitions=[]
for stmt in statements:
stmt_type=stmt.get_type()
if stmt_type==pr.StatementType.PROD_DEF:
self._products.extend(stmt._products)
elif stmt_type==pr.StatementType.COMP_DEF:
self._components.extend(stmt._components)
else:
self._transitions.append(stmt._transition)
def _verify_the_chain(self):
"""verifies in the chain that
- products and components are only once defined
- there is no undefined product or component in any transition
- there in no self loop on any product or transition
"""
# checking product duplicates
self._entity_dict={}
seen=self._entity_dict
for p in self._products:
if p._name not in seen:
seen[p._name]=p
else:
raise ValueError(f'"{p._name}" was defined multiple times.')
# checking component duplicates
for c in self._components:
if c._name not in seen:
seen[c._name]=c
else:
raise ValueError(f'"{c._name}" was defined multiple times.')
# checking transition duplicates
tseen=set()
for t in self._transitions:
if t._target not in seen:
raise KeyError(f'"{t._target}" has not been defined.')
if t._sources:
if t._target in t._sources: # a self loop
raise ValueError(f'A self loop exist on "{t._target}"')
for s in t._sources:
if s not in seen:
raise KeyError(f'"{s}" has not been defined.')
if (s, t._target) not in tseen:
tseen.add((s,t._target))
else:
raise ValueError(f'Transition from "{s}" to "{t._target}" was defined multiple times.')
else:
if (None, t._target) not in tseen:
tseen.add((None,t._target))
else:
raise ValueError(f'Transition from supplier to "{t._target}" was defined multiple times.')
def _build_outgoings(self):
"""builds the dictionary of each entity name mapped into the list of its outgoing transitions.
The dictionary is used when formulating planning LP.
It creates dictionary self._outgoings.
"""
self._outgoings={}
self._leaves=set(self._entity_dict.keys())
for tr in self._transitions:
self._leaves.discard(tr._target)
if tr._sources:
for src in tr._sources:
if src in self._outgoings:
self._outgoings[src].append(tr)
else:
self._outgoings[src]=[tr]
<file_sep>/planner.py
import sys, traceback
from lib.parser import Parser
from lib.supply_chain import SupplyChain
from lib.solver import PlanningSolver
if __name__ == '__main__':
if len(sys.argv) != 2 and len(sys.argv) != 3:
print("[ERR] Invalid usage.")
print("\n\nUsage: PROG <model> [<lp_file>]")
print("\t<model> contains the supply chain description")
print("\t<lp_file> if given, stores the LP")
exit(1)
model_fname=sys.argv[1]
lp_file=sys.argv[2] if len(sys.argv)==3 else None
try:
par=Parser(model_fname)
stmts=par.parse()
supp_chain=SupplyChain(stmts)
solver=PlanningSolver(supp_chain)
solver.solve()
print(solver)
if lp_file:
solver.write_lp(lp_file)
except Exception as e:
print(f"[ERR] Planning failed.\nReason:\n")
print("="*100)
traceback.print_exc()
exit(2)
exit(0)
| c267c6d78654fded814143dd83389254a259fc9f | [
"Markdown",
"Python",
"Makefile"
] | 13 | Markdown | hhatefi/sc_planner | d704cb8a5eb62075b992eb244ac7b45de52b1203 | 6d1ad598b17fcaa7cdf793ceb6df02cdba42b145 |
refs/heads/master | <file_sep><?php
namespace tiktok;
use App\OpenApi\Factory\BusinessApiGatewayFactory;
use App\OpenApi\Tiktok\Store\TiktokStoreApiGateway;
class AccessTokenTest extends \TestCase
{
public function testGetAccessToken()
{
$apiGateway = BusinessApiGatewayFactory::getTiktokBusinessApiGateway(TiktokStoreApiGateway::class, env("TIKTOK_STORE_APP_KEY"), env("TIKTOK_STORE_APP_SECRET"), 1);
var_dump($apiGateway->getResourceOwner()->getToken());
}
public function testRefreshAccessToken()
{
}
}
<file_sep><?php
namespace Hgs\Openapi\OauthClient;
class RefreshToken
{
const REFRESH_TIME = 60 * 60 * 3;
private $id;
private $expiresAt;
/**
* RefreshToken constructor.
* @param $id
*/
public function __construct($id, $expiresAt)
{
$this->id = $id;
$this->expiresAt = $expiresAt;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id): void
{
$this->id = $id;
}
public function notTimeToRefresh(): bool
{
if ($this->getExpiresAt() >= (time() - self::REFRESH_TIME)) {
return true;
}
return false;
}
/**
* @return mixed
*/
public function getExpiresAt()
{
return $this->expiresAt;
}
/**
* @param mixed $expiresAt
*/
public function setExpiresAt($expiresAt): void
{
$this->expiresAt = $expiresAt;
}
}
<file_sep><?php
namespace Hgs\Openapi\Transformer;
interface Transformer
{
public function transform($responseBody);
}
<file_sep><?php
namespace Hgs\Openapi\Tiktok\Store;
use Hgs\Openapi\Base\HttpClient;
use Hgs\Openapi\Factory\BusinessApiGatewayFactory;
use Hgs\Openapi\OauthClient\AccessToken;
use Hgs\Openapi\OauthClient\RefreshToken;
use Hgs\Openapi\OauthClient\ResourceOwner;
use Hgs\Openapi\OauthClient\TiktokStoreApp;
use Hgs\Openapi\Transformer\TiktokStoreResponseTransfomer;
use Illuminate\Support\Facades\DB;
class TiktokStoreResourceOwner extends ResourceOwner
{
const MODAL_TYPE = 'tiktok_store';
const ACCESS_TOKEN_ENDPOINT = "oauth2/access_token";
const REFRESH_TOKEN_ENDPOINT = "oauth2/refresh_token";
public function refreshToken()
{
$token = $this->getToken();
if (!$token) {
throw new \Exception('Token不存在');
}
if ($token->getRefreshToken()->notTimeToRefresh()) {
return $token;
}
$app = BusinessApiGatewayFactory::getAppInstances(TiktokStoreApp::IDENTIFIER);
$queryParams['app_id'] = $app->getAppId();
$queryParams['app_secret'] = $app->getAppSecret();
$queryParams['grant_type'] = 'refresh_token';
$queryParams['refresh_token'] = $token->getRefreshToken()->getId();
$url = sprintf("%s%s?%s", TiktokStoreApiGateway::HOST, self::REFRESH_TOKEN_ENDPOINT, http_build_query($queryParams));
$accessTokenData = HttpClient::request($url, TiktokStoreResponseTransfomer::class);
$refreshToken = new RefreshToken($accessTokenData['refresh_token'], time() + 60 * 60 * 24 * 14);
$accessToken = new AccessToken($accessTokenData['access_token'], time() + $accessTokenData['expires_in'], $refreshToken);
$this->storeToken($accessToken);
return $accessToken;
}
protected function storeToken(AccessToken $accessToken)
{
DB::connection('admin')
->table('external_oauth_access_token')
->updateOrInsert(
['modal_id' => $this->getId(), 'modal_type' => self::MODAL_TYPE],
[
'access_token' => $accessToken->getId(),
'refresh_token' => $accessToken->getRefreshToken()->getId(),
'refresh_token_expires_at' => date('Y-m-d H:i:s', $accessToken->getRefreshToken()->getExpiresAt()),
'access_token_expires_at' => date('Y-m-d H:i:s', $accessToken->getExpiresAt()),
]
);
}
public function requestToken()
{
$accessTokenData = DB::connection('admin')
->table('external_oauth_access_token')
->where('modal_id', $this->getId())
->where('modal_type', self::MODAL_TYPE)
->get();
if (!$accessTokenData->isEmpty()) {
$refreshToken = new RefreshToken($accessTokenData->refresh_token, $accessTokenData->refresh_token_expires_at);
return new AccessToken($accessTokenData->access_token, $accessTokenData->access_token_expires_at, $refreshToken);
}
return $this->auth($this->getAuthCode());
}
protected function auth($code): AccessToken
{
$grantType = $code ? 'authorization_code' : 'authorization_self';
$app = BusinessApiGatewayFactory::getAppInstances(TiktokStoreApp::IDENTIFIER);
$queryParams['app_id'] = $app->getAppId();
$queryParams['app_secret'] = $app->getAppSecret();
$queryParams['grant_type'] = $grantType;
if (!$code) {
$queryParams['test_shop'] = 1;
}
$queryParams['code'] = $code;
$url = sprintf("%s%s?%s", TiktokStoreApiGateway::HOST, self::ACCESS_TOKEN_ENDPOINT, http_build_query($queryParams));
$accessTokenData = HttpClient::request($url, TiktokStoreResponseTransfomer::class);
$refreshToken = new RefreshToken($accessTokenData['refresh_token'], time() + 60 * 60 * 24 * 14);
$accessToken = new AccessToken($accessTokenData['access_token'], time() + $accessTokenData['expires_in'], $refreshToken);
$this->storeToken($accessToken);
return $accessToken;
}
}
<file_sep><?php
namespace Hgs\Openapi\Command;
use Hgs\Openapi\Factory\BusinessApiGatewayFactory;
use Hgs\Openapi\OauthClient\AccessToken;
use Hgs\Openapi\OauthClient\RefreshToken;
use Hgs\Openapi\Tiktok\Store\TiktokStoreApiGateway;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class RefreshAccessToken extends Command
{
protected $signature = 'openapi:token-refresh';
protected $description = '刷新access token';
public function handle()
{
$accessTokenData = DB::connection('admin')->table('external_oauth_access_token')->get();
foreach ($accessTokenData as $token) {
$refreshToken = new RefreshToken($token->refresh_token, strtotime($token->refresh_token_expires_at));
$accessToken = new AccessToken($token->access_token, strtotime($token->access_token_expires_at), $refreshToken);
$apiGateway = BusinessApiGatewayFactory::getTiktokBusinessApiGateway(TiktokStoreApiGateway::class, env("TIKTOK_STORE_APP_KEY"), env("TIKTOK_STORE_APP_SECRET"), $token->modal_id);
$resourceOwner = $apiGateway->getResourceOwner();
$resourceOwner->setToken($accessToken);
$resourceOwner->refreshToken();
}
}
}
<file_sep><?php
namespace Hgs\Openapi\OauthClient;
class App
{
private $appId;
private $appSecret;
/**
* App constructor.
* @param $appId
* @param $appSecret
*/
public function __construct($appId, $appSecret)
{
$this->appId = $appId;
$this->appSecret = $appSecret;
}
/**
* @return mixed
*/
public function getAppId()
{
return $this->appId;
}
/**
* @param mixed $appId
*/
public function setAppId($appId): void
{
$this->appId = $appId;
}
/**
* @return mixed
*/
public function getAppSecret()
{
return $this->appSecret;
}
/**
* @param mixed $appSecret
*/
public function setAppSecret($appSecret): void
{
$this->appSecret = $appSecret;
}
}
<file_sep><?php
namespace Hgs\Openapi\Tiktok\Store;
class Order extends TiktokStoreApiGateway
{
//只能获取2021-04开始的数据
public function orderList()
{
$params = [
'create_time_start' => 1617264922,
'size' => 1,
'page' => 0
];
return $this->requestBusinessApi('order/searchList', $params);
}
public function detail($orderId)
{
$params = [
'order_id' => $orderId
];
return $this->requestBusinessApi('order/detail', $params);
}
}
<file_sep><?php
namespace Hgs\Openapi\Base;
use Hgs\Openapi\OauthClient\ResourceOwner;
use Hgs\Openapi\Transformer\TiktokStoreResponseTransfomer;
abstract class BusinessApiGateway
{
private $resourceOwner;
public function __construct($resourceOwner)
{
$this->resourceOwner = $resourceOwner;
}
/**
* @return mixed
*/
public function getResourceOwner(): ResourceOwner
{
return $this->resourceOwner;
}
/**
* @param mixed $resourceOwner
*/
public function setResourceOwner($resourceOwner): void
{
$this->resourceOwner = $resourceOwner;
}
public function requestBusinessApi($path, $params)
{
return HttpClient::request($this->buildUrl($path, $params), TiktokStoreResponseTransfomer::class);
}
protected abstract function buildUrl($path, $params);
}
<file_sep><?php
namespace Hgs\Openapi\Tiktok\Store;
use Hgs\Openapi\Base\BusinessApiGateway;
use Hgs\Openapi\Factory\BusinessApiGatewayFactory;
use Hgs\Openapi\OauthClient\TiktokStoreApp;
class TiktokStoreApiGateway extends BusinessApiGateway
{
const HOST = "https://openapi-fxg.jinritemai.com/";
const VERSION = 2;
protected function buildUrl($path, $params): string
{
$app = BusinessApiGatewayFactory::getAppInstances(TiktokStoreApp::IDENTIFIER);
$httpQueryParams['param_json'] = $this->transformParamsToJson($params);
$httpQueryParams['method'] = str_replace('/', '.', $path);
$httpQueryParams['app_key'] = $app->getAppId();
$httpQueryParams['timestamp'] = date('Y-m-d H:i:s', time());
$httpQueryParams['v'] = self::VERSION;
$httpQueryParams['sign'] = $this->sign($httpQueryParams, $app->getAppSecret());
$httpQueryParams['access_token'] = $this->getResourceOwner()->getToken()->getId();
$queryStr = http_build_query($httpQueryParams, '', '&', PHP_QUERY_RFC3986);
return sprintf("%s%s?%s", self::HOST, $path, $queryStr);
}
private function transformParamsToJson($params)
{
ksort($params);
return json_encode($params, JSON_FORCE_OBJECT);
}
private function sign($queryParams, $appSecret): string
{
ksort($queryParams);
$signStr = '';
foreach ($queryParams as $paramName => $paramValue) {
$signStr .= $paramName . $paramValue;
}
return md5($appSecret . $signStr . $appSecret);
}
}
<file_sep><?php
namespace Hgs\Openapi\Factory;
use Hgs\Openapi\Base\BusinessApiGateway;
use Hgs\Openapi\OauthClient\TiktokStoreApp;
use Hgs\Openapi\Tiktok\Store\TiktokStoreResourceOwner;
class BusinessApiGatewayFactory
{
private static $appInstances;
/**
* @return mixed
*/
public static function getAppInstances($identifier)
{
return self::$appInstances[$identifier];
}
public static function getTiktokBusinessApiGateway($class, $appId, $appSecret, $resourceId, $authCode = ''): BusinessApiGateway
{
self::$appInstances[TiktokStoreApp::IDENTIFIER] = new TiktokStoreApp($appId, $appSecret);
$resourceOwner = new TiktokStoreResourceOwner($resourceId, $authCode);
return new $class($resourceOwner);
}
}
<file_sep><?php
namespace Hgs\Openapi\OauthClient;
class TiktokStoreApp extends App
{
const IDENTIFIER = 'tiktok';
}
<file_sep># 开源API封装
## 安装vendor publish
```php
composer require laravelista/lumen-vendor-publish:7.x
app\Console\Kernel.php 中加入 VendorPublishCommand::class
```
## 安装hgs/openapi
```php
composer require hgs/openapi dev-master
bootstrap/app.php中注册提供者$app->register(Hgs\Openapi\OpenapiServiceProvider::class);
php artisan vendor:publish
php artisan migrate
```
## 使用
```php
$orderApiGateway = BusinessApiGatewayFactory::getTiktokBusinessApiGateway(Order::class, env("TIKTOK_STORE_APP_KEY"), env("TIKTOK_STORE_APP_SECRET"), 1);
$data = $orderApiGateway->orderList();
```
<file_sep><?php
namespace Hgs\Openapi\Transformer;
class TiktokStoreResponseTransfomer implements Transformer
{
public function transform($responseBody)
{
$data = json_decode($responseBody, true);
if ($data['err_no']) {
throw new \Exception($data['message']);
}
return $data['data'];
}
}
<file_sep><?php
namespace Hgs\Openapi\Base;
use GuzzleHttp\Client;
class HttpClient
{
public static function request($url, $responseFormater)
{
$response = (new Client())->get($url)->getBody()->getContents();
$formater = new $responseFormater;
return $formater->transform($response);
}
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateOauthClientAccessToken extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::connection('admin')->create('external_oauth_access_token', function (Blueprint $table) {
$table->id();
$table->string('access_token', 100)->comment('');
$table->string('refresh_token', 100)->comment('刷新token');
$table->dateTime('refresh_token_expires_at')->comment('过期时间');
$table->dateTime('access_token_expires_at')->comment('过期时间');
$table->text('scopes')->comment('范围');
$table->integer('modal_id', false, true)->nullable(false)->default(0)->index()->comment('关联ID');
$table->string('modal_type', 100)->nullable(false)->default('')->comment('关联类型');
$table->index(['modal_type', 'modal_id']);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::connection('admin')->dropIfExists('external_oauth_access_token');
}
}
<file_sep><?php
namespace Hgs\Openapi\OauthClient;
abstract class ResourceOwner
{
private $id;
private $authCode;
private $token;
/**
* ResourceOwner constructor.
* @param $id
* @param $code
*/
public function __construct($id = '', $authCode = '')
{
$this->id = $id;
$this->authCode = $authCode;
}
/**
* @return mixed
*/
public function getAuthCode()
{
return $this->authCode;
}
/**
* @param mixed $authCode
*/
public function setAuthCode($authCode): void
{
$this->authCode = $authCode;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id): void
{
$this->id = $id;
}
public function getToken(): AccessToken
{
if ($this->token) {
return $this->token;
}
return $this->requestToken();
}
public function setToken($token)
{
$this->token = $token;
}
public abstract function requestToken();
public abstract function refreshToken();
protected abstract function storeToken(AccessToken $accessToken);
}
<file_sep><?php
namespace tiktok;
use App\OpenApi\Factory\BusinessApiGatewayFactory;
use App\OpenApi\Tiktok\Store\Order;
class OrderTest extends \TestCase
{
public function testOrderList()
{
$orderApiGateway = BusinessApiGatewayFactory::getTiktokBusinessApiGateway(Order::class, env("TIKTOK_STORE_APP_KEY"), env("TIKTOK_STORE_APP_SECRET"), 1);
$data = $orderApiGateway->orderList();
var_dump($data);
}
public function testOrderDetail()
{
$orderApiGateway = BusinessApiGatewayFactory::getTiktokBusinessApiGateway(Order::class, env("TIKTOK_STORE_APP_KEY"), env("TIKTOK_STORE_APP_SECRET"), 1);
$data = $orderApiGateway->detail('4804807930112619658A');
var_dump($data);
}
}
<file_sep><?php
namespace Hgs\Openapi\OauthClient;
class AccessToken
{
private $id;
private $expiresAt;
private $scopes;
/**
* @var RefreshToken
*/
private $refreshToken;
/**
* AccessToken constructor.
* @param $id
*/
public function __construct($id, $expiresAt, $refreshToken, $scopes = '')
{
$this->id = $id;
$this->expiresAt = $expiresAt;
$this->scopes = $scopes;
$this->refreshToken = $refreshToken;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id): void
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getExpiresAt()
{
return $this->expiresAt;
}
/**
* @param mixed $expiresAt
*/
public function setExpiresAt($expiresAt): void
{
$this->expiresAt = $expiresAt;
}
/**
* @return mixed
*/
public function getScopes()
{
return $this->scopes;
}
/**
* @param mixed $scopes
*/
public function setScopes($scopes): void
{
$this->scopes = $scopes;
}
/**
* @return mixed
*/
public function getRevoked()
{
return $this->revoked;
}
/**
* @param mixed $revoked
*/
public function setRevoked($revoked): void
{
$this->revoked = $revoked;
}
/**
* @return mixed
*/
public function getRefreshToken()
{
return $this->refreshToken;
}
/**
* @param mixed $refreshToken
*/
public function setRefreshToken($refreshToken): void
{
$this->refreshToken = $refreshToken;
}
}
<file_sep><?php
namespace Hgs\Openapi;
use Hgs\Openapi\Command\RefreshAccessToken;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;
class OpenapiServiceProvider extends ServiceProvider
{
public function boot(Filesystem $filesystem)
{
$this->publishes([
__DIR__ . '/../database/migrations/create_oauth_client_access_token.php' => $this->getMigrationFileName($filesystem),
], 'migrations');
$this->commands([
RefreshAccessToken::class
]);
}
protected function getMigrationFileName(Filesystem $filesystem): string
{
$timestamp = date('Y_m_d_His');
return Collection::make($this->app->databasePath() . DIRECTORY_SEPARATOR . 'migrations' . DIRECTORY_SEPARATOR)
->flatMap(function ($path) use ($filesystem) {
return $filesystem->glob($path . '*_create_oauth_client_access_token.php');
})->push($this->app->databasePath() . "/migrations/{$timestamp}_create_oauth_client_access_token.php")
->first();
}
public function register()
{
parent::register(); // TODO: Change the autogenerated stub
}
}
| afe3b05240b9559c7f9a8a01728b9401eda35c25 | [
"Markdown",
"PHP"
] | 19 | PHP | fengzewen/openapi | d20da778f6a66c67fff3c8291a2b3ef83f464928 | 4e3cebc31a62a5fc2badcbf9e5a658c61688d49f |
refs/heads/master | <file_sep><?php
error_reporting(E_ERROR | E_PARSE);
$the_server="";
$the_stats_file="/status.xsl";
$is_shoutcast=true;
$streamtitle="";
$streamgenre="";
if (!isset($_GET['translateAllRadioStations'])) {
$translateAllRadioStations="ALL RADIO STATIONS";
} else {
$translateAllRadioStations=$_GET['translateAllRadioStations'];
}
if (!isset($_GET['the_stream']) || !isset($_GET['cur_i'])) {
//nothing
die();
} else {
$the_link=trim($_GET['the_stream']);
if (strpos($the_link,'radionomy.com')) { //is a radionomy.com link
$streamgenre=$translateAllRadioStations;
preg_match ( '#^http://(.*)/(.*)#' , $the_link, $matches);
$streamtitle=$matches[2];
} else {
preg_match ( '#^http://(.*):(.*)/|;#' , $the_link, $matches);
$ip=$matches[1];
$port=$matches[2];
//echo $ip.' --- '.$port.' --- ';
//shoutcast start
$fp = @fsockopen($ip,$port,$errno,$errstr,1);
if (!$fp) {
$streamtitle = "Connection timed out or the server is offline"; // If you always get this error then it means your web host is blocking outward connections. If you ask nicely, they might add your server IP to their allow list.
//$is_shoutcast=false;
} else {
fputs($fp, "GET /index.html HTTP/1.0\r\nUser-Agent: Mozilla\r\n\r\n");
while (!feof($fp)) {
$info = fgets($fp);
}
$info = str_replace('</body></html>', "", $info);
$split = explode('Stream Title: </font></td><td><font class=default><b>', $info);
if (count($split)>=2) { // is shoutcast
$split = explode('</b></td></tr><tr>', $split[1]);
$streamtitle = $split[0];
//the genre
$split_genre = explode('Stream Genre: </font></td><td><font class=default><b>', $info);
$split_genre = explode('</b></td></tr>', $split_genre[1]);
$streamgenre = $split_genre[0];
} else {
$is_shoutcast=false;
}
}
//shoutcast end
//icecast start
if ($is_shoutcast===false) {
$the_server='http://'.$ip.':'.$port;
//get statistics file contents
$fp = fopen($the_server.$the_stats_file,'r');
if(!$fp) {
//error connecting to server!
$streamtitle = "Unable to connect to Icecast server.";
} else {
$stats_file_contents = '';
while(!feof($fp)) {
$stats_file_contents .= fread($fp,1024);
}
fclose($fp);
//create array to store results for later usage
$radio_info = array();
$radio_info['server'] = $the_server;
$radio_info['title'] = '';
$radio_info['description'] = '';
$radio_info['content_type'] = '';
$radio_info['mount_start'] = '';
$radio_info['bit_rate'] = '';
$radio_info['listeners'] = '';
$radio_info['most_listeners'] = '';
$radio_info['genre'] = '';
$radio_info['url'] = '';
$radio_info['now_playing'] = array();
$radio_info['now_playing']['artist'] = '';
$radio_info['now_playing']['track'] = '';
$temp = array();
//format results into array
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$stats_file_contents,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($temp,$to_push);
}
}
//build final array from temp array
$radio_info['title'] = $temp[0];
$radio_info['description'] = $temp[1];
$radio_info['content_type'] = $temp[2];
$radio_info['mount_start'] = $temp[3];
$radio_info['bit_rate'] = $temp[4];
$radio_info['listeners'] = $temp[5];
$radio_info['most_listeners'] = $temp[6];
$radio_info['genre'] = $temp[7];
$radio_info['url'] = $temp[8];
$streamtitle=$radio_info['title'];
$streamgenre=$radio_info['genre'];
}
}
//icecast end
if (trim($streamtitle)!='') {
//nothing
} else {
$streamtitle='The stream title is currently empty';
}/**/
if (trim($streamgenre)!='') {
$streamgenre=str_replace ( "," , ";" , $streamgenre);
} else {
//$streamgenre='No genre available';
}
$streamgenre=$translateAllRadioStations.";".$streamgenre;
//echo $_GET['cur_i'].'#----#'.'http://'.$ip.':'.$port.$the_stats_file.count($split).' ---- '.$is_shoutcast;
}
echo $_GET['cur_i'].'#----#'.strip_tags($streamtitle).'#----#'.strip_tags($streamgenre);
}
?><file_sep>LX6
===
<file_sep><?php
/*
Now Playing PHP script for SHOUTcast
This script is (C) MixStream.net 2008
Feel free to modify this free script
in any other way to suit your needs.
Version: v1.1
*/
/* ----------- Server configuration ---------- */
$songtitle="";
if (!isset($_GET['the_stream'])) {
//nothing
die();
} else {
$the_link=trim($_GET['the_stream']);
if (strpos($the_link,'radionomy.com')) { //is a radionomy.com link
$songtitle="The song title is not available";
} else {
preg_match ( '#^http://(.*):(.*)/|;#' , $the_link, $matches);
$ip=$matches[1];
$port=$matches[2];
//echo $ip.' --- '.$port.' --- ';
$fp = @fsockopen($ip,$port,$errno,$errstr,1);
if (!$fp) {
$songtitle="The song title is not available - Connection refused"; // sever is offline
} else {
fputs($fp, "GET /7.html HTTP/1.0\r\nUser-Agent: Mozilla\r\n\r\n");
while (!feof($fp)) {
$info = fgets($fp);
}
if (trim($info)) { // is shoutcast
$info = str_replace('</body></html>', "", $info);
$split = explode(',', $info);
if (empty($split[6]) ) {
$songtitle="The song title is not available"; // sever is online but no song title
} else {
$title = str_replace('\'', '`', $split[6]);
$title = str_replace(',', ' ', $title);
$songtitle="$title"; // Diaplays song
}
} else {
//icecast start
$the_server='http://'.$ip.':'.$port;
$the_stats_file="/status.xsl";
//get statistics file contents
$fp = fopen($the_server.$the_stats_file,'r');
if(!$fp) {
//error connecting to server!
$songtitle = "The song title is not available - Unable to connect to Icecast server.";
}
$stats_file_contents = '';
while(!feof($fp)) {
$stats_file_contents .= fread($fp,1024);
}
fclose($fp);
//create array to store results for later usage
$radio_info = array();
$radio_info['server'] = $the_server;
$radio_info['title'] = '';
$radio_info['description'] = '';
$radio_info['content_type'] = '';
$radio_info['mount_start'] = '';
$radio_info['bit_rate'] = '';
$radio_info['listeners'] = '';
$radio_info['most_listeners'] = '';
$radio_info['genre'] = '';
$radio_info['url'] = '';
$radio_info['now_playing'] = array();
$radio_info['now_playing']['artist'] = '';
$radio_info['now_playing']['track'] = '';
$temp = array();
//format results into array
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$stats_file_contents,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($temp,$to_push);
}
}
//build final array from temp array
if (count($temp)>=1) {
$radio_info['title'] = $temp[0];
}
if (count($temp)>=2) {
$radio_info['description'] = $temp[1];
}
if (count($temp)>=3) {
$radio_info['content_type'] = $temp[2];
}
if (count($temp)>=4) {
$radio_info['mount_start'] = $temp[3];
}
if (count($temp)>=5) {
$radio_info['bit_rate'] = $temp[4];
}
if (count($temp)>=6) {
$radio_info['listeners'] = $temp[5];
}
if (count($temp)>=7) {
$radio_info['most_listeners'] = $temp[6];
}
if (count($temp)>=8) {
$radio_info['genre'] = $temp[7];
}
if (count($temp)>=9) {
$radio_info['url'] = $temp[8];
}
//format now playing
/*$now_playing = explode(" - ",$temp[9]);
$radio_info['now_playing']['artist'] = $now_playing[0];
$radio_info['now_playing']['track'] = $now_playing[1];*/
if (count($temp)>=10) {
$songtitle=$temp[9];
}
//icecast end
}
}
/*echo $songtitle;
if (file_exists('http://'.$ip.':'.$port.'/7.html')) {
echo "The file 7.html exists";
} else {
echo 'The file 7.html does not exist'.'http://'.$ip.':'.$port.'/7.html';
}*/
}
if (trim($songtitle)=='') {
$songtitle="The song title is not available";
}
echo $songtitle;
}
?>
| 52152c6d7d099a93edcf876c4fd3e0c9c2db3528 | [
"Markdown",
"PHP"
] | 3 | PHP | gogekkos/LX6 | 030baa04987fcef996cb91d617b21d156d5271f6 | 39af6d13a2e3fd7425381c86b9eea611c88fc285 |
refs/heads/master | <file_sep>// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {TeamTypes, ThreadTypes} from 'action_types';
import deepFreeze from 'utils/deep_freeze';
import threadsReducer from './threads';
describe('threads', () => {
test('RECEIVED_THREADS should update the state', () => {
const state = deepFreeze({
threadsInTeam: {},
threads: {},
counts: {},
});
const nextState = threadsReducer(state, {
type: ThreadTypes.RECEIVED_THREADS,
data: {
team_id: 'a',
threads: [
{id: 't1'},
],
total: 3,
unread_mentions_per_channel: {},
total_unread_threads: 0,
total_unread_mentions: 1,
},
});
expect(nextState).not.toBe(state);
expect(nextState.threads.t1).toEqual({
id: 't1',
});
expect(nextState.counts.a).toEqual({
total: 3,
total_unread_threads: 0,
unread_mentions_per_channel: {},
total_unread_mentions: 1,
});
expect(nextState.threadsInTeam.a).toContain('t1');
});
test('RECEIVED_PER_CHANNEL_MENTION_COUNTS should update the state', () => {
const state = deepFreeze({
threadsInTeam: {},
threads: {},
counts: {
a: {
total: 3,
total_unread_threads: 0,
total_unread_mentions: 2,
},
},
});
const nextState = threadsReducer(state, {
type: ThreadTypes.RECEIVED_PER_CHANNEL_MENTION_COUNTS,
data: {
team_id: 'a',
counts: {a: 2},
},
});
expect(nextState).not.toBe(state);
expect(nextState.counts.a).toEqual({
total: 3,
total_unread_threads: 0,
unread_mentions_per_channel: {a: 2},
total_unread_mentions: 2,
});
});
test('LEAVE_TEAM should clean the state', () => {
const state = deepFreeze({
threadsInTeam: {},
threads: {},
counts: {},
});
let nextState = threadsReducer(state, {
type: ThreadTypes.RECEIVED_THREADS,
data: {
team_id: 'a',
threads: [
{id: 't1'},
],
total: 3,
unread_mentions_per_channel: {},
total_unread_threads: 0,
total_unread_mentions: 1,
},
});
expect(nextState).not.toBe(state);
// leave team
nextState = threadsReducer(state, {
type: TeamTypes.LEAVE_TEAM,
data: {
id: 'a',
},
});
expect(nextState.threads.t1).toBe(undefined);
expect(nextState.counts.a).toBe(undefined);
expect(nextState.threadsInTeam.a).toBe(undefined);
});
});
| 66af1225e05870c7d6395b8f11315740baab35ad | [
"JavaScript"
] | 1 | JavaScript | wiggin77/mattermost-redux | 041dc98731d1317c7d4f8014d79f81d1e9e80663 | 758bdadca83a25619bc4205df3f1bda27b1e626c |
refs/heads/master | <file_sep>using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Newtonsoft.Json;
namespace AirVinyl.Model
{
public class DynamicProperty
{
[Key] [Column(Order = 1)] public string Key { get; set; }
[Key] [Column(Order = 2)] public int VinylRecordId { get; set; }
public string SerializedValue { get; set; }
public object Value
{
get => JsonConvert.DeserializeObject(SerializedValue);
set => SerializedValue = JsonConvert.SerializeObject(value);
}
public virtual VinylRecord VinylRecord { get; set; }
}
}<file_sep>using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Http;
using AirVinyl.API.Helpers;
using AirVinyl.DataAccessLayer;
using AirVinyl.Model;
using Microsoft.AspNet.OData;
using Microsoft.AspNet.OData.Routing;
namespace AirVinyl.API.Controllers
{
public class PersonController : ODataController
{
private readonly AirVinylDbContext _ctx = new AirVinylDbContext();
[HttpGet]
[ODataRoute("Tim")]
public IHttpActionResult GetSingletonKevin()
{
var personTim = _ctx.People.FirstOrDefault(p => p.PersonId == 6);
return Ok(personTim);
}
[HttpGet]
[ODataRoute("Tim/Email")]
[ODataRoute("Tim/FirstName")]
[ODataRoute("Tim/LastName")]
[ODataRoute("Tim/DateOfBirth")]
[ODataRoute("Tim/Gender")]
public IHttpActionResult GetPersonProperty()
{
var person = _ctx.People.FirstOrDefault(p => p.PersonId == 6);
if (person == null) return NotFound();
var propertyToGet = Url.Request.RequestUri.Segments.Last();
if (person.HasProperty(propertyToGet) == false) return NotFound();
var propertyValue = person.GetValue(propertyToGet);
if (propertyValue == null) return StatusCode(HttpStatusCode.NoContent);
return this.CreateOKHttpActionResult(propertyValue);
}
[HttpGet]
[ODataRoute("Tim/Email/$value")]
[ODataRoute("Tim/FirstName/$value")]
[ODataRoute("Tim/LastName/$value")]
[ODataRoute("Tim/DateOfBirth/$value")]
[ODataRoute("Tim/Gender/$value")]
public IHttpActionResult GetPersonRawProperty()
{
var person = _ctx.People.FirstOrDefault(p => p.PersonId == 6);
if (person == null) return NotFound();
var propertyToGet = Url.Request.RequestUri.Segments[Url.Request.RequestUri.Segments.Length - 2]
.TrimEnd('/');
if (person.HasProperty(propertyToGet) == false) return NotFound();
var propertyValue = person.GetValue(propertyToGet);
if (propertyValue == null) return StatusCode(HttpStatusCode.NoContent);
return this.CreateOKHttpActionResult(propertyValue.ToString());
}
[HttpGet]
[EnableQuery]
[ODataRoute("Tim/Friends")]
public IHttpActionResult GetPersonCollectionProperty()
{
var person = _ctx.People.Include(p => p.Friends).Include(p => p.VinylRecords)
.FirstOrDefault(p => p.PersonId == 6);
if (person == null) return NotFound();
var collectionPropertyToGet = Url.Request.RequestUri.Segments.Last();
if (person.HasProperty(collectionPropertyToGet) == false) return NotFound();
var collectionPropertyValue = person.GetValue(collectionPropertyToGet);
return this.CreateOKHttpActionResult(collectionPropertyValue);
}
[HttpGet]
[EnableQuery]
[ODataRoute("Tim/VinylRecords")]
public IHttpActionResult GetVinylRecordsForPerson()
{
var person = _ctx.People.FirstOrDefault(p => p.PersonId == 6);
if (person == null) return NotFound();
return Ok(_ctx.VinylRecords.Where(v => v.Person.PersonId == 6));
}
[HttpPatch]
[ODataRoute("Tim")]
public IHttpActionResult PartiallyUpdateTime(Delta<Person> patch)
{
if (ModelState.IsValid == false) return BadRequest(ModelState);
var currentPerson = _ctx.People.FirstOrDefault(p => p.PersonId == 6);
if (currentPerson == null) return NotFound();
patch.Patch(currentPerson);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
protected override void Dispose(bool disposing)
{
_ctx.Dispose();
base.Dispose(disposing);
}
}
}<file_sep>using System;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Http;
using AirVinyl.API.Helpers;
using AirVinyl.DataAccessLayer;
using AirVinyl.Model;
using Microsoft.AspNet.OData;
using Microsoft.AspNet.OData.Routing;
namespace AirVinyl.API.Controllers
{
public class PeopleController : ODataController
{
private readonly AirVinylDbContext _ctx = new AirVinylDbContext();
[EnableQuery]
public IHttpActionResult Get()
{
return Ok(_ctx.People.AsQueryable());
}
[EnableQuery]
public IHttpActionResult Get([FromODataUri] int key)
{
var people = _ctx.People.Where(p => p.PersonId == key);
if (people.Any() == false) return NotFound();
return Ok(SingleResult.Create(people));
}
[HttpGet]
[ODataRoute("People({key})/Email")]
[ODataRoute("People({key})/FirstName")]
[ODataRoute("People({key})/LastName")]
[ODataRoute("People({key})/DateOfBirth")]
[ODataRoute("People({key})/Gender")]
public IHttpActionResult GetPersonProperty([FromODataUri] int key)
{
var person = _ctx.People.FirstOrDefault(p => p.PersonId == key);
if (person == null) return NotFound();
var propertyToGet = Url.Request.RequestUri.Segments.Last();
if (person.HasProperty(propertyToGet) == false) return NotFound();
var propertyValue = person.GetValue(propertyToGet);
if (propertyValue == null) return StatusCode(HttpStatusCode.NoContent);
return Created(propertyValue);
}
[HttpGet]
[EnableQuery]
[ODataRoute("People({key})/VinylRecords")]
public IHttpActionResult GetVinylRecordsForPerson([FromODataUri] int key)
{
var person = _ctx.People.FirstOrDefault(p => p.PersonId == key);
if (person == null) return NotFound();
return Ok(_ctx.VinylRecords.Where(v => v.Person.PersonId == key));
}
[HttpGet]
[EnableQuery]
[ODataRoute("People({key})/VinylRecords({vinylRecordKey})")]
public IHttpActionResult GetVinylRecordForPerson([FromODataUri] int key, [FromODataUri] int vinylRecordKey)
{
var person = _ctx.People.FirstOrDefault(p => p.PersonId == key);
if (person == null) return NotFound();
var vinylRecords =
_ctx.VinylRecords
.Include(v => v.DynamicVinylRecordProperties)
.Where(v => v.Person.PersonId == key && v.VinylRecordId == vinylRecordKey);
if (vinylRecords.Any() == false) return NotFound();
return Ok(SingleResult.Create(vinylRecords));
}
[HttpPost]
[ODataRoute("People({key})/VinylRecords")]
public IHttpActionResult CreateVinylRecordForPerson([FromODataUri] int key, VinylRecord vinylRecord)
{
if (ModelState.IsValid == false) return BadRequest(ModelState);
var person = _ctx.People.FirstOrDefault(p => p.PersonId == key);
if (person == null) return NotFound();
vinylRecord.Person = person;
_ctx.VinylRecords.Add(vinylRecord);
_ctx.SaveChanges();
return Created(vinylRecord);
}
[HttpPatch]
[ODataRoute("People({key})/VinylRecords({vinylRecordKey})")]
public IHttpActionResult PartiallyUpdateVinylRecordForPerson([FromODataUri] int key,
[FromODataUri] int vinylRecordKey, Delta<VinylRecord> patch)
{
if (ModelState.IsValid == false) return BadRequest(ModelState);
var person = _ctx.People.FirstOrDefault(p => p.PersonId == key);
if (person == null) return NotFound();
var currentVinylRecord =
_ctx.VinylRecords
.Include(v => v.DynamicVinylRecordProperties)
.FirstOrDefault(v => v.Person.PersonId == key && v.VinylRecordId == vinylRecordKey);
if (currentVinylRecord == null) return NotFound();
patch.Patch(currentVinylRecord);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
[HttpDelete]
[ODataRoute("People({key})/VinylRecords({vinylRecordKey})")]
public IHttpActionResult DeleteVinylRecordForPerson([FromODataUri] int key, [FromODataUri] int vinylRecordKey)
{
var person = _ctx.People.FirstOrDefault(p => p.PersonId == key);
if (person == null) return NotFound();
var currentVinylRecord =
_ctx.VinylRecords.FirstOrDefault(v => v.Person.PersonId == key && v.VinylRecordId == vinylRecordKey);
if (currentVinylRecord == null) return NotFound();
_ctx.VinylRecords.Remove(currentVinylRecord);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
[HttpGet]
[ODataRoute("People({key})/Friends")]
[EnableQuery]
public IHttpActionResult GetPersonCollectionProperty([FromODataUri] int key)
{
var person = _ctx.People.Include(p => p.Friends).Include(p => p.VinylRecords)
.FirstOrDefault(p => p.PersonId == key);
if (person == null) return NotFound();
var collectionPropertyToGet = Url.Request.RequestUri.Segments.Last();
if (person.HasProperty(collectionPropertyToGet) == false) return NotFound();
var collectionPropertyValue = person.GetValue(collectionPropertyToGet);
return this.CreateOKHttpActionResult(collectionPropertyValue);
}
[HttpGet]
[ODataRoute("People({key})/Email/$value")]
[ODataRoute("People({key})/FirstName/$value")]
[ODataRoute("People({key})/LastName/$value")]
[ODataRoute("People({key})/DateOfBirth/$value")]
[ODataRoute("People({key})/Gender/$value")]
public IHttpActionResult GetPersonPropertyRawValue([FromODataUri] int key)
{
var person = _ctx.People.FirstOrDefault(p => p.PersonId == key);
if (person == null) return NotFound();
var propertyToGet = Url.Request.RequestUri.Segments[Url.Request.RequestUri.Segments.Length - 2]
.TrimEnd('/');
if (person.HasProperty(propertyToGet) == false) return NotFound();
var propertyValue = person.GetValue(propertyToGet);
if (propertyValue == null) return StatusCode(HttpStatusCode.NoContent);
return this.CreateOKHttpActionResult(propertyValue.ToString());
}
public IHttpActionResult Post(Person person)
{
if (ModelState.IsValid == false) return BadRequest(ModelState);
_ctx.People.Add(person);
_ctx.SaveChanges();
return Created(person);
}
public IHttpActionResult Put([FromODataUri] int key, Person person)
{
if (ModelState.IsValid == false) return BadRequest(ModelState);
var currentPerson = _ctx.People.FirstOrDefault(p => p.PersonId == key);
if (currentPerson == null) return NotFound();
person.PersonId = currentPerson.PersonId;
_ctx.Entry(currentPerson).CurrentValues.SetValues(person);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
public IHttpActionResult Patch([FromODataUri] int key, Delta<Person> patch)
{
if (ModelState.IsValid == false) return BadRequest(ModelState);
var currentPerson = _ctx.People.FirstOrDefault(p => p.PersonId == key);
if (currentPerson == null) return NotFound();
patch.Patch(currentPerson);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
public IHttpActionResult Delete([FromODataUri] int key)
{
var currentPerson = _ctx.People.Include(p => p.Friends).FirstOrDefault(p => p.PersonId == key);
if (currentPerson == null) return NotFound();
var peopleWithCurrentPersonAsFriends = _ctx.People
.Include(p => p.Friends)
.Where(p => p.Friends.Select(f => f.PersonId).AsQueryable().Contains(key));
foreach (var person in peopleWithCurrentPersonAsFriends) person.Friends.Remove(currentPerson);
_ctx.People.Remove(currentPerson);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
// POST odata/People('key')/Friends/$ref
[HttpPost]
[ODataRoute("People({key})/Friends/$ref")]
public IHttpActionResult CreateLinkToFriend([FromODataUri] int key, [FromBody] Uri link)
{
var currentPerson = _ctx.People.Include(p => p.Friends).FirstOrDefault(p => p.PersonId == key);
if (currentPerson == null) return NotFound();
var keyOfFriendToAdd = Request.GetKeyValue<int>(link);
if (currentPerson.Friends.Any(f => f.PersonId == keyOfFriendToAdd))
return BadRequest(
$"The person with id {key} is already linked to the person with id {keyOfFriendToAdd}");
var friendToLinkTo = _ctx.People.FirstOrDefault(f => f.PersonId == keyOfFriendToAdd);
if (friendToLinkTo == null) return NotFound();
currentPerson.Friends.Add(friendToLinkTo);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
[HttpPut]
[ODataRoute("People({key})/Friends({relatedKey})/$ref")]
public IHttpActionResult UpdateLinkToFriend([FromODataUri] int key, [FromODataUri] int relatedKey,
[FromBody] Uri link)
{
var currentPerson = _ctx.People.Include(p => p.Friends).FirstOrDefault(p => p.PersonId == key);
if (currentPerson == null) return NotFound();
var currentFriend = _ctx.People.Include(p => p.Friends).FirstOrDefault(p => p.PersonId == relatedKey);
if (currentFriend == null) return NotFound();
var keyOfFriendToAdd = Request.GetKeyValue<int>(link);
if (currentPerson.Friends.Any(f => f.PersonId == keyOfFriendToAdd))
return BadRequest(
$"The person with id {key} is already linked to the person with id {keyOfFriendToAdd}");
var friendToLinkTo = _ctx.People.FirstOrDefault(f => f.PersonId == keyOfFriendToAdd);
if (friendToLinkTo == null) return NotFound();
currentPerson.Friends.Remove(currentPerson);
currentFriend.Friends.Add(friendToLinkTo);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
[HttpDelete]
[ODataRoute("People({key})/Friends({relatedKey})/$ref")]
public IHttpActionResult DeleteLinkToFriend([FromODataUri] int key, [FromODataUri] int relatedKey)
{
var currentPerson = _ctx.People.Include(p => p.Friends).FirstOrDefault(p => p.PersonId == key);
if (currentPerson == null) return NotFound();
var currentFriend = _ctx.People.Include(p => p.Friends).FirstOrDefault(p => p.PersonId == relatedKey);
if (currentFriend == null) return NotFound();
currentPerson.Friends.Remove(currentFriend);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
protected override void Dispose(bool disposing)
{
_ctx.Dispose();
base.Dispose(disposing);
}
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using AirVinyl.API.Helpers;
using AirVinyl.DataAccessLayer;
using AirVinyl.Model;
using Microsoft.AspNet.OData;
using Microsoft.AspNet.OData.Routing;
namespace AirVinyl.API.Controllers
{
public class RecordStoresController : ODataController
{
// context
private readonly AirVinylDbContext _ctx = new AirVinylDbContext();
// GET odata/RecordStores
[EnableQuery]
public IHttpActionResult Get()
{
return Ok(_ctx.RecordStores);
}
// GET odata/RecordStores(key)
[EnableQuery]
public IHttpActionResult Get([FromODataUri] int key)
{
var recordStores = _ctx.RecordStores.Where(p => p.RecordStoreId == key);
if (!recordStores.Any()) return NotFound();
return Ok(SingleResult.Create(recordStores));
}
[HttpGet]
[ODataRoute("RecordStores({key})/Tags")]
[EnableQuery]
public IHttpActionResult GetRecordStoreTagsProperty([FromODataUri] int key)
{
// no Include necessary for EF - Tags isn't a navigation property
// in the entity model.
var recordStore = _ctx.RecordStores.FirstOrDefault(p => p.RecordStoreId == key);
if (recordStore == null) return NotFound();
var collectionPropertyToGet = Url.Request.RequestUri.Segments.Last();
var collectionPropertyValue = recordStore.GetValue(collectionPropertyToGet);
// return the collection of tags
return this.CreateOKHttpActionResult(collectionPropertyValue);
}
[HttpGet]
[ODataRoute("RecordStores({key})/AirVinyl.Functions.IsHighRated(minimumRating={minimumRating})")]
public bool IsHighRated([FromODataUri] int key, int minimumRating)
{
var recordStore = _ctx.RecordStores.FirstOrDefault(rs =>
rs.RecordStoreId == key &&
rs.Ratings.Any() &&
rs.Ratings.Sum(rating => rating.Value) / rs.Ratings.Count >= minimumRating);
return recordStore != null;
}
[HttpGet]
[ODataRoute("RecordStores/AirVinyl.Functions.AreRatedBy(personIds={personIds})")]
public IHttpActionResult AreRatedBy([FromODataUri] IEnumerable<int> personIds)
{
var recordStores =
_ctx.RecordStores.Where(rs =>
rs.Ratings.Any(rating =>
personIds.Contains(rating.RatedBy.PersonId)));
return this.CreateOKHttpActionResult(recordStores);
}
[HttpGet]
[ODataRoute("GetHighRatedRecordStores(minimumRating={minimumRating})")]
public IHttpActionResult IsHighRated(int minimumRating)
{
var recordStores = _ctx.RecordStores.Where(rs =>
rs.Ratings.Any() &&
rs.Ratings.Sum(rating => rating.Value) / rs.Ratings.Count >= minimumRating);
return this.CreateOKHttpActionResult(recordStores);
}
[HttpPost]
[ODataRoute("RecordStores({key})/AirVinyl.Actions.Rate")]
public IHttpActionResult Rate([FromODataUri] int key, ODataActionParameters parameters)
{
var recordStore = _ctx.RecordStores.FirstOrDefault(rs => rs.RecordStoreId == key);
if (recordStore == null) return NotFound();
if (parameters.TryGetValue("rating", out var outputFromDictionary) == false) return NotFound();
if (int.TryParse(outputFromDictionary.ToString(), out var rating) == false) return NotFound();
if (parameters.TryGetValue("personId", out outputFromDictionary) == false) return NotFound();
if (int.TryParse(outputFromDictionary.ToString(), out var personId) == false) return NotFound();
var person = _ctx.People.FirstOrDefault(rs => rs.PersonId == personId);
if (person == null) return NotFound();
recordStore.Ratings.Add(new Rating {RatedBy = person, Value = rating});
return _ctx.SaveChanges() > -1 ? this.CreateOKHttpActionResult(true) : this.CreateOKHttpActionResult(false);
}
[HttpPost]
[ODataRoute("RecordStores/AirVinyl.Actions.RemoveRatings")]
public IHttpActionResult RemoveRatings(ODataActionParameters parameters)
{
if (parameters.TryGetValue("personId", out var outputFromDictionary) == false) return NotFound();
if (int.TryParse(outputFromDictionary.ToString(), out var personId) == false) return NotFound();
var person = _ctx.People.FirstOrDefault(rs => rs.PersonId == personId);
if (person == null) return NotFound();
var recordStoresRatedByCurrentPerson =
_ctx.RecordStores
.Include("Ratings")
.Include("Ratings.RatedBy")
.Where(rs => rs.Ratings.Any(rating => rating.RatedBy.PersonId == personId))
.ToList();
foreach (var store in recordStoresRatedByCurrentPerson)
{
var ratingsByCurrentPerson =
store.Ratings.Where(rating => rating.RatedBy.PersonId == personId).ToList();
foreach (var rating in ratingsByCurrentPerson) store.Ratings.Remove(rating);
}
return _ctx.SaveChanges() > -1 ? this.CreateOKHttpActionResult(true) : this.CreateOKHttpActionResult(false);
}
[HttpPost]
[ODataRoute("RemoveRecordStoreRatings")]
public IHttpActionResult RemoveRecordStoreRatings(ODataActionParameters parameters)
{
if (parameters.TryGetValue("personId", out var outputFromDictionary) == false) return NotFound();
if (int.TryParse(outputFromDictionary.ToString(), out var personId) == false) return NotFound();
var person = _ctx.People.FirstOrDefault(rs => rs.PersonId == personId);
if (person == null) return NotFound();
var recordStoresRatedByCurrentPerson =
_ctx.RecordStores
.Include("Ratings")
.Include("Ratings.RatedBy")
.Where(rs => rs.Ratings.Any(rating => rating.RatedBy.PersonId == personId))
.ToList();
foreach (var store in recordStoresRatedByCurrentPerson)
{
var ratingsByCurrentPerson =
store.Ratings.Where(rating => rating.RatedBy.PersonId == personId).ToList();
foreach (var rating in ratingsByCurrentPerson) store.Ratings.Remove(rating);
}
return _ctx.SaveChanges() > -1
? StatusCode(HttpStatusCode.NoContent)
: StatusCode(HttpStatusCode.InternalServerError);
}
[HttpGet]
[ODataRoute("RecordStores/AirVinyl.Model.SpecializedRecordStore")]
[EnableQuery]
public IHttpActionResult GetSpecializedRecordStores()
{
var specializedStores = _ctx.RecordStores.OfType<SpecializedRecordStore>();
return Ok(specializedStores);
}
[HttpGet]
[EnableQuery]
[ODataRoute("RecordStores({key})/AirVinyl.Model.SpecializedRecordStore")]
public IHttpActionResult GetSpecializedRecordStore([FromODataUri] int key)
{
var specializedStores = _ctx.RecordStores.Where(r => r is SpecializedRecordStore && r.RecordStoreId == key)
.OfType<SpecializedRecordStore>();
if (specializedStores.Any() == false) return NotFound();
return Ok(SingleResult.Create(specializedStores));
}
[HttpPost]
[ODataRoute("RecordStores")]
public IHttpActionResult CreateRecordStore(RecordStore recordStore)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
// add the RecordStore
_ctx.RecordStores.Add(recordStore);
_ctx.SaveChanges();
// return the created RecordStore
return Created(recordStore);
}
[HttpPatch]
[ODataRoute("RecordStores({key})")]
[ODataRoute("RecordStores({key})/AirVinyl.Model.SpecializedRecordStore")]
public IHttpActionResult UpdateRecordStorePartially([FromODataUri] int key, Delta<RecordStore> patch)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
// find a matching record store
var currentRecordStore = _ctx.RecordStores.FirstOrDefault(p => p.RecordStoreId == key);
// if the record store isn't found, return NotFound
if (currentRecordStore == null) return NotFound();
patch.Patch(currentRecordStore);
_ctx.SaveChanges();
// return NoContent
return StatusCode(HttpStatusCode.NoContent);
}
[HttpDelete]
[ODataRoute("RecordStores({key})")]
[ODataRoute("RecordStores({key})/AirVinyl.Model.SpecializedRecordStore")]
public IHttpActionResult DeleteRecordStore([FromODataUri] int key)
{
var currentRecordStore = _ctx.RecordStores.Include("Ratings")
.FirstOrDefault(p => p.RecordStoreId == key);
if (currentRecordStore == null) return NotFound();
currentRecordStore.Ratings.Clear();
_ctx.RecordStores.Remove(currentRecordStore);
_ctx.SaveChanges();
// return NoContent
return StatusCode(HttpStatusCode.NoContent);
}
protected override void Dispose(bool disposing)
{
// dispose the context
_ctx.Dispose();
base.Dispose(disposing);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.OData.Builder;
namespace AirVinyl.Model
{
public class Person
{
[Key] public int PersonId { get; set; }
[StringLength(100)] public string Email { get; set; }
[Required] [StringLength(50)] public string FirstName { get; set; }
[Required] [StringLength(50)] public string LastName { get; set; }
[Required] [DataType(DataType.Date)] public DateTimeOffset DateOfBirth { get; set; }
[Required] public Gender Gender { get; set; }
public int NumberOfRecordsOnWishList { get; set; }
public decimal AmountOfCashToSpend { get; set; }
public ICollection<Person> Friends { get; set; }
[Contained] public ICollection<VinylRecord> VinylRecords { get; set; }
}
} | 3681f51293b2beaf2cecc374ce658ad7fe5a7c4a | [
"C#"
] | 5 | C# | yousufmohammad26/PluralSight_ODataV4_Course | 9e4128b759af55a33a95c42e1b8b33dafd81e7bc | ab06fb6b426071502313859c785d1bf11d827815 |
refs/heads/master | <file_sep>interface Config {
upperCaseChance?: number;
letterReplaceChance?: number;
tripleChance?: number;
maxTags?: number;
}
const defaults = {
upperCaseChance: 0.5,
letterReplaceChance: 0.8,
tripleChance: 0.1,
maxTags: 3,
};
const letterReplacements: { [index: string]: string } = {
S: "$",
A: "4",
a: "@",
l: "1",
i: "1",
I: "1",
o: "0",
s: "z",
H: "#",
z: "zzz",
Z: "ZZZ",
g: "ggg",
G: "GGG",
E: "3",
e: "3",
t: "+",
D: "|)",
};
const decorations = [
"x",
"X",
"xX",
"xxx",
"~",
".-~",
"xXx",
"XxX",
"xxX_",
"|",
"./|",
"@@@",
"$$$",
"***",
"+",
"|420|",
".::",
".:",
".-.",
"|||",
"--",
"*--",
];
const tags = [
"SHOTS FIRED",
"420",
"LEGIT",
"360",
"Pr0",
"NO$$$cop3z",
"0SC0pe",
"MLG",
"h4xx0r",
"M4X$W4G",
"L3G1TZ",
"3edgy5u",
"2edgy4u",
"nedgy(n+2)u",
"s0b4s3d",
"SWEG",
"LEGIT",
"WUBWUBWUB",
"BLAZEIT",
"b14Z3d",
"[le]G1t",
"60x7",
"24x7BLAZEIT",
"4.2*10^2",
"literally",
"[le]terally",
"1337",
"l33t",
"31337",
"Tr1Ck$h0t",
"SCRUBLORD",
"DR0PTH3B4$$",
"w33d",
"<NAME>",
"MTNDEW",
"WATCH OUT",
"EDGY",
"ACE DETECTIVE",
"90s KID",
"NO REGRETS",
"THANKS OBAMA",
"SAMPLE TEXT",
"FAZE",
"#nofilter",
];
const randomChoice = (list: string[]): string => {
return list[Math.floor(Math.random() * list.length)];
};
const randomiseCase = (letter: string, upperCaseChance: number): string => {
return Math.random() < upperCaseChance
? letter.toUpperCase()
: letter.toLowerCase();
};
export function swagify(string: string, options?: Config) {
const { upperCaseChance, letterReplaceChance, tripleChance, maxTags } = {
...defaults,
...options,
};
if(!string) string = ''
const letters = string.split("");
for (const i in letters) {
if (Math.random() < letterReplaceChance) {
const replacement = letterReplacements[letters[i]];
if (replacement) {
letters[i] = letterReplacements[letters[i]];
}
}
letters[i] = randomiseCase(letters[i], upperCaseChance);
}
if (Math.random() < tripleChance) {
const tripleIndex = Math.floor(Math.random() * letters.length);
const letter = letters[tripleIndex];
if (letter) {
letters[tripleIndex] = letter.repeat(3);
}
}
string = letters.join("");
// decorate
const decoration = randomChoice(decorations);
string = decoration + string + decoration.split("").reverse().join("");
// add tags
const tagsCount = Math.floor(Math.random() * maxTags);
for (let i = 0; i < tagsCount; i++) {
string = "[" + randomChoice(tags) + "]" + string;
}
return string;
}
<file_sep># Swagify
"I use it every day." - Connor, 12, 420th prestige on BLOPS2
_Author: [GitHub](https://github.com/defaultnamehere)_ _Repo:
[GitHub](https://github.com/defaultnamehere/swagify)_
## Usage
```ts
import { swagify } from "https://deno.land/x/swagify/mod.ts";
console.log(swagify("Username to swagify"));
```
## Config (This is optional)
| Props | Type | Default |
| ------------------- | -------- | ------- |
| upperCaseChance | `number` | 0.5 |
| letterReplaceChance | `number` | 0.8 |
| tripleChance | `number` | 0.1 |
| maxTags | `number` | 3 |
## Example
```ts
const name = swagify("Artemiy", {
upperCaseChance: 0,
letterReplaceChance: 1,
tripleChance: 0,
maxTags: 200,
});
console.log(name);
```
## Node
```bash
npm i @artemis69/swagify
```
```ts
import { swagify } from "@artemis69/swagify";
console.log(swagify("Username to swagify"));
```
| fbd84bd0bc98b1ee23f73d6ce174450a8de1cb74 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | yhdgms1/Swagify | 3f16910c73300176f04b109f679e95d957e555ec | c0ce39806547a5d16297265436bbfdef087da3cd |
refs/heads/master | <repo_name>NoyesE/GameProject<file_sep>/README.md
# GameProject
AdvancedDotNetWebClass
Need to implement a user player object to go in the database and the main game
This is a game about building a town with your friends
<file_sep>/GameProject/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GameProject.Models;
namespace GameProject.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Player myPlayer = new Player
{
Name = "Ian",
wood = 0,
lumberHut = 0
};
return View(myPlayer);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}<file_sep>/GameProject/Models/Player.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GameProject.Models
{
public class Player
{
public string Name { get; set; }
public int wood { get; set; }
public int lumberHut { get; set; }
}
} | e8d4c32e42aafe9d09a701a179b5fd53b55ae47b | [
"Markdown",
"C#"
] | 3 | Markdown | NoyesE/GameProject | 18b588069f7c9ffc757396b508ee4202044c218e | 81f1936c6e59d22dfdcb2af9038dcef9ff2b2e44 |
refs/heads/master | <file_sep># Import the necessary package to process data in JSON format
try:
import json
except ImportError:
import simplejson as json
# Import the necessary methods from "twitter" library
import oauth2 as oauth
# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN = '1238348797-5GmDO5kldGC5tB5A6r0knWePIaR0a3crRBjwwMp'
ACCESS_SECRET = '<KEY>'
CONSUMER_KEY = 'o5p2TNGv19WkEfu324YInDlZT'
CONSUMER_SECRET = '<KEY>'
consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
access_token = oauth.Token(key=ACCESS_TOKEN, secret=ACCESS_SECRET)
client = oauth.Client(consumer, access_token)
timeline_endpoint = "https://api.twitter.com/1.1/statuses/user_timeline.json"
response, data = client.request(timeline_endpoint)
tweets = json.loads(data)
my_gen = (item for item in tweets if item[u'text'].find('you') > -1)
for item in my_gen:
print item[u'user'][u'screen_name'] + ': ' + item[u'text'] + '\n'
| 113cf2b5366bee61e5a3b76246247b97aa7abb97 | [
"Python"
] | 1 | Python | jacobrake/subtweetconnection | 7fab0ad1693969e9a0c53717345e25c1b89fa87e | fdb71c2313e285a181114e089e13c3cb772e25f6 |
refs/heads/master | <file_sep>"""Connect to the API gateway in the associated template."""
import asyncio
import json
import sys
import websockets
async def main(uri):
"""Connect to websocket and send/read messages."""
print("Making a connection")
async with websockets.connect(uri, ssl=True) as websocket:
print("Connected!")
print("Sending message")
await websocket.send(json.dumps({"action": "Hello World"}))
print("Waiting for response")
response = await websocket.recv()
print(f'Got response! {response!r}')
print("Disconnecting!")
print("Disconnected!")
if __name__ == "__main__":
uri = sys.argv[1]
asyncio.get_event_loop().run_until_complete(main(uri))
| edc8074c53958e2ea84e97351455f0382c6cad03 | [
"Python"
] | 1 | Python | MaxwellGBrown/aws_api_gateway_websocket_example | 5a22d28f2f12bf12a14a8b570794bfbeabc465fc | a9eb7b87b1104c0622f0a6602bccb7b42a28a4dd |
refs/heads/master | <repo_name>quangtuan9237/DownloadFromChromeNetwork<file_sep>/index.js
const CDP = require('chrome-remote-interface');
const execFile = require('child_process').execFile;
const spawn = require('child_process').spawn;
const child_process = require('child_process');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
async function example() {
let client;
try {
// connect to endpoint
client = await CDP();
// extract domains
const {Network, Page} = client;
let downloadLink = "";
let lectureID = "";
let defaultID = "";
let count = 0;
let lastHdID, hdID = "";
// setup handlers
Network.requestWillBeSent((params) => {
const url = "" + params.request.url;
let regEx;
regEx = /https:\/\/.*?\/.*?\/(.*?)\/.*?\/.*?\/(.*?)\/master.json.*/;
if(regEx.test(url)){
downloadLink = url;
lectureID = url.replace(regEx, "$1");
defaultID = url.replace(regEx, "$2");
console.log("lectureID ", lectureID);
console.log("defaultID ", defaultID);
}
regEx = /https:\/\/.*?\/.*?\/.*?\/.*?\/video\/(.*?)\/.*?\/.*/;
if(regEx.test(url)){
count++;
hdID = url.replace(regEx, "$1");
if(count > 8 && lastHdID != hdID){
count = 0;
console.log("hdID ", hdID);
lastHdID = hdID;
downloadLink = downloadLink.replace(defaultID,lastHdID);
downloadLink = downloadLink.replace("json?base64_init=1", "mpd");
console.log("downloadLink ", downloadLink);
rl.question('Please enter video name: ', (videoName) => {
//child_process.execSync(`start cmd.exe /K youtube-dl ${downloadLink} --merge-output-format mp4 -o ${videoName}.mp4`);
child_process.execSync(`start cmd.exe /K streamlink ${downloadLink} best --hds-segment-threads 10 -o "videos/one-on-one-coaching/${videoName}.mp4"`);
});
//let videoName = readline.question("Input video name: ");
}
}
});
// enable events then start!
await Network.enable();
} catch (err) {
console.error(err);
}
}
example();<file_sep>/README.md
# DownloadFromChromeNetwork
This project is written in Node.js. It captures all network request from chrome tab. Using regEx to filter which links we need and download them.
Project require:
+ Node.js
+ Streamlink (https://github.com/streamlink/streamlink)
| 2ef1245b74219daf87688711d7f8a348df319a58 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | quangtuan9237/DownloadFromChromeNetwork | afad1c01ea19f10cb336e56ed926bb528ec2817c | 43eb1242f3fa363a136ed61ec3c8e214a004bae8 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
class AddTodo extends Component {
constructor() {
super();
// Same thing as the App component. We need to initialize todo on state to be used in our render method
this.state = {
todo: ''
};
}
// This is an example of a typical handle change method. It takes in a value and uses that value to update a property on state.
handleChange(value) {
this.setState({ todo: value });
}
// In order what happens here is
// 1. we invoke the addTodo prop passing through the value of this.state.todo. It's important to remember that this.props is an object with the key value pairs being whatever was passed down when we rendered the component. In this case, in App we rendered <AddTodo addTodo={this.addtodo}/> like so, so we have access to a prop with the key addTodo and the value a function.
// 2. We then setState on this component back to an empty string so that the user doesn't need to worry about doing it themselves and can just add the todo.
handleClick() {
this.props.addTodo(this.state.todo);
this.setState({ todo: '' });
}
render() {
console.log('this.props in add todo', this.props);
return (
<div>
<p>Add Todo</p>
{/* our input tag receives its value from state so when state changes, the input on the view reflects that latest change */}
{/* We also need to pass an es6 arrow function to the on change to make sure that when onChange event happens, the es6 arrow function is invoked, gets it's context from the surrounding scope (render's value of this which is the AddTodo component) and then we invoke handleChange correctly (AddTodo.handleChange()) (implicit context) */}
<input
value={this.state.todo}
onChange={e => this.handleChange(e.target.value)}
/>
{/* Same things as above with the arrow function */}
<button onClick={() => this.handleClick()}>Add Todo</button>
</div>
);
}
}
export default AddTodo;
<file_sep>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import AddTodo from './AddTodo';
class App extends Component {
constructor() {
// super must always be called in a constructor that is extending another class (Component) before we can use this
super();
// We initialize state with a todos property whose value is an empty array. That's because in our render method, we are calling this.state.todos.map(). Now, if we didn't set the initial value of this.state.todos = [], then this.state.todos would be undefined. If you try to call undefined.map, you get a breaking javascript error. Thus the importance of setting up all of the initial values for all of the state variables this component will use.
this.state = {
todos: []
};
// In order to make sure that addTodo is invoked with the correct value of this, we need to create a copy of it on each new instance of App that is bound to that instance.
// The below code is creating a direct property on our App component whose value is the bound function copy
this.addTodo = this.addTodo.bind(this);
// Simple example
// Run in browser console if you want to see
// class Test {
// constructor(name) {
// this.name = name
// this.logger2 = this.logger2.bind(this)
// }
// logger() {
// console.log(this)
// }
// logger2() {
// console.log(this)
// }
// }
// let newTest = new Test('John')
// console.log(newTest)
// console.log('Does newTest have a copy of the logger method?', newTest.hasOwnProperty('logger'))
// console.log('Does newTest have a copy of logger2 method?', newTest.hasOwnProperty('logger2'))
// console.log('Is the copy of logger2 on newTest the same function as the class method on the prototype?', newTest.logger2 === newTest.__proto__.logger2)
}
// addTodo takes in a todo parameter and then makes a copy of the todos array on state. It then adds that todo param ('string') to the copy of todos and lastly sets state, setting todos to the copied array that contains all the old todos plus the new one
addTodo(todo) {
let copy = this.state.todos;
copy.push(todo);
this.setState({ todos: copy });
}
render() {
return (
<div className="App">
{/* We render out the AddTodo component passing down 1 prop. That prop is addTodo={this.addTodo}. Remember, since we bound addTodo in the constructor, the function we are passing down is a bound copy of the addTodo method. That means that even though the child component will invoke it from the button onClick event, the value of this will still be the App component. */}
<AddTodo addTodo={this.addTodo} />
{/* Here we map through the todos on state and render out a div for each one. It's important that we add the key so react can properly keep track of each of these and if one changes we know about it. */}
{this.state.todos.map((todo, i) => {
return <div key={`${todo}-${i}`}>{todo}</div>;
})}
</div>
);
}
}
export default App;
| 8c127d41efe9b46e78169a50dafafd4c6dcc80c8 | [
"JavaScript"
] | 2 | JavaScript | thawkinsusa/react-3-demo-notes | 396b271d35ed9a3b47298f2b32020f8517c67468 | bdac07888c4095e0bbd3f305f9e9222e52996091 |
refs/heads/master | <file_sep>export const environment = {
production: true,
config: {
apiKey: "<KEY>",
authDomain: "challenge-6ef58.firebaseapp.com",
databaseURL: "https://challenge-6ef58.firebaseio.com",
projectId: "challenge-6ef58",
storageBucket: "challenge-6ef58.appspot.com",
messagingSenderId: "945265277389",
appId: "1:945265277389:web:a389f2840c862f3b31ec84",
measurementId: "G-PM258JQ365",
},
};
<file_sep>import { Client } from './../models/client.models';
import * as clientActions from "../actions/clientes.actions";
export type Action = clientActions.All;
export function clientReducer(state: Client, action: Action){
switch (action.type) {
case clientActions.GET_CLIENT:
return { ...state, loading: true };
case clientActions.GET_CLIENT_SUCCESS:
return { ...state, clients : action.payload, loading: false };
case clientActions.POST_CLIENT:
return { ...state, ...action.payload, loading: true };
case clientActions.POST_CLIENT_SUCCESS:
return { ...state, loading: false };
case clientActions.POST_CLIENT_FAIL:
return { ...state, ...action.payload, loading: false };
default:
return state;
}
}<file_sep>export interface Client {
apellido: string;
edad: number;
fecha_nac: string;
nombre: string;
error?: string;
}
export interface clients {
clients: Client[];
}<file_sep>import { Component, OnInit } from "@angular/core";
import { Client, clients } from "./models/client.models";
import { Store } from "@ngrx/store";
import { Observable } from "rxjs";
import * as ClientActions from "./actions/clientes.actions";
import { NgbDateStruct, NgbCalendar } from "@ng-bootstrap/ng-bootstrap";
interface AppState {
client: clients;
}
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
clients$: Observable<clients>;
clicked: boolean = false;
dateval: NgbDateStruct;
date: { year: number; month: number };
clientPost: Client = {
apellido: "",
edad: null,
fecha_nac: "",
nombre: "",
};
constructor(private store: Store<AppState>, private calendar: NgbCalendar) {
this.clients$ = this.store.select("client");
}
ngOnInit() {
this.getClients();
}
getClients() {
this.store.dispatch(new ClientActions.GetClient("/Clientes/"));
}
calculateAge(e) {
let dateString = new Date(
`${e.year}/${e.month}/${e.day < 10 ? e.day : "0" + e.day}`
);
let today = new Date();
let birthDate = new Date(dateString);
let age = today.getFullYear() - birthDate.getFullYear();
let m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
this.clientPost.fecha_nac = `${e.day > 10 ? e.day : "0" + e.day}-${
e.month
}-${e.year}`;
this.clientPost.edad = age;
}
average(arr) {
if (arr)
return (
arr.reduce((a, b) => {
return a + b.edad;
}, 0) / arr.length
);
}
standardDeviation(arr) {
if (arr) {
const n = arr.length;
const mean =
arr.reduce((a, b) => {
return a + b.edad;
}, 0) / n;
return Math.sqrt(
arr.map((x) => Math.pow(x.edad - mean, 2)).reduce((a, b) => a + b) / n
);
}
}
postClients() {
this.store.dispatch(new ClientActions.PostClient(this.clientPost));
this.clientPost = {
apellido: "",
edad: null,
fecha_nac: "",
nombre: "",
};
}
}
<file_sep>import { Action } from "@ngrx/store";
import { Client } from "../models/client.models";
export const GET_CLIENT = "Client get";
export const GET_CLIENT_SUCCESS = "Client get success";
export const POST_CLIENT = "Client post";
export const POST_CLIENT_SUCCESS = "Client post success";
export const POST_CLIENT_FAIL = "Client post fail";
export class GetClient implements Action {
readonly type = GET_CLIENT;
constructor(public payload: string) {}
}
export class GetClientSuccess implements Action {
readonly type = GET_CLIENT_SUCCESS;
constructor(public payload: Client[]) {}
}
export class PostClient implements Action {
readonly type = POST_CLIENT;
constructor(public payload: any) {}
}
export class PostClientSuccess implements Action {
readonly type = POST_CLIENT_SUCCESS;
constructor(public payload?: any) {}
}
export class PostClientFail implements Action {
readonly type = POST_CLIENT_FAIL;
constructor(public payload?: any) {}
}
export type All =
| GetClient
| GetClientSuccess
| PostClient
| PostClientSuccess
| PostClientFail;
<file_sep>import { Injectable } from "@angular/core";
import { AngularFireDatabase } from "@angular/fire/database";
import { AngularFirestore } from "@angular/fire/firestore";
import { Effect, Actions, ofType } from "@ngrx/effects";
import { Observable, of } from "rxjs";
import { map, mergeMap, catchError, delay } from "rxjs/operators";
import * as clientActions from "../actions/clientes.actions";
import { Client, clients } from "../models/client.models";
import { v4 as uuidv4 } from 'uuid';
export type Action = clientActions.All;
@Injectable()
export class ClientEffects {
constructor(private actions: Actions, private db: AngularFireDatabase, private firestore:AngularFirestore) {}
@Effect()
getClient: Observable<Action> = this.actions.pipe(
ofType(clientActions.GET_CLIENT),
map((action: clientActions.GetClient) => action.payload),
mergeMap((payload) => this.db.list(payload).valueChanges()),
map((client: any) => {
return new clientActions.GetClientSuccess(client);
})
);
@Effect()
postClient: Observable<Action> = this.actions.pipe(
ofType(clientActions.POST_CLIENT),
map((action: clientActions.PostClient) => action.payload),
mergeMap((payload) =>
of(this.db.object(`Clientes/${uuidv4()}`).set(payload))
),
map(() => new clientActions.PostClientSuccess()),
catchError((err) =>
of(new clientActions.PostClientFail({ error: err.message }))
)
);
}
| 72d8319beb6f491e63eb2be102cc51466ea84dda | [
"TypeScript"
] | 6 | TypeScript | Carlos123211/ChallengeRx | e692ca279b3743524d9f82649a94d0683f988c1b | b1d7dfc1c10e6c8a6b4090f80021dbc2650345f5 |
refs/heads/master | <repo_name>USGS-CIDA/mlr-python-base-docker<file_sep>/Dockerfile
FROM python:3.6-alpine
LABEL maintainer="<EMAIL>"
ENV USER=python
ENV HOME=/home/$USER
ENV artifact_id=sample_app
ENV gunicorn_keep_alive=75
ENV gunicorn_silent_timeout=120
ENV gunicorn_graceful_timeout=120
ENV bind_ip 0.0.0.0
ENV protocol=https
ENV listening_port=8000
ENV oauth_server_token_key_url=https://example.gov/oauth/token_key
ENV jwt_algorithm=HS256
ENV jwt_decode_audience=default
ENV CERT_IMPORT_DIRECTORY=$HOME/certificates
ENV ssl_cert_path=$CERT_IMPORT_DIRECTORY/wildcard-ssl.crt
ENV ssl_key_path=$CERT_IMPORT_DIRECTORY/wildcard-ssl.key
ENV SSL_STORAGE_DIR=$HOME/ssl
ENV PROJ_DIR=/usr
ENV PATH="$PATH:$HOME/.local/bin"
ENV PIP_CERT=/etc/ssl/certs/ca-certificates.crt
RUN apk update && apk add --update --no-cache \
build-base \
ca-certificates \
libffi-dev \
openssl-dev \
openssl \
netcat-openbsd \
proj \
proj-util \
proj-dev \
curl && \
rm -rf /var/cache/apk/*
RUN if getent ahosts "sslhelp.doi.net" > /dev/null 2>&1; then \
wget 'https://s3-us-west-2.amazonaws.com/prod-owi-resources/resources/InstallFiles/SSL/DOIRootCA.cer' -O /usr/local/share/ca-certificates/DOIRootCA2.crt && \
update-ca-certificates; \
fi
RUN python3 -m ensurepip && \
rm -rf /usr/lib/python*/ensurepip && \
pip3 install --upgrade --no-cache-dir pip==20.0.2 && \
if [[ ! -e /usr/bin/python ]]; then ln -sf /usr/bin/python3 /usr/bin/python; fi
RUN adduser --disabled-password -u 1000 $USER
WORKDIR $HOME
RUN mkdir $HOME/local
COPY import_certs.sh import_certs.sh
COPY entrypoint.sh entrypoint.sh
COPY gunicorn_config.py local/gunicorn_config.py
RUN [ "chmod", "+x", "import_certs.sh", "entrypoint.sh" ]
RUN chown $USER:$USER import_certs.sh entrypoint.sh local/gunicorn_config.py
RUN chown -R $USER:$USER $HOME
USER $USER
ARG GUNICORN_VERSION=20.0.4
ARG GEVENT_VERSION=1.4.0
ARG CERTIFI_VERSION=2019.11.28
RUN pip3 install --user --quiet --no-cache-dir gunicorn==$GUNICORN_VERSION && \
pip3 install --user --quiet --no-cache-dir gevent==$GEVENT_VERSION && \
pip3 install --user --quiet --no-cache-dir certifi==$CERTIFI_VERSION
# This is used for downstream containers that may need this scripting in order to
# orchestrate container startups.
# See: https://github.com/eficode/wait-for
RUN curl -o ./wait-for.sh https://raw.githubusercontent.com/eficode/wait-for/f71f8199a0dd95953752fb5d3f76f79ced16d47d/wait-for && \
chmod +x ./wait-for.sh
COPY app.py $HOME/app.py
CMD ["./entrypoint.sh"]
HEALTHCHECK CMD curl -k ${protocol}://127.0.0.1:${listening_port}/version | grep -q "\"artifact\": \"${artifact_id}\"" || exit 1
ONBUILD RUN rm $HOME/app.py
<file_sep>/docker-compose.yml
---
version: '3.5'
secrets:
ssl_crt:
file: ./config/certificates/wildcard-dev.crt
ssl_key:
file: ./config/certificates/wildcard-dev.key
services:
mlr-python-base:
build: .
image: mlr-python-base
container_name: mlr-python-base
secrets:
- source: ssl_crt
target: /home/python/certificates/wildcard-ssl.crt
- source: ssl_key
target: /home/python/certificates/wildcard-ssl.key
env_file:
- config.env
- secrets.env
ports:
- "8000:8000"
<file_sep>/config/certificates/README.md
Development wildcard certificates generated via:
```
$ openssl genrsa -out wildcard-dev.key 2048
$ openssl req -nodes -newkey rsa:2048 -keyout wildcard-dev.key -out wildcard-dev.csr -subj "/C=US/ST=Wisconsin/L=Middleon/O=US Geological Survey/OU=WMA/CN=*"
$ openssl x509 -req -days 9999 -in wildcard-dev.csr -signkey wildcard-dev.key -out wildcard-dev.crt<file_sep>/import_certs.sh
#!/bin/ash
# shellcheck shell=dash
echo "Importing ca certificates..."
#Create PEM Cert Storage Dir
mkdir -p $SSL_STORAGE_DIR
# Get Certifi cacert PEM path
CERTIFI_CACERT_PATH=$(python -c "import certifi; print(certifi.where())")
# Ensure certificate import directory exists
if [ -n "${CERT_IMPORT_DIRECTORY}" ] && [ -d "${CERT_IMPORT_DIRECTORY}" ]; then
CERT_COUNT=$(find $CERT_IMPORT_DIRECTORY -name "*.crt" -type f | wc -l)
if [ $CERT_COUNT -gt 0 ]; then
for c in ${CERT_IMPORT_DIRECTORY}/*.crt; do
FILENAME=`basename ${c%.*}` # get just file name, not extension
echo "Importing $FILENAME.crt"
#Convert CRT to PEM and append to certifi cacerts
openssl x509 -in $CERT_IMPORT_DIRECTORY/$FILENAME.crt -out $SSL_STORAGE_DIR/$FILENAME.pem
cat $SSL_STORAGE_DIR/$FILENAME.pem >> $CERTIFI_CACERT_PATH
done
else
echo "No certificates found in $CERT_IMPORT_DIRECTORY"
fi
else
echo "Could not find or access cert import directory: $CERT_IMPORT_DIRECTORY"
fi
<file_sep>/gunicorn_config.py
import os
import gunicorn
bind_ip = os.getenv('bind_ip', '0.0.0.0')
bind_port = os.getenv('listening_port', '8443')
bind = '{0}:{1}'.format(bind_ip, bind_port)
capture_output = True
# ssl_key_path and ssl_cert_path environment variables are defined when secrets are created
keyfile = os.getenv('ssl_key_path')
certfile = os.getenv('ssl_cert_path')
# Settings to hopefully help stability on Docker in AWS
# See: https://github.com/benoitc/gunicorn/issues/1194
keepalive = int(os.getenv('gunicorn_keep_alive', 75))
timeout = int(os.getenv('gunicorn_silent_timeout', 120))
grceful_timeout = int(os.getenv('gunicorn_graceful_timeout', 120))
worker_class = 'gevent'
ciphers = 'TLSv1.2'
gunicorn.SERVER_SOFTWARE = ''<file_sep>/entrypoint.sh
#!/bin/ash
# shellcheck shell=dash
/bin/ash $HOME/import_certs.sh
if [ -f "app.py" ]; then
gunicorn --reload app:app --config file:$HOME/local/gunicorn_config.py --user $USER
else
gunicorn --reload app --config file:$HOME/local/gunicorn_config.py --user $USER
fi
<file_sep>/CHANGELOG.md
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). (Patch version X.Y.0 is implied if not specified.)
## [Unreleased]
### Added
- <EMAIL> - Added wait-for.sh (and the netcat package) to help with
downstream container start orchestration
- <EMAIL> - Dockerfile
- <EMAIL> - docker-compose.env
- <EMAIL> - docker-compose.yml
- <EMAIL> - .travis.yml
- <EMAIL> - python user
- <EMAIL> - curl check in travis to verify http server is running
- <EMAIL> - certificate import script
- <EMAIL> - maintainer label in Dockerfile
- <EMAIL> - certificate import envs in Dockerfile
- <EMAIL> - sample application for base container
- <EMAIL> - health check
- <EMAIL> - onbuild command to remove sample application on downstream containers
- <EMAIL> - squelching pip installation
### Changed
- <EMAIL> - use port 8000
- <EMAIL> - switch in entrypoint to test for sample application
- <EMAIL> - Moved lines around in Dockerfile
- <EMAIL> - Dockerfile now uses python user instead of root
- <EMAIL> - Removed check in travis for a running container
- <EMAIL> - Split out config to config.env and secrets.yml
- <EMAIL> - docker-compose now mounts certificates into python home dir
<file_sep>/README.md
# mlr-python-base-docker
base Docker image for MLR python artifacts
| 0709bcb9bbec3bc847098b5522bd800c3eafeacf | [
"YAML",
"Markdown",
"Python",
"Dockerfile",
"Shell"
] | 8 | Dockerfile | USGS-CIDA/mlr-python-base-docker | cce66e383b65c1692bbd02ea706b43f10266d9ce | 44d2abdcd55e0920884d1a8a125708c982e3e5d4 |
refs/heads/master | <repo_name>dregin/mastodon-to-others<file_sep>/plugins/ifttt-poster.py
import requests
import yaml
def post(post):
# Attempt to load config
config_location = "config/ifttt.yml"
config = {}
try:
with open(config_location, 'r') as stream:
try:
config = yaml.load(stream)['config']
except yaml.YAMLError as e:
print(e)
except IOError:
print("Please create config: {}".format(config_location))
if not config['enabled'] == 'True':
print('IFTTT disabled')
return
print("Posting to IFTTT")
share_token = config['share_token'].strip('#')
tag_present = False
for tag in post['tags']:
if tag.term == share_token:
tag_present = True
if tag_present:
report = {}
report["value1"] = post['link']
message = post['summary'].strip(config['share_token']).strip()
try:
if config['invite']:
message = "{}\n\nJoin my Mastodon Instance through this invite: {}".format(message, config['invite'])
except KeyError:
pass
report["value2"] = message
requests.post(config['maker_url'], data=report)
<file_sep>/plugins/twitter-poster.py
import twitter
import yaml
def post(post):
print("Posting to Twitter")
# Attempt to load config
config_location = "config/twitter.yml"
config = {}
try:
with open(config_location, 'r') as stream:
try:
config = yaml.load(stream)['config']
except yaml.YAMLError as e:
print(e)
except IOError:
print("Please create config: {}".format(config_location))
print("Use helper script @ https://github.com/bear/python-twitter/blob/master/get_access_token.py")
share_token = config['share_token'].strip('#')
tag_present = False
for tag in post['tags']:
if tag.term == share_token:
tag_present = True
if tag_present:
api = twitter.Api(consumer_key=config['consumer_key'],
consumer_secret=config['consumer_secret'],
access_token_key=config['access_token_key'],
access_token_secret=config['access_token_secret'])
try:
message = u"{} {}".format(post['summary'].replace(u'#', u" #"), post['link'])
try:
if config['invite']:
message = u"{}\n\nJoin my Mastodon Instance through this invite: {}".format(message, config['invite'])
except KeyError:
pass
api.PostUpdate(message)
except twitter.TwitterError as e:
print(e.message[0]['message'])
else:
print("Post doesn't contain the share token - {}".format(share_token))
<file_sep>/requirements.txt
facebook-sdk
feedparser
python-twitter
pyyaml
<file_sep>/postparser.py
#!/bin/python
import feedparser
import imp
from HTMLParser import HTMLParser
import plugins
from urllib2 import URLError
import yaml
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
def parse(feed):
d = feedparser.parse(feed)
if d.bozo:
raise d.bozo_exception
try:
mastodon_post = d.entries[0]
except IndexError:
return
post = {}
post['link'] = mastodon_post.link
post['date_time'] = mastodon_post.published
post['summary'] = strip_tags(mastodon_post.summary)
try:
post['tags'] = mastodon_post.tags
except AttributeError:
exit()
new_post = False
try:
with open('last_modified', 'r') as f:
last_modified = f.readline()
if last_modified < post['date_time']:
new_post = True
with open('last_modified', 'w') as f:
f.write(post['date_time'])
except IOError:
new_post = True
with open('last_modified', 'w') as f:
f.write(post['date_time'])
if new_post:
for name in plugins.__all__:
# Load plugin and post
package_info = imp.find_module(name, ['plugins'])
social_outlet = imp.load_module(name, *package_info)
social_outlet.post(post)
config_location = 'config.yml'
config = {}
try:
with open(config_location, 'r') as stream:
try:
config = yaml.load(stream)['config']
except yaml.YAMLError as e:
print(e)
except IOError:
print("Please create config: {}".format(config_location))
feed = config['feed']
try:
parse(feed)
except URLError:
print("Mastodonw instance @ {} isn't accessible".format(feed))
<file_sep>/README.md
# mastodon-to-others
## Description
Script to share Mastodon posts with a specific hash tag (default is #share) to other social media.
Plugins included are for twitter and ifttt.
## Installation
Clone the repo and run `postparser.py` from cron
Update configs in config directory to reflect your settings
## Cron
```
* * * * * cd /opt/mastodon-to-others/ && /usr/bin/python /opt/mastodon-to-others/postparser.py
```
| 359da463957c5fd54f4eec00bae3c867db121323 | [
"Markdown",
"Python",
"Text"
] | 5 | Python | dregin/mastodon-to-others | 3e08aa52fd3b433ccc5897e293af15b21f902d93 | 3f277f227a3d5cd8000747287d0538453f274460 |
refs/heads/master | <file_sep>from sqlalchemy.dialects.postgresql import JSON, ARRAY # type: ignore
from sqlalchemy import Index # type: ignore
from service import db
# N.B.: 'Index' is only used if *additional* index required!
# [Index is created automatically per 'primary_key' setting].
class TitleRegisterData(db.Model): # type: ignore
title_number = db.Column(db.String(10), primary_key=True)
register_data = db.Column(JSON)
geometry_data = db.Column(JSON)
official_copy_data = db.Column(JSON)
is_deleted = db.Column(db.Boolean, default=False, nullable=False)
last_modified = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now(), nullable=False)
lr_uprns = db.Column(ARRAY(db.String), default=[], nullable=True)
Index('idx_last_modified_and_title_number', TitleRegisterData.last_modified,
TitleRegisterData.title_number)
Index('idx_title_uprns', TitleRegisterData.lr_uprns, postgresql_using='gin')
class UprnMapping(db.Model): # type: ignore
uprn = db.Column(db.String(20), primary_key=True)
lr_uprn = db.Column(db.String(20), nullable=False)
class UserSearchAndResults(db.Model): # type: ignore
"""
Store details of user view (for audit purposes) and update after payment (for reconciliation).
"""
# As several users may be searching at the same time, we need a compound primary key.
# Note that WebSeal prevents a user from being logged in from multiple places concurrently.
search_datetime = db.Column(db.DateTime(), nullable=False, primary_key=True)
user_id = db.Column(db.String(20), nullable=False, primary_key=True)
title_number = db.Column(db.String(20), nullable=False)
search_type = db.Column(db.String(20), nullable=False)
purchase_type = db.Column(db.String(20), nullable=False)
amount = db.Column(db.String(10), nullable=False)
cart_id = db.Column(db.String(30), nullable=True)
# Post-payment items: these (or the like) are also held in the 'transaction_data' DB.
# TODO: Ideally they should be fetched from there instead, via the 'search_datetime' key.
lro_trans_ref = db.Column(db.String(30), nullable=True) # Reconciliation: 'transId' from Worldpay.
viewed_datetime = db.Column(db.DateTime(), nullable=True) # If null, user has yet to view the results.
valid = db.Column(db.Boolean, default=False)
def __init__(self,
search_datetime,
user_id,
title_number,
search_type,
purchase_type,
amount,
cart_id,
lro_trans_ref,
viewed_datetime,
valid
):
self.search_datetime = search_datetime
self.user_id = user_id
self.title_number = title_number
self.search_type = search_type
self.purchase_type = purchase_type
self.amount = amount
self.cart_id = cart_id
self.lro_trans_ref = lro_trans_ref
self.viewed_datetime = viewed_datetime
self.valid = valid
# This is for serialisation purposes; it returns the arguments used and their values as a dict.
# Note that __dict__ only works well in this case if no other local variables are defined.
# "marshmallow" may be an alternative: https://marshmallow.readthedocs.org/en/latest.
def get_dict(self):
return self.__dict__
def id(self):
return '<lro_trans_ref {}>'.format(self.lro_trans_ref)
Index('idx_title_number', UserSearchAndResults.title_number)
class Validation(db.Model): # type: ignore
""" Store of price etc., for anti-fraud purposes """
__tablename__ = 'validation'
price = db.Column(db.Integer, nullable=False, default=300, primary_key=True)
product = db.Column(db.String(20), default="drvSummary") # purchase_type
<file_sep>"""add is_deleted and last_modified columns
Revision ID: 59cbcf04663
Revises: 59935c933ab
Create Date: 2015-04-20 13:32:09.792703
"""
# revision identifiers, used by Alembic.
revision = '59cbcf04663'
down_revision = '59935c933ab'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, column
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('title_register_data', sa.Column('is_deleted', sa.Boolean(), nullable=True))
title_register_data = table('title_register_data', column('is_deleted'))
op.execute(title_register_data.update().values(is_deleted=False))
op.alter_column('title_register_data', 'is_deleted', nullable=False)
op.add_column('title_register_data', sa.Column('last_modified',
sa.types.DateTime(timezone=True),
nullable=True))
title_register_data = table('title_register_data', column('last_modified'))
op.execute(title_register_data.update().values(last_modified=sa.func.now()))
op.alter_column('title_register_data', 'last_modified', nullable=False)
op.create_index('idx_last_modified_and_title_number', 'title_register_data',
['last_modified', 'title_number'], unique=False)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index('idx_last_modified_and_title_number', table_name='title_register_data')
op.drop_column('title_register_data', 'last_modified')
op.drop_column('title_register_data', 'is_deleted')
### end Alembic commands ###
<file_sep>"""Add official copy data column
Revision ID: 2bbd8de7dcb
Revises: <KEY>
Create Date: 2015-06-29 11:08:37.905618
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '59cbcf04663'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('title_register_data', sa.Column('official_copy_data', postgresql.JSON(), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('title_register_data', 'official_copy_data')
### end Alembic commands ###
<file_sep># To run (from top-level package directory):
# 'digital-register-api' (this package) needs to be running as a separate service, via 'lr-start-all' or the like.
# 'source environment.sh; python tests/integration_tests.py'
import requests
from datetime import datetime
# Postgres datetime format is YYYY-MM-DD MM:HH:SS.mm
_now = datetime.now()
MC_timestamp = _now.strftime("%Y-%m-%d %H:%M:%S.%f")
test_data = {"MC_timestamp": MC_timestamp,
"MC_userId": "Test User",
"MC_titleNumber": "GR12345",
"MC_searchType": "D",
"MC_purchaseType": "drvSummaryView",
"amount": 2,
"cart_id": "374f501f4567",
"last_changed_datestring": "12 Jul 2014",
"last_changed_timestring": "11:04:32",
}
REGISTER_TITLE_API_URL = 'http://172.16.42.43:8004'
# added a method so that unit testing doesn't run this automatically and fail it when nothing is running
def integration_test():
response = requests.post('{}/save_search_request'.format(REGISTER_TITLE_API_URL), data=test_data)
print(response)
<file_sep>import requests # type: ignore
import logging
from service import app
ADDRESS_SEARCH_API_URL = app.config['ADDRESS_SEARCH_API']
logger = logging.getLogger(__name__)
def get_titles_by_postcode(postcode, page_number, page_size):
logger.debug('Start get_titles_by_postcode. Postcode: {}'.format(postcode))
logger.info('Sending to address-search-api')
response = requests.get(
'{}search'.format(ADDRESS_SEARCH_API_URL),
params={'page_number': page_number,
'postcode': postcode,
'page_size': page_size
}
)
logger.info('Returned from address-search-api')
if response:
logger.debug('End get_titles_by_postcode. Response: {}'.format(response.content))
return _to_json(response)
def _to_json(response):
try:
return response.json()
except Exception as e:
raise Exception('API response body is not JSON', e)
<file_sep>from datetime import datetime
import json
import pg8000
import re
from config import CONFIG_DICT
from service import db_access
INSERT_TITLE_QUERY_FORMAT = (
'insert into title_register_data('
'title_number, register_data, geometry_data, is_deleted, last_modified, official_copy_data, lr_uprns'
')'
'values('
"%s, %s, %s, %s, %s, %s, '{{ {} }}'"
')'
)
DELETE_ALL_TITLES_QUERY = 'delete from title_register_data;'
def _get_db_connection_params():
connection_string_regex = (
r'^.*?//(?P<user>.+?):(?P<password>.+?)@(?P<host>.+?):(?P<port>\d+)/(?P<database>.+)$'
)
db_connection_string = CONFIG_DICT['SQLALCHEMY_DATABASE_URI']
matches = re.match(connection_string_regex, db_connection_string)
return {
'user': matches.group('user'),
'password': matches.group('password'),
'host': matches.group('host'),
'port': int(matches.group('port')),
'database': matches.group('database'),
}
DB_CONNECTION_PARAMS = _get_db_connection_params()
class TestDbAccess:
def setup_method(self, method):
self.connection = self._connect_to_db()
self._delete_all_titles()
def teardown_method(self, method):
try:
self.connection.close()
except (pg8000.InterfaceError):
pass
def test_get_title_register_returns_none_when_title_not_in_the_db(self):
assert db_access.get_title_register('non-existing') is None
def test_get_title_register_returns_none_when_title_marked_as_deleted(self):
title_number = 'title123'
self._create_title(title_number, is_deleted=True)
title = db_access.get_title_register(title_number)
assert title is None
def test_get_title_register_returns_title_data_when_title_not_marked_as_deleted(self):
title_number = 'title123'
register_data = {'register': 'data1'}
geometry_data = {'geometry': 'data2'}
is_deleted = False
last_modified = datetime(2015, 9, 10, 12, 34, 56, 123)
official_copy_data = {'official': 'copy'}
lr_uprns = ['123', '456']
self._create_title(title_number, register_data, geometry_data, is_deleted, last_modified, official_copy_data, lr_uprns)
title = db_access.get_title_register(title_number)
assert title is not None
assert title.title_number == title_number
assert title.register_data == register_data
assert title.geometry_data == geometry_data
assert title.is_deleted == is_deleted
assert title.last_modified.timestamp() == last_modified.timestamp()
assert title.official_copy_data == official_copy_data
assert title.lr_uprns == lr_uprns
def test_get_title_registers_returns_titles_with_right_content(self):
title_number = 'title123'
register_data = {'register': 'data1'}
geometry_data = {'geometry': 'data2'}
is_deleted = False
last_modified = datetime(2015, 9, 10, 12, 34, 56, 123)
official_copy_data = {'official': 'copy'}
lr_uprns = ['123', '456']
self._create_title(title_number, register_data, geometry_data, is_deleted, last_modified, official_copy_data, lr_uprns)
titles = db_access.get_title_registers([title_number])
assert len(titles) == 1
title = titles[0]
assert title is not None
assert title.title_number == title_number
assert title.register_data == register_data
assert title.geometry_data == geometry_data
assert title.is_deleted == is_deleted
assert title.last_modified.timestamp() == last_modified.timestamp()
assert title.official_copy_data == official_copy_data
assert title.lr_uprns == lr_uprns
def test_get_title_registers_returns_list_with_all_existing_titles(self):
existing_title_numbers = {'title1', 'title2', 'title3'}
for title_number in existing_title_numbers:
self._create_title(title_number)
titles = db_access.get_title_registers(existing_title_numbers | {'non-existing-1'})
assert len(titles) == 3
returned_title_numbers = self._get_title_numbers(titles)
assert existing_title_numbers == returned_title_numbers
def test_get_title_registers_returns_empty_list_when_no_title_found(self):
titles = db_access.get_title_registers(['non-existing-1', 'non-existing-2'])
assert titles == []
def test_get_title_registers_does_not_return_deleted_titles(self):
existing_title_number_1 = 'existing-1'
existing_title_number_2 = 'existing-2'
deleted_title_number_1 = 'deleted-1'
deleted_title_number_2 = 'deleted-2'
self._create_title(existing_title_number_1, is_deleted=False)
self._create_title(existing_title_number_2, is_deleted=False)
self._create_title(deleted_title_number_1, is_deleted=True)
self._create_title(deleted_title_number_2, is_deleted=True)
titles = db_access.get_title_registers([
existing_title_number_1, deleted_title_number_1, existing_title_number_2, deleted_title_number_2
])
assert len(titles) == 2
assert self._get_title_numbers(titles) == {existing_title_number_1, existing_title_number_2}
def test_get_official_copy_data_returns_none_when_title_not_in_the_db(self):
assert db_access.get_official_copy_data('non-existing') is None
def test_get_official_copy_data_returns_none_when_title_marked_as_deleted(self):
title_number = 'title123'
self._create_title(title_number, is_deleted=True, official_copy_data={'official': 'copy'})
title = db_access.get_official_copy_data(title_number)
assert title is None
def test_get_official_copy_data_returns_the_copy_when_title_in_the_db(self):
title_number = 'title123'
register_data = {'register': 'data1'}
geometry_data = {'geometry': 'data2'}
is_deleted = False
last_modified = datetime(2015, 9, 10, 12, 34, 56, 123)
official_copy_data = {'official': 'copy'}
lr_uprns = ['123', '456']
self._create_title(title_number, register_data, geometry_data, is_deleted, last_modified, official_copy_data, lr_uprns)
title = db_access.get_official_copy_data(title_number)
assert title is not None
assert title.title_number == title_number
assert title.register_data == register_data
assert title.geometry_data == geometry_data
assert title.is_deleted == is_deleted
assert title.last_modified.timestamp() == last_modified.timestamp()
assert title.official_copy_data == official_copy_data
assert title.lr_uprns == lr_uprns
def _get_title_numbers(self, titles):
return set(map(lambda title: title.title_number, titles))
def _create_title(
self,
title_number,
register_data={},
geometry_data={},
is_deleted=False,
last_modified=datetime.now(),
official_copy_data={},
lr_uprns=[]):
print(INSERT_TITLE_QUERY_FORMAT.format(self._get_string_list_for_pg(lr_uprns)))
self.connection.cursor().execute(
INSERT_TITLE_QUERY_FORMAT.format(self._get_string_list_for_pg(lr_uprns)),
(
title_number,
json.dumps(register_data),
json.dumps(geometry_data),
is_deleted,
last_modified,
json.dumps(official_copy_data),
)
)
return self.connection.commit()
def _get_string_list_for_pg(self, strings):
return ','.join(['"{}"'.format(s) for s in strings])
def _delete_all_titles(self):
self.connection.cursor().execute(DELETE_ALL_TITLES_QUERY)
self.connection.commit()
def _connect_to_db(self):
return pg8000.connect(**DB_CONNECTION_PARAMS)
<file_sep>"""Add UPRN mapping table
Revision ID: 36316acef1a
Revises: <KEY>
Create Date: 2015-09-22 16:36:26.390621
"""
# revision identifiers, used by Alembic.
revision = '36316acef1a'
down_revision = '<KEY>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('uprn_mapping',
sa.Column('uprn', sa.String(length=20), nullable=False),
sa.Column('lr_uprn', sa.String(length=20), nullable=False),
sa.PrimaryKeyConstraint('uprn')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('uprn_mapping')
### end Alembic commands ###<file_sep>import logging
from elasticsearch import Elasticsearch # type: ignore
from elasticsearch_dsl import Search # type: ignore
from service import app
logger = logging.getLogger(__name__)
def get_properties_for_postcode(postcode, page_size, page_number):
logger.debug('Start get_properties_for_postcode using {}'.format(postcode))
search = _create_search(_get_postcode_search_doc_type())
query = search.filter('term', postcode=postcode).sort(
{'house_number_or_first_number': {'missing': '_last'}},
{'address_string': {'missing': '_last'}}
)
start_index, end_index = _get_start_and_end_indexes(page_number, page_size)
logger.debug('End get_properties_for_postcode')
return query[start_index:end_index].execute().hits
def get_properties_for_address(address, page_size, page_number):
logger.debug('Start get_properties_for_address using {}'.format(address))
search = _create_search(_get_address_search_doc_type())
query = search.query('match', address_string=address.lower())
start_index, end_index = _get_start_and_end_indexes(page_number, page_size)
logger.debug('End get_properties_for_address')
return query[start_index:end_index].execute().hits
def get_info():
return Elasticsearch([_get_elasticsearch_endpoint_url()]).info()
def _create_search(doc_type):
client = Elasticsearch([_get_elasticsearch_endpoint_url()])
search = Search(using=client, index=_get_index_name(), doc_type=doc_type)
search = search[0:_get_max_number_search_results()]
return search
def _get_start_and_end_indexes(page_number, page_size):
start_index = page_number * page_size
end_index = start_index + page_size
return start_index, end_index
def _get_index_name():
return app.config['ELASTICSEARCH_INDEX_NAME']
def _get_max_number_search_results():
return app.config['MAX_NUMBER_SEARCH_RESULTS']
def _get_page_size():
return app.config['SEARCH_RESULTS_PER_PAGE']
def _get_elasticsearch_endpoint_url():
return app.config['ELASTICSEARCH_ENDPOINT_URI']
def _get_postcode_search_doc_type():
return app.config['POSTCODE_SEARCH_DOC_TYPE']
def _get_address_search_doc_type():
return app.config['ADDRESS_SEARCH_DOC_TYPE']
<file_sep>import json # type: ignore
from decimal import Decimal # type: ignore
from datetime import datetime # type: ignore
from service import legacy_transmission_queue # type: ignore
FakeReturnSearchRowFound = {"search_datetime": datetime(2016, 1, 26, 13, 0, 30, 5449),
"user_id": "Test User",
"title_number": "GR12345",
"search_type": "D",
"purchase_type": "drvSummaryView",
"amount": Decimal('2'),
"cart_id": "374f501f4567",
"lro_trans_ref": None,
"viewed_datetime": None,
}
FakeReturnNoSearchRowFound = {} # type: ignore
FakeSearchTransmissionDict = {"SEARCH_DATETIME": "2016-01-26 13:00:30.005449",
"LRO_TRANS_REF": "1234",
"USER_ID": "Test User",
"VIEWED_DATETIME": "2015-12-01 14:34:14.362556",
"SEARCH_TYPE": "D",
"PURCHASE_TYPE": "drvSummaryView",
"AMOUNT": 2,
"CART_ID": "374f501f4567",
"TITLE_NUMBER": "GR12345",
"EVENT_ID": "Search"
}
FakeEmptySearchTransmissionDict = {} # type: ignore
class TestCreateSearchMessage:
def test_message_is_created_when_db_row_is_returned(self):
created_message = legacy_transmission_queue.create_user_search_message(FakeReturnSearchRowFound) # type: ignore
created_message = json.loads(created_message)
assert created_message['title_number'] == FakeSearchTransmissionDict['TITLE_NUMBER']
def test_message_is_not_created_when_no_row_returned(self):
created_message = legacy_transmission_queue.create_user_search_message(FakeReturnNoSearchRowFound) # type: ignore
created_message = json.loads(created_message)
assert created_message == {}
def integration_test_message_is_published_when_created_message_is_not_empty(self):
sent_message = legacy_transmission_queue.send_legacy_transmission(FakeSearchTransmissionDict) # type: ignore
assert sent_message is True
def integration_test_message_is_not_published_when_created_message_is_empty(self):
sent_message = legacy_transmission_queue.send_legacy_transmission(FakeEmptySearchTransmissionDict) # type: ignore
assert sent_message is False
if __name__ == '__main__':
test = TestCreateSearchMessage()
test.integration_test_message_is_published_when_created_message_is_not_empty()
<file_sep>"""Initial migration
Revision ID: 59935c933ab
Revises: None
Create Date: 2015-04-10 10:16:12.530777
"""
# revision identifiers, used by Alembic.
revision = '59935c933ab'
down_revision = None
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('title_register_data',
sa.Column('title_number', sa.String(length=10), nullable=False),
sa.Column('register_data', postgresql.JSON(), nullable=True),
sa.Column('geometry_data', postgresql.JSON(), nullable=True),
sa.PrimaryKeyConstraint('title_number')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('title_register_data')
### end Alembic commands ###
<file_sep>"""Restrict summary access
Revision ID: 73b223519cdb
Revises: 3<PASSWORD>
Create Date: 2016-03-03 10:38:09.877599
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '36316acef1a'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('user_search_and_results',
sa.Column('search_datetime', sa.DateTime(), nullable=False),
sa.Column('user_id', sa.String(length=20), nullable=False),
sa.Column('title_number', sa.String(length=20), nullable=False),
sa.Column('search_type', sa.String(length=20), nullable=False),
sa.Column('purchase_type', sa.String(length=20), nullable=False),
sa.Column('amount', sa.String(length=10), nullable=False),
sa.Column('cart_id', sa.String(length=30), nullable=True),
sa.Column('lro_trans_ref', sa.String(length=30), nullable=True),
sa.Column('viewed_datetime', sa.DateTime(), nullable=True),
sa.Column('valid', sa.Boolean, default=False),
sa.PrimaryKeyConstraint('search_datetime', 'user_id')
)
op.create_index('idx_title_number', 'user_search_and_results', ['title_number'], unique=False)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index('idx_title_number', table_name='user_search_and_results')
op.drop_table('user_search_and_results')
### end Alembic commands ###
<file_sep>from flask import jsonify, Response, request, make_response # type: ignore
import json
import logging
import math
from service import app, db_access, es_access, api_client
INTERNAL_SERVER_ERROR_RESPONSE_BODY = json.dumps(
{'error': 'Internal server error'}
)
JSON_CONTENT_TYPE = 'application/json'
logger = logging.getLogger(__name__)
TITLE_NOT_FOUND_RESPONSE = Response(
json.dumps({'error': 'Title not found'}),
status=404,
mimetype=JSON_CONTENT_TYPE
)
@app.errorhandler(Exception)
def handleServerError(error):
logger.error(
'An error occurred when processing a request',
exc_info=error
)
return Response(
INTERNAL_SERVER_ERROR_RESPONSE_BODY,
status=500,
mimetype=JSON_CONTENT_TYPE
)
# TODO: remove the root route when the monitoring tools can work without it
@app.route('/', methods=['GET'])
@app.route('/health', methods=['GET'])
def health_check():
errors = _check_elasticsearch_connection() + _check_postgresql_connection()
status = 'error' if errors else 'ok'
http_status = 500 if errors else 200
response_body = {'status': status}
if errors:
response_body['errors'] = errors
return Response(
json.dumps(response_body),
status=http_status,
mimetype=JSON_CONTENT_TYPE,
)
@app.route('/titles/<title_ref>', methods=['GET'])
def get_title(title_ref):
logger.debug('Start GET titles: {}'.format(title_ref))
data = db_access.get_title_register(title_ref)
if data:
result = {
'data': data.register_data,
'title_number': data.title_number,
'geometry_data': data.geometry_data,
}
logger.debug('End GET titles')
return jsonify(result)
else:
logger.debug('End GET titles. Title not found.')
return TITLE_NOT_FOUND_RESPONSE
@app.route('/titles/<title_ref>/official-copy', methods=['GET'])
def get_official_copy(title_ref):
logger.debug('Start GET titles official copy')
data = db_access.get_official_copy_data(title_ref)
if data:
result = {
'official_copy_data': {
'sub_registers': data.official_copy_data['sub_registers'],
'title_number': data.title_number,
}
}
logger.debug('End GET titles official copy')
return jsonify(result)
else:
logger.debug('End GET titles official copy.Title not found')
return TITLE_NOT_FOUND_RESPONSE
@app.route('/title_search_postcode/<postcode>', methods=['GET'])
def get_properties_for_postcode(postcode):
logger.debug('Start get properties for postcode using {}'.format(postcode))
page_number = int(request.args.get('page', 0))
normalised_postcode = postcode.replace('_', '').strip().upper()
# call Address_search_api to obtain list of AddressBase addresses
address_records = api_client.get_titles_by_postcode(normalised_postcode, page_number, _get_page_size())
# Iterate over dict collecting the AddressBase uprns to obtain the mapped LR_Uprns from PG
if address_records:
for address in address_records.get('data').get('addresses'):
address['title_number'] = 'not found'
address['tenure'] = ''
address_base_uprn = address.get('uprn')
if address_base_uprn:
# using AB uprn get Land Registry's version
logger.info('Searching for lruprn using adressbase uprn {}'.format(address_base_uprn))
lr_uprn_mapping = db_access.get_mapped_lruprn(address_base_uprn)
# Now using LR_uprn obtain some title details (currently title details and tenure)
if lr_uprn_mapping:
logger.info('Using {} to look up title number and register data'.format(lr_uprn_mapping.lr_uprn))
title_details = db_access.get_title_number_and_register_data(lr_uprn_mapping.lr_uprn)
if title_details:
logger.info('Title details found: {}, {}'.format(title_details.title_number, title_details.register_data.get('tenure')))
address['title_number'] = title_details.title_number
address['tenure'] = title_details.register_data.get('tenure')
logger.debug('Register_data found: {}'.format(title_details.register_data))
address['register_data'] = title_details.register_data
result = _paginated_address_records_v2(address_records, page_number)
return jsonify(result)
@app.route('/title_search_address/<address>', methods=['GET'])
def get_titles_for_address(address):
logger.debug('Start title_search_address using {}'.format(address))
page_number = int(request.args.get('page', 0))
address_records = es_access.get_properties_for_address(address, _get_page_size(), page_number)
result = _paginated_address_records(address_records, page_number)
logger.debug('End title_search_address - paginated address: {}'.format(result))
return jsonify(result)
@app.route('/save_search_request', methods=['POST'])
def save_search_request():
logger.debug('Start save_search_request')
# N.B.: "request.form" is a 'multidict', so need to flatten it first; assume single value per key.
form_dict = request.form.to_dict()
logger.debug('Request to be saved: {}'.format(form_dict))
cart_id = db_access.save_user_search_details(form_dict)
logger.debug('End save_search_request - returning cart_id: {}'.format(cart_id))
return cart_id, 200
@app.route('/user_can_view/<username>/<title_number>', methods=['GET'])
def user_can_view(username, title_number):
logger.debug('Start user_can_view using {} and {}'.format(username, title_number))
result = str(db_access.user_can_view(username, title_number))
logger.debug('End user_can_view. Result = {}'.format(result))
return make_response(result, 200) if result == 'True' else make_response(result, 403)
@app.route('/get_price/<product>', methods=['GET'])
def get_price(product):
logger.debug('Start get_price for product: {}'.format(product))
price = db_access.get_price(product)
logger.debug('End get_price for product. Price : {}'.format(price))
return str(price), 200
def _hit_postgresql_with_sample_query():
# Hitting PostgreSQL database to see if it responds properly
db_access.get_title_register('non-existing-title')
def _paginated_address_records(address_records, page_number):
# NOTE: our code uses the number of records reported by elasticsearch.
# Records that have been deleted are not included in the search results list.
nof_results = min(address_records.total, _get_max_number_search_results())
nof_pages = math.ceil(nof_results / _get_page_size()) # 0 if no results
if address_records:
title_numbers = [rec.title_number for rec in address_records]
titles = db_access.get_title_registers(title_numbers)
ordered = sorted(titles, key=lambda t: title_numbers.index(t.title_number))
title_dicts = [{'title_number': t.title_number, 'data': t.register_data} for t in ordered]
else:
title_dicts = []
return {'titles': title_dicts, 'number_pages': nof_pages, 'page_number': page_number,
'number_results': nof_results}
def _paginated_address_records_v2(address_records, page_number):
# NOTE: our code uses the number of records reported by elasticsearch.
# Records that have been deleted are not included in the search results list.
nof_results = min(address_records['data'].get('total'), _get_max_number_search_results())
nof_pages = math.ceil(nof_results / _get_page_size()) # 0 if no results
logger.info('Number of results: {}, Number of pages: {}'.format(nof_results, nof_pages))
if address_records:
title_dicts = [{'title_number': address.get('title_number'), 'data': address.get('register_data'), 'address': address.get('joined_fields')} for address in address_records['data']['addresses']]
logger.debug('list of paginated results {}'.format(title_dicts))
else:
logger.info('No records found')
title_dicts = []
return {'titles': title_dicts, 'number_pages': nof_pages, 'page_number': page_number,
'number_results': nof_results}
def _check_postgresql_connection():
"""Checks PostgreSQL connection and returns a list of errors"""
try:
logger.debug('Start check postgres connection')
_hit_postgresql_with_sample_query()
logger.debug('End check postgres connection')
return []
except Exception as e:
logger.error('Problem talking to Postgres: {}'.format(e))
error_message = 'Problem talking to PostgreSQL: {0}'.format(str(e))
return [error_message]
def _check_elasticsearch_connection():
"""Checks elasticsearch connection and returns a list of errors"""
try:
logger.debug('Start check elasticsearch connection')
status = es_access.get_info()['status']
if status == 200:
logger.debug('End check elasticsearch connection')
return []
else:
logger.debug('End check elasticsearch connection - not 200 status')
return ['Unexpected elasticsearch status: {}'.format(status)]
except Exception as e:
logger.error('Problem talking to elasticsearch: {}'.format(e))
return ['Problem talking to elasticsearch: {0}'.format(str(e))]
def _get_page_size():
return app.config['SEARCH_RESULTS_PER_PAGE']
def _get_max_number_search_results():
return app.config['MAX_NUMBER_SEARCH_RESULTS']
<file_sep>import elasticsearch
import mock
import pytest
import requests
from time import sleep
from config import CONFIG_DICT
from service import es_access
PROPERTY_BY_POSTCODE_DOC_TYPE = 'property_by_postcode_3'
PROPERTY_BY_ADDRESS_DOC_TYPE = 'property_by_address'
class TestEsAccess:
def setup_method(self, method):
self._ensure_empty_index()
def test_get_properties_for_postcode_throws_exception_on_unsuccessful_attempt_to_talk_to_es(self):
with mock.patch.dict(es_access.app.config, {'ELASTICSEARCH_ENDPOINT_URI': 'http://non-existing2342345.co.uk'}):
with pytest.raises(Exception) as e:
es_access.get_properties_for_postcode('XX000XX', 10, 0)
assert type(e.value) == elasticsearch.exceptions.ConnectionError
def test_get_properties_for_postcode_returns_properties_with_right_data(self):
postcode = 'XX000XX'
title_number = 'TITLE1001'
address_string = 'address string'
house_number = 123
entry_datetime = '2015-09-09T12:34:56.123+00'
self._create_property_for_postcode(postcode, title_number, address_string, house_number, entry_datetime)
self._wait_for_elasticsearch()
titles = es_access.get_properties_for_postcode(postcode, 10, 0)
assert len(titles) == 1
title = titles[0]
assert title.postcode == postcode
assert title.title_number == title_number
assert title.address_string == address_string
assert title.house_number_or_first_number == house_number
assert title.entry_datetime == entry_datetime
def test_get_properties_for_postcode_returns_properties_sorted_by_number_then_address(self):
postcode = 'XX000XX'
title_number_1, title_number_2, title_number_3 = 'TITLE1001', 'TITLE1002', 'TITLE1003'
self._create_property_for_postcode(postcode, title_number_1, 'address b 1', house_number=2)
self._create_property_for_postcode(postcode, title_number_2, 'address a 1', house_number=1)
self._create_property_for_postcode(postcode, title_number_3, 'address b 1', house_number=1)
self._wait_for_elasticsearch()
titles = es_access.get_properties_for_postcode(postcode, 10, 0)
assert self._get_title_numbers(titles) == [title_number_2, title_number_3, title_number_1]
def test_get_properties_for_postcode_returns_empty_list_when_no_matches(self):
properties = es_access.get_properties_for_postcode('XX000XX', 10, 0)
assert properties == []
def test_get_properties_for_postcode_does_not_return_addresses_from_different_postcodes(self):
postcode_1 = 'XX000XX'
postcode_2 = 'YY000YY'
title_number_1 = 'TITLE1001'
title_number_2 = 'TITLE1002'
self._create_property_for_postcode(postcode_1, title_number_1, 'address a 1')
self._create_property_for_postcode(postcode_2, title_number_2, 'address b 1')
self._wait_for_elasticsearch()
properties_for_postcode_1 = es_access.get_properties_for_postcode(postcode_1, 10, 0)
assert self._get_title_numbers(properties_for_postcode_1) == [title_number_1]
properties_for_postcode_2 = es_access.get_properties_for_postcode(postcode_2, 10, 0)
assert self._get_title_numbers(properties_for_postcode_2) == [title_number_2]
def test_get_properties_for_postcode_returns_the_right_page_of_records(self):
postcode = 'XX000XX'
for i in range(1, 6):
self._create_property_for_postcode('XX000XX', 'TITLE{}'.format(i), 'address {}'.format(i), i)
self._wait_for_elasticsearch()
first_page = es_access.get_properties_for_postcode(postcode, 2, 0)
assert self._get_title_numbers(first_page) == ['TITLE1', 'TITLE2']
second_page = es_access.get_properties_for_postcode(postcode, 2, 1)
assert self._get_title_numbers(second_page) == ['TITLE3', 'TITLE4']
third_page = es_access.get_properties_for_postcode(postcode, 2, 2)
assert self._get_title_numbers(third_page) == ['TITLE5']
def test_get_properties_for_address_throws_exception_on_unsuccessful_attempt_to_talk_to_es(self):
with mock.patch.dict(es_access.app.config, {'ELASTICSEARCH_ENDPOINT_URI': 'http://non-existing2342345.co.uk'}):
with pytest.raises(Exception) as e:
es_access.get_properties_for_address('XX000XX', 10, 0)
assert type(e.value) == elasticsearch.exceptions.ConnectionError
def test_get_properties_for_address_returns_properties_with_right_data(self):
title_number = 'TITLE1001'
address_string = 'address string'
entry_datetime = '2015-09-09T12:34:56.123+00'
self._create_property_for_address(title_number, address_string, entry_datetime)
self._wait_for_elasticsearch()
titles = es_access.get_properties_for_address(address_string, 10, 0)
assert len(titles) == 1
title = titles[0]
assert title.title_number == title_number
assert title.address_string == address_string
assert title.entry_datetime == entry_datetime
def test_get_properties_for_address_returns_properties_sorted_by_match_strength(self):
title_number_1, title_number_2, title_number_3 = 'TITLE1001', 'TITLE1002', 'TITLE1003'
self._create_property_for_address(title_number_1, 'almost same address')
self._create_property_for_address(title_number_2, 'other address')
self._create_property_for_address(title_number_3, 'same address')
self._wait_for_elasticsearch()
titles = es_access.get_properties_for_address('same address', 10, 0)
assert self._get_title_numbers(titles) == [title_number_3, title_number_1, title_number_2]
def test_get_properties_for_address_returns_empty_list_when_no_matches(self):
titles = es_access.get_properties_for_address('non-existing address', 10, 0)
assert titles == []
def test_get_properties_for_address_returns_the_right_page_of_records(self):
search_phrase = 'strongest match first'
address_1 = 'match first'
address_2 = 'weakest match'
address_3 = 'strongest match first'
title_number_1 = "MIDDLE"
title_number_2 = "WEAKEST"
title_number_3 = "STRONGEST"
self._create_property_for_address(title_number_1, address_1)
self._create_property_for_address(title_number_2, address_2)
self._create_property_for_address(title_number_3, address_3)
self._wait_for_elasticsearch()
first_page = es_access.get_properties_for_address(search_phrase, page_size=2, page_number=0)
assert self._get_title_numbers(first_page) == ['STRONGEST', 'MIDDLE']
second_page = es_access.get_properties_for_address(search_phrase, page_size=2, page_number=1)
assert self._get_title_numbers(second_page) == ['WEAKEST']
def test_get_info_throws_exception_on_unsuccessful_attempt_to_talk_to_es(self):
with mock.patch.dict(es_access.app.config, {'ELASTICSEARCH_ENDPOINT_URI': 'http://non-existing2342345.co.uk'}):
with pytest.raises(Exception) as e:
es_access.get_info()
assert type(e.value) == elasticsearch.exceptions.ConnectionError
def test_get_info_returns_cluster_info(self):
result = es_access.get_info()
assert result.get('status') == 200
assert result.get('cluster_name') == 'elasticsearch'
def _drop_index(self):
requests.delete(self._get_index_uri())
def _ensure_empty_index(self):
self._drop_index()
index = {
'mappings': {
PROPERTY_BY_POSTCODE_DOC_TYPE: {
'properties': {
'title_number': {'type': 'string', 'index': 'no'},
'postcode': {'type': 'string', 'index': 'not_analyzed'},
'house_number_or_first_number': {'type': 'integer', 'index': 'not_analyzed'},
'address_string': {'type': 'string', 'index': 'not_analyzed'},
'entry_datetime': {
'type': 'date',
'format': 'date_time',
'index': 'no'
},
}
},
PROPERTY_BY_ADDRESS_DOC_TYPE: {
'properties': {
'title_number': {'type': 'string', 'index': 'no'},
'address_string': {'type': 'string', 'index': 'analyzed'},
'entry_datetime': {'type': 'date', 'format': 'date_time', 'index': 'no'},
}
}
}
}
response = requests.put(self._get_index_uri(), json=index)
assert response.status_code == 200
def _create_property_for_postcode(
self, postcode, title_number, address_string, house_number=1, entry_datetime='2015-09-09T12:34:56.123+00'):
entry_json = {
'title_number': title_number,
'entry_datetime': entry_datetime,
'postcode': postcode,
'house_number_or_first_number': house_number,
'address_string': address_string,
}
uri = '{}/{}/'.format(self._get_index_uri(), PROPERTY_BY_POSTCODE_DOC_TYPE)
response = requests.post(uri, json=entry_json)
assert response.status_code == 201
def _create_property_for_address(
self, title_number, address_string, entry_datetime='2015-09-09T12:34:56.123+00'):
entry_json = {
'title_number': title_number,
'entry_datetime': entry_datetime,
'address_string': address_string,
}
uri = '{}/{}/'.format(self._get_index_uri(), PROPERTY_BY_ADDRESS_DOC_TYPE)
response = requests.post(uri, json=entry_json)
assert response.status_code == 201
def _get_title_numbers(self, search_results):
return list(map(lambda result: result.title_number, search_results))
def _get_index_uri(self):
return self._get_elasticsearch_uri() + '/' + CONFIG_DICT['ELASTICSEARCH_INDEX_NAME']
def _get_elasticsearch_uri(self):
return CONFIG_DICT['ELASTICSEARCH_ENDPOINT_URI']
def _wait_for_elasticsearch(self):
sleep(1.5)
<file_sep>#!/bin/sh
export SETTINGS='test'
export POSTGRES_USER='postgres'
export POSTGRES_PASSWORD='<PASSWORD>'
export POSTGRES_HOST='172.16.42.43'
export POSTGRES_PORT=5432
export POSTGRES_DB='test_register_data'
export ELASTICSEARCH_ENDPOINT_URI='http://localhost:9200'
export MAX_NUMBER_SEARCH_RESULTS=7
export SEARCH_RESULTS_PER_PAGE=3
export ELASTICSEARCH_INDEX_NAME='test-landregistry'
<file_sep>import hashlib
import config
import logging
from sqlalchemy import false # type: ignore
from sqlalchemy.orm.strategy_options import Load # type: ignore
from service import db, legacy_transmission_queue
from service.models import TitleRegisterData, UprnMapping, UserSearchAndResults, Validation
from datetime import datetime, timedelta
logger = logging.getLogger(__name__)
def save_user_search_details(params):
"""
Save user's search request details, for audit purposes.
Return cart id. as a hash with "block_size" of 64.
:param params:
"""
logger.debug('Start save_user_search_details')
logger.debug(params)
uf = 'utf-8'
hash = hashlib.sha1()
hash.update(bytes(params['MC_titleNumber'], uf))
hash.update(bytes(params['last_changed_datestring'], uf))
hash.update(bytes(params['last_changed_timestring'], uf))
# Convert byte hash to string, for DB usage
# Max. length of corresponding LRO_SESSION_ID is 64 for DB2 but we don't care much about that at present ;-)
cart_id = hash.hexdigest()[:30]
user_search_request = UserSearchAndResults(
search_datetime=params['MC_timestamp'],
user_id=params['MC_userId'],
title_number=params['MC_titleNumber'],
search_type=params['MC_searchType'],
purchase_type=params['MC_purchaseType'],
# needs to be in pence
amount=int(float(params['amount']) * 100),
cart_id=cart_id,
viewed_datetime=None,
lro_trans_ref=None,
valid=False,
)
logger.info('Sending to PostGres')
# Insert to DB.
db.session.add(user_search_request)
db.session.commit()
logger.info('Finished sending to PostGres')
# Put message on queue.
prepped_message = _create_queue_message(params, cart_id)
logger.info('Sending to legacy transmission queue')
logger.debug(prepped_message)
legacy_transmission_queue.send_legacy_transmission(prepped_message)
logger.info('Finished sending to transmission queue')
logger.debug('End save_user_search_details - returning cartId: {}'.format(cart_id))
return cart_id
def user_can_view(user_id, title_number):
"""
Get user's view details, after payment.
Returns True/False according to whether "viewing window" is valid or not.
:param user_id:
:param title_number:
"""
logger.debug('Start user_can_view')
status = False
# Get relevant record (only one assumed).
kwargs = {"user_id": user_id, "title_number": title_number}
logger.info('retreiving date and time of viewing')
view = UserSearchAndResults.query.filter_by(**kwargs).order_by(UserSearchAndResults.viewed_datetime.desc().nullslast()).first()
# 'viewed_datetime' denotes initial "access time" usage; name reflects different, earlier usage.
if view and view.viewed_datetime and view.valid:
minutes = int(config.CONFIG_DICT['VIEW_WINDOW_TIME'])
viewing_duration = datetime.now() - view.viewed_datetime
view_window_time = timedelta(minutes=minutes)
status = viewing_duration < view_window_time
logger.debug('End user_can_view. Returning {}'.format(status))
return status
def get_price(product):
result = Validation.query.filter_by(product=product).first()
return result.price
def get_title_register(title_number):
if title_number:
logger.debug('Start get_title_register using {}'.format(title_number))
# Will retrieve the first matching title that is not marked as deleted
result = TitleRegisterData.query.options(
Load(TitleRegisterData).load_only(
TitleRegisterData.title_number.name,
TitleRegisterData.register_data.name,
TitleRegisterData.geometry_data.name
)
).filter(
TitleRegisterData.title_number == title_number,
TitleRegisterData.is_deleted == false()
).first()
logger.debug('Returning result: {}'.format(result))
logger.debug('End get_title_register')
return result
else:
logger.debug('End get_title_register - No title number received')
raise TypeError('Title number must not be None.')
def get_title_registers(title_numbers):
logger.debug('Start get_title_registers using {}'.format(title_numbers))
# Will retrieve matching titles that are not marked as deleted
fields = [TitleRegisterData.title_number.name, TitleRegisterData.register_data.name,
TitleRegisterData.geometry_data.name]
query = TitleRegisterData.query.options(Load(TitleRegisterData).load_only(*fields))
results = query.filter(TitleRegisterData.title_number.in_(title_numbers),
TitleRegisterData.is_deleted == false()).all()
logger.debug('Returning results: {}'.format(results))
logger.debug('End get_title_registers ')
return results
def get_official_copy_data(title_number):
logger.debug('Start get_official_copy_data using: {}'.format(title_number))
result = TitleRegisterData.query.options(
Load(TitleRegisterData).load_only(
TitleRegisterData.title_number.name,
TitleRegisterData.official_copy_data.name
)
).filter(
TitleRegisterData.title_number == title_number,
TitleRegisterData.is_deleted == false()
).first()
logger.debug('Returning result: {}'.format(result))
logger.debug('End get_official_copy_data')
return result
def get_title_number_and_register_data(lr_uprn):
logger.debug('Start get_title_number_and_register_data using: {}'.format(lr_uprn))
amended_lr_uprn = '{' + lr_uprn + '}'
result = TitleRegisterData.query.options(
Load(TitleRegisterData).load_only(
TitleRegisterData.lr_uprns,
TitleRegisterData.title_number,
TitleRegisterData.register_data
)
).filter(
TitleRegisterData.lr_uprns.contains(amended_lr_uprn),
TitleRegisterData.is_deleted == false()
).all()
logger.debug('Returning result: {}'.format(result))
logger.debug('End get_title_number_and_register_data')
if result:
return result[0]
else:
return None
def get_mapped_lruprn(address_base_uprn):
logger.debug('Start get_mapped_lruprn using {}'.format(address_base_uprn))
result = UprnMapping.query.options(
Load(UprnMapping).load_only(
UprnMapping.lr_uprn.name,
UprnMapping.uprn.name
)
).filter(
UprnMapping.uprn == address_base_uprn
).first()
logger.debug('Returning result: {}'.format(result))
logger.debug('End get_mapped_lruprn')
return result
def _get_time():
# Postgres datetime format is YYYY-MM-DD MM:HH:SS.mm
_now = datetime.now()
return _now.strftime("%Y-%m-%d %H:%M:%S.%f")
def _create_queue_message(params, cart_id):
"""
Using parameters fed into the original method we need to create a json version with different keys
:param params:
:param cart_id:
:return:
"""
return {'search_datetime': params['MC_timestamp'],
'user_id': params['MC_userId'],
'title_number': params['MC_titleNumber'],
'search_type': params['MC_searchType'],
'purchase_type': params['MC_purchaseType'],
# needs to be in pence
'amount': int(float(params['amount']) * 100),
'cart_id': cart_id,
'viewed_datetime': None,
'lro_trans_ref': None}
<file_sep>"""Add Validation model
Revision ID: 9486941ad9cd
Revises: <KEY>
Create Date: 2016-03-03 11:38:14.372962
"""
# This line added manually!
import config
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
# This line added manually! [Original: op.create_table('validation',]
validation_table = op.create_table('validation',
sa.Column('price', sa.Integer(), nullable=False),
sa.Column('product', sa.String(length=20), nullable=True),
sa.PrimaryKeyConstraint('price')
)
### end Alembic commands ###
# This line added manually!
price = int(config.CONFIG_DICT['NOMINAL_PRICE'])
op.bulk_insert(validation_table, [{'price': price, 'product': 'drvSummary'}])
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('validation')
### end Alembic commands ###
<file_sep>import logging
import atexit
import os
from service.server import app
LOGGER = logging.getLogger(__name__)
@atexit.register
def handle_shutdown(*args, **kwargs):
LOGGER.info('Stopped the server')
LOGGER.info('Starting the server')
app.run(host="0.0.0.0", port=int(os.environ.get('PORT', '5000')))
<file_sep>#!/bin/sh
export SETTINGS='dev'
export POSTGRES_USER='postgres'
export POSTGRES_PASSWORD='<PASSWORD>'
export POSTGRES_HOST='172.16.42.43'
export POSTGRES_PORT=5432
export POSTGRES_DB='register_data'
export LOGGING_CONFIG_FILE_PATH='logging_config.json'
export FAULT_LOG_FILE_PATH='/var/log/applications/digital-register-api-fault.log'
export ELASTICSEARCH_ENDPOINT_URI='http://localhost:9200'
export ELASTICSEARCH_INDEX_NAME='landregistry'
export ADDRESS_SEARCH_API='http://landregistry.local:8002/'
export MAX_NUMBER_SEARCH_RESULTS=50
export PYTHONPATH=.
export SEARCH_RESULTS_PER_PAGE=20
export POSTCODE_SEARCH_DOC_TYPE=property_by_postcode_3
export ADDRESS_SEARCH_DOC_TYPE=property_by_address
export NOMINAL_PRICE=300
export LOGGING_LEVEL='DEBUG'
<file_sep>import json
import mock
from datetime import datetime
from collections import namedtuple
from elasticsearch_dsl.utils import AttrList
from service import app
from service.server import db_access, es_access, api_client
FakeTitleRegisterData = namedtuple(
'TitleRegisterData',
['title_number', 'register_data', 'geometry_data', 'official_copy_data']
)
FakeUprnMapping = namedtuple(
'UprnMapping',
['uprn', 'lr_uprn'])
FakeElasticsearchAddressHit = namedtuple(
'Hit',
['title_number', 'address_string', 'entry_datetime']
)
FakeElasticsearchPostcodeHit = namedtuple(
'Hit',
['title_number', 'postcode', 'house_number_or_first_number', 'address_string', 'entry_datetime']
)
TEST_EXCEPTION = Exception('Test exception')
ES_RESULT = {
"data": {
"addresses": [
{
"building_name": "1 INGLEWOOD HOUSE",
"building_number": "",
"department_name": "",
"dependent_locality": "",
"dependent_thoroughfare_name": "",
"double_dependent_locality": "",
"entry_datetime": "2014-06-07T09:01:38+00",
"joined_fields": "1 INGLEWOOD HOUSE, SIDWELL STREET, EXETER, EX1 1AA",
"organisation_name": "",
"post_town": "EXETER",
"postcode": "EX1 1AA",
"sub_building_name": "",
"thoroughfare_name": "SIDWELL STREET",
"uprn": "1234",
"x_coordinate": 292772.0,
"y_coordinate": 93294.0
}]
}
}
def _get_page_size():
return app.config['SEARCH_RESULTS_PER_PAGE']
def _get_es_postcode_results(*title_numbers, total=None):
result = AttrList([_get_es_postcode_result(i) for i in title_numbers])
result.total = len(title_numbers) if total is None else total
return result
def _get_empty_es_result(total=None):
result = AttrList([])
result.total = total if total else 0
return result
def _get_empty_api_client():
return {'data': {'addresses': [], 'total': 0, 'page_number': 0, 'page_size': 20}}
def _get_one_result_from_api_client():
return {'data': {'addresses': [
{
"building_name": "1 INGLEWOOD HOUSE",
"building_number": "",
"department_name": "",
"dependent_locality": "",
"dependent_thoroughfare_name": "",
"double_dependent_locality": "",
"entry_datetime": "2014-06-07T09:01:38+00",
"joined_fields": "1 INGLEWOOD HOUSE, SIDWELL STREET, EXETER, EX1 1AA",
"organisation_name": "",
"post_town": "EXETER",
"postcode": "EX1 1AA",
"sub_building_name": "",
"thoroughfare_name": "SIDWELL STREET",
"uprn": "10023117067",
"x_coordinate": 292772.0,
"y_coordinate": 93294.0,
"title_number": "EX100",
"tenure": "freehold",
"register_data": "blah"
}], 'total': 1, 'page_number': 1, 'page_size': 20}}
def _get_two_results_from_api_client():
return {'data': {'addresses': [
{
"building_name": "1 INGLEWOOD HOUSE",
"building_number": "",
"department_name": "",
"dependent_locality": "",
"dependent_thoroughfare_name": "",
"double_dependent_locality": "",
"entry_datetime": "2014-06-07T09:01:38+00",
"joined_fields": "1 INGLEWOOD HOUSE, SIDWELL STREET, EXETER, EX1 1AA",
"organisation_name": "",
"post_town": "EXETER",
"postcode": "EX1 1AA",
"sub_building_name": "",
"thoroughfare_name": "SIDWELL STREET",
"uprn": "10023117067",
"x_coordinate": 292772.0,
"y_coordinate": 93294.0,
"title_number": "EX100",
"tenure": "freehold",
"register_data": "blah"
},
{
"building_name": "2 INGLEWOOD HOUSE",
"building_number": "",
"department_name": "",
"dependent_locality": "",
"dependent_thoroughfare_name": "",
"double_dependent_locality": "",
"entry_datetime": "2014-06-07T09:01:38+00",
"joined_fields": "2 INGLEWOOD HOUSE, SIDWELL STREET, EXETER, EX1 1AA",
"organisation_name": "",
"post_town": "EXETER",
"postcode": "EX1 1AA",
"sub_building_name": "",
"thoroughfare_name": "SIDWELL STREET",
"uprn": "10023117067",
"x_coordinate": 292772.0,
"y_coordinate": 93294.0,
"title_number": "EX101",
"tenure": "freehold",
"register_data": "blah"
}], 'total': 2, 'page_number': 1, 'page_size': 20}}
def _get_api_client_response_when_es_finds_but_no_pg_result():
return {'data': {'addresses': [], 'total': 1, 'page_number': 1, 'page_size': 20}}
def _get_es_address_results(*title_numbers, total=None):
result = AttrList([_get_es_address_result(i) for i in title_numbers])
result.total = len(title_numbers) if total is None else total
return result
def _get_es_postcode_result(number):
return FakeElasticsearchPostcodeHit(
title_number=str(number),
postcode='SW11 2DR',
house_number_or_first_number=number,
address_string='address string {}'.format(number),
entry_datetime=datetime(2015, 8, 12, 12, 34, 56),
)
def _get_es_address_result(number):
return FakeElasticsearchAddressHit(
title_number=str(number),
address_string='address string {}'.format(number),
entry_datetime=datetime(2015, 8, 12, 12, 34, 56),
)
def _get_titles(*title_numbers):
return [_get_sample_title(i) for i in title_numbers]
def _get_sample_title(number):
return FakeTitleRegisterData(
str(number),
{'register': 'data {}'.format(number)},
{'geometry': 'geodata {}'.format(number)},
{'sub_registers': [{'A': 'register A {}'.format(number)}]},
)
def _get_sample_uprn():
return FakeUprnMapping(
uprn='1234',
lr_uprn='1234'
)
class TestHealthCheck:
def setup_method(self, method):
self.app = app.test_client()
@mock.patch.object(db_access, 'get_title_register', return_value=None)
@mock.patch.object(es_access, 'get_info', return_value={'status': 200})
def test_health_check_returns_200_response_when_data_stores_respond_properly(
self, mock_get_info, mock_get_user):
response = self.app.get('/health')
assert response.status_code == 200
assert response.data.decode() == '{"status": "ok"}'
@mock.patch.object(db_access, 'get_title_register', side_effect=Exception('Test PG exception'))
@mock.patch.object(es_access, 'get_info', return_value={'status': 200})
def test_health_check_returns_500_response_when_db_access_fails(self, mock_get_info, mock_get_user):
response = self.app.get('/health')
assert response.status_code == 500
json_response = json.loads(response.data.decode())
assert json_response == {
'status': 'error',
'errors': ['Problem talking to PostgreSQL: Test PG exception'],
}
@mock.patch.object(db_access, 'get_title_register', return_value=None)
@mock.patch.object(es_access, 'get_info', side_effect=Exception('Test ES exception'))
def test_health_check_returns_500_response_when_es_access_fails(self, mock_get_info, mock_get_user):
response = self.app.get('/health')
assert response.status_code == 500
json_response = json.loads(response.data.decode())
assert json_response == {
'status': 'error',
'errors': ['Problem talking to elasticsearch: Test ES exception'],
}
@mock.patch.object(db_access, 'get_title_register', side_effect=Exception('Test PG exception'))
@mock.patch.object(es_access, 'get_info', side_effect=Exception('Test ES exception'))
def test_health_check_returns_500_response_with_multiple_errors_when_both_data_stores_fail(
self, mock_get_info, mock_get_user):
response = self.app.get('/health')
assert response.status_code == 500
json_response = json.loads(response.data.decode())
assert json_response == {
'status': 'error',
'errors': [
'Problem talking to elasticsearch: Test ES exception',
'Problem talking to PostgreSQL: Test PG exception',
],
}
class TestGetTitle:
def setup_method(self, method):
self.app = app.test_client()
@mock.patch.object(db_access, 'get_title_register', return_value=None)
def test_get_title_calls_db_access_to_get_title(self, mock_get_title_register):
title_number = 'title123'
self.app.get('/titles/{}'.format(title_number))
mock_get_title_register.assert_called_once_with(title_number)
@mock.patch.object(db_access, 'get_title_register', return_value=None)
def test_get_title_returns_404_response_when_db_access_returns_none(self, mock_get_title_register):
response = self.app.get('/titles/title123')
assert response.status_code == 404
assert '"error": "Title not found"' in response.data.decode()
@mock.patch.object(db_access, 'get_title_register', side_effect=TEST_EXCEPTION)
def test_get_title_returns_generic_error_response_when_db_access_fails(self, mock_get_title_register):
response = self.app.get('/titles/title123')
assert response.status_code == 500
json_body = json.loads(response.data.decode())
assert json_body == {'error': 'Internal server error'}
def test_get_title_returns_200_response_with_title_from_db_access(self):
title_number = 'title123'
register_data = {'register': 'data'}
geometry_data = {'geometry': 'data'}
sub_registers = {'sub_registers': [{'A': 'register A'}]}
title = FakeTitleRegisterData(title_number, register_data, geometry_data, sub_registers)
with mock.patch('service.server.db_access.get_title_register', return_value=title):
response = self.app.get('/titles/{}'.format(title_number))
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert json_body == {
'title_number': title_number,
'data': register_data,
'geometry_data': geometry_data,
}
class TestGetOfficialCopy:
def setup_method(self, method):
self.app = app.test_client()
@mock.patch.object(db_access, 'get_official_copy_data', return_value=None)
def test_get_official_copy_calls_db_access_to_get_the_copy(self, mock_get_official_copy_data):
title_number = 'title123'
self.app.get('/titles/{}/official-copy'.format(title_number))
mock_get_official_copy_data.assert_called_once_with(title_number)
@mock.patch.object(db_access, 'get_official_copy_data', return_value=None)
def test_get_official_copy_returns_404_response_when_db_access_returns_none(self, mock_get_official_copy_data):
title_number = 'title123'
response = self.app.get('/titles/{}/official-copy'.format(title_number))
assert response.status_code == 404
json_body = json.loads(response.data.decode())
assert json_body == {'error': 'Title not found'}
@mock.patch.object(db_access, 'get_official_copy_data', side_effect=TEST_EXCEPTION)
def test_get_official_copy_returns_generic_error_response_when_db_access_fails(self, mock_get_official_copy_data):
response = self.app.get('/titles/title123/official-copy')
assert response.status_code == 500
json_body = json.loads(response.data.decode())
assert json_body == {'error': 'Internal server error'}
def test_get_official_copy_returns_200_response_with_copy_from_db_access(self):
title_number = 'title123'
sub_registers = [{'A': 'register A'}, {'B': 'register B'}]
title = FakeTitleRegisterData(
title_number, {'register': 'data'}, {'geometry': 'data'}, {'sub_registers': sub_registers}
)
with mock.patch('service.server.db_access.get_official_copy_data', return_value=title):
response = self.app.get('/titles/{}/official-copy'.format(title_number))
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert json_body == {
'official_copy_data': {
'sub_registers': sub_registers,
'title_number': title_number,
}
}
class TestGetPropertiesForPostcode:
def setup_method(self, method):
self.app = app.test_client()
@mock.patch.dict(app.config, {'SEARCH_RESULTS_PER_PAGE': 321})
@mock.patch.object(api_client, 'get_titles_by_postcode', return_value=_get_empty_api_client())
def test_get_properties_for_postcode_calls_db_access_with_page_number_and_normalised_postcode(
self, mock_get_properties):
postcode = ' Sw11_ 2dR '
normalised_postcode = 'SW11 2DR'
page_number = 123
self.app.get('/title_search_postcode/{}?page={}'.format(postcode, page_number))
mock_get_properties.assert_called_once_with(normalised_postcode, page_number, 321)
@mock.patch.object(api_client, 'get_titles_by_postcode', return_value=_get_empty_api_client())
def test_get_properties_for_postcode_calls_es_access_with_default_page_number_when_not_provided(
self, mock_get_properties):
postcode = 'SW11 2DR'
self.app.get('/title_search_postcode/{}'.format(postcode))
mock_get_properties.assert_called_once_with(postcode, 0, _get_page_size())
@mock.patch.object(api_client, 'get_titles_by_postcode', side_effect=TEST_EXCEPTION)
def test_get_properties_for_postcode_returns_generic_error_response_when_fails(self, mock_get_properties):
response = self.app.get('/title_search_postcode/SW112DR')
assert response.status_code == 500
json_body = json.loads(response.data.decode())
assert json_body == {'error': 'Internal server error'}
@mock.patch.object(db_access, 'get_mapped_lruprn', return_value=_get_titles(1))
def test_get_properties_for_postcode_calls_db_access_with_uprn_from_elasticsearch(
self, mock_get_registers):
with mock.patch('service.server.api_client.get_titles_by_postcode') as mock_get_properties:
mock_get_properties.return_value = ES_RESULT
self.app.get('/title_search_postcode/SW11 2DR')
mock_get_registers.assert_called_once_with('1234')
@mock.patch.object(api_client, 'get_titles_by_postcode', return_value=_get_one_result_from_api_client())
@mock.patch.object(db_access, 'get_mapped_lruprn', return_value=_get_sample_uprn())
@mock.patch.object(db_access, 'get_title_number_and_register_data', return_value=_get_sample_title(1))
def test_get_properties_for_postcode_returns_response_in_correct_format(
self, mock_get_titles, mock_get_mapped_lruprn, get_title_and_register_data):
response = self.app.get('/title_search_postcode/SW11%202DR')
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert json_body == {
'number_pages': 1,
'number_results': 1,
'page_number': 0,
'titles': [
{'address': '1 INGLEWOOD HOUSE, SIDWELL STREET, EXETER, EX1 1AA', 'data': {'register': 'data 1'}, 'title_number': '1'}
]
}
@mock.patch.object(api_client, 'get_titles_by_postcode', return_value=_get_two_results_from_api_client())
@mock.patch.object(db_access, 'get_mapped_lruprn', return_value=_get_sample_uprn())
@mock.patch.object(db_access, 'get_title_number_and_register_data', return_value=_get_sample_title(1))
def test_get_properties_for_postcode_returns_titles_in_order_given_by_api_client(
self, mock_get_titles, mock_get_mapped_lruprn, get_title_and_register_data):
response = self.app.get('/title_search_postcode/SW11%202DR')
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert 'titles' in json_body
assert json_body['titles'] == [
{'address': '1 INGLEWOOD HOUSE, SIDWELL STREET, EXETER, EX1 1AA', 'data': {'register': 'data 1'}, 'title_number': '1'},
{'address': '2 INGLEWOOD HOUSE, SIDWELL STREET, EXETER, EX1 1AA', 'data': {'register': 'data 1'}, 'title_number': '1'}
]
@mock.patch.object(api_client, 'get_titles_by_postcode', return_value=_get_two_results_from_api_client())
@mock.patch.object(db_access, 'get_mapped_lruprn', return_value=_get_sample_uprn())
@mock.patch.object(db_access, 'get_title_number_and_register_data', return_value=_get_sample_title(1))
def test_get_properties_for_postcode_response_contains_requested_page_number_when_present(self,
mock_get_titles,
mock_get_mapped_lruprn,
get_title_and_register_data):
requested_page_number = 12
response = self.app.get('/title_search_postcode/SW11%202DR?page={}'.format(requested_page_number))
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert 'page_number' in json_body
assert json_body['page_number'] == requested_page_number
@mock.patch.object(api_client, 'get_titles_by_postcode', return_value=_get_api_client_response_when_es_finds_but_no_pg_result())
def test_get_properties_for_postcode_returns_requested_page_number_when_it_does_not_exist(
self, mock_get_titles):
requested_page_number = 3
page_size = 5
with mock.patch.dict(app.config, {'SEARCH_RESULTS_PER_PAGE': page_size}):
response = self.app.get('/title_search_postcode/SW11%202DR?page={}'.format(requested_page_number))
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert 'page_number' in json_body
assert json_body == {
'number_pages': 1,
'number_results': 1,
'page_number': requested_page_number,
'titles': []
}
@mock.patch.object(api_client, 'get_titles_by_postcode', return_value=_get_empty_api_client())
def test_get_properties_for_postcode_returns_right_response_when_no_results_from_api_client(self, mock_get_properties):
response = self.app.get('/title_search_postcode/SW11%202DR')
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert json_body == {'number_pages': 0, 'number_results': 0, 'page_number': 0, 'titles': []}
@mock.patch.object(api_client, 'get_titles_by_postcode', return_value=_get_api_client_response_when_es_finds_but_no_pg_result())
@mock.patch.object(db_access, 'get_mapped_lruprn', return_value=None)
def test_get_properties_for_postcode_returns_right_response_when_no_results_from_pg(
self, mock_get_titles, mock_get_mapped_lruprn):
response = self.app.get('/title_search_postcode/SW11%202DR')
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert json_body == {'number_pages': 1, 'number_results': 1, 'page_number': 0, 'titles': []}
class TestGetPropertiesForAddress:
def setup_method(self, method):
self.app = app.test_client()
@mock.patch.dict(app.config, {'SEARCH_RESULTS_PER_PAGE': 321})
@mock.patch.object(es_access, 'get_properties_for_address', return_value=[])
def test_get_properties_for_address_calls_es_access_with_page_number_and_search_term(self, mock_get_properties):
search_term = 'search term'
page_number = 123
self.app.get('/title_search_address/{}?page={}'.format(search_term, page_number))
mock_get_properties.assert_called_once_with(search_term, 321, page_number)
@mock.patch.object(es_access, 'get_properties_for_address', return_value=[])
def test_get_properties_for_address_calls_es_access_with_default_page_number_when_not_provided(
self, mock_get_properties):
search_term = '<PASSWORD>'
self.app.get('/title_search_address/{}'.format(search_term))
mock_get_properties.assert_called_once_with(search_term, _get_page_size(), 0)
@mock.patch.object(es_access, 'get_properties_for_address', side_effect=TEST_EXCEPTION)
def test_get_properties_for_address_returns_generic_error_response_when_fails(self, mock_get_properties):
response = self.app.get('/title_search_address/searchterm')
assert response.status_code == 500
json_body = json.loads(response.data.decode())
assert json_body == {'error': 'Internal server error'}
@mock.patch.object(db_access, 'get_title_registers', return_value=_get_titles(1))
def test_get_properties_for_address_calls_db_access_with_data_from_elasticsearch(
self, mock_get_registers):
with mock.patch('service.server.es_access.get_properties_for_address') as mock_get_properties:
mock_get_properties.return_value = _get_es_address_results(1, 2, 3, 4)
self.app.get('/title_search_address/searchterm')
mock_get_registers.assert_called_once_with(['1', '2', '3', '4'])
@mock.patch.object(es_access, 'get_properties_for_address', return_value=_get_es_address_results(1, 2))
@mock.patch.object(db_access, 'get_title_registers', return_value=_get_titles(1, 2))
def test_get_properties_for_address_returns_response_in_correct_format(
self, mock_get_registers, mock_get_properties):
response = self.app.get('/title_search_address/searchterm')
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert json_body == {
'number_pages': 1,
'number_results': 2,
'page_number': 0,
'titles': [
{'data': {'register': 'data 1'}, 'title_number': '1'},
{'data': {'register': 'data 2'}, 'title_number': '2'}
]
}
@mock.patch.object(es_access, 'get_properties_for_address', return_value=_get_es_address_results(3, 1, 2))
@mock.patch.object(db_access, 'get_title_registers', return_value=_get_titles(1, 2, 3))
def test_get_properties_for_address_returns_titles_in_order_given_by_es_access(
self, mock_get_registers, mock_get_properties):
response = self.app.get('/title_search_address/searchterm')
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert 'titles' in json_body
assert json_body['titles'] == [
{'data': {'register': 'data 3'}, 'title_number': '3'},
{'data': {'register': 'data 1'}, 'title_number': '1'},
{'data': {'register': 'data 2'}, 'title_number': '2'},
]
@mock.patch.object(es_access, 'get_properties_for_address', return_value=_get_es_address_results(1, 2, total=4))
@mock.patch.object(db_access, 'get_title_registers', return_value=_get_titles(1, 2))
def test_get_properties_for_address_response_contains_right_number_of_pages_when_last_page_full(
self, mock_get_registers, mock_get_properties):
page_size = 2
with mock.patch.dict(app.config, {'SEARCH_RESULTS_PER_PAGE': page_size}):
response = self.app.get('/title_search_address/searchterm?page=1')
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert 'page_number' in json_body
assert json_body['number_pages'] == 2
@mock.patch.object(es_access, 'get_properties_for_address', return_value=_get_es_address_results(1, total=4))
@mock.patch.object(db_access, 'get_title_registers', return_value=_get_titles(1))
def test_get_properties_for_address_response_contains_right_number_of_pages_when_last_page_not_full(
self, mock_get_registers, mock_get_properties):
page_size = 2
with mock.patch.dict(app.config, {'SEARCH_RESULTS_PER_PAGE': page_size}):
response = self.app.get('/title_search_address/searchterm?page=1')
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert 'page_number' in json_body
assert json_body['number_pages'] == 2
@mock.patch.object(es_access, 'get_properties_for_address', return_value=_get_es_address_results(1, total=200))
@mock.patch.object(db_access, 'get_title_registers', return_value=_get_titles(1))
def test_get_properties_for_address_response_contains_requested_page_number_when_present(
self, mock_get_properties, mock_get_registers):
requested_page_number = 12
response = self.app.get('/title_search_address/searchterm?page={}'.format(requested_page_number))
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert 'page_number' in json_body
assert json_body['page_number'] == requested_page_number
@mock.patch.object(es_access, 'get_properties_for_address', return_value=_get_es_address_results(total=10))
@mock.patch.object(db_access, 'get_title_registers', return_value=_get_titles(1))
def test_get_properties_for_address_returns_requested_page_number_when_it_does_not_exist(
self, mock_get_registers, mock_get_properties):
requested_page_number = 3
page_size = 5
with mock.patch.dict(app.config, {'SEARCH_RESULTS_PER_PAGE': page_size}):
response = self.app.get('/title_search_address/searchterm?page={}'.format(requested_page_number))
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert 'page_number' in json_body
assert json_body == {
'number_pages': 2,
'number_results': 10,
'page_number': requested_page_number,
'titles': []
}
@mock.patch.object(es_access, 'get_properties_for_address', return_value=_get_empty_es_result())
def test_get_properties_for_address_returns_right_response_when_no_results_from_es(self, mock_get_properties):
response = self.app.get('/title_search_address/searchterm')
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert json_body == {'number_pages': 0, 'number_results': 0, 'page_number': 0, 'titles': []}
@mock.patch.object(es_access, 'get_properties_for_address', return_value=_get_es_address_results(1, total=1))
@mock.patch.object(db_access, 'get_title_registers', return_value=[])
def test_get_properties_for_address_returns_right_response_when_no_results_from_pg(
self, mock_get_registers, mock_get_properties):
response = self.app.get('/title_search_address/searchterm')
assert response.status_code == 200
json_body = json.loads(response.data.decode())
assert json_body == {'number_pages': 1, 'number_results': 1, 'page_number': 0, 'titles': []}
<file_sep>alembic==0.8.4
amqp==1.4.9
anyjson==0.3.3
blinker==1.3
cov-core==1.14.0
coverage==3.7.1
elasticsearch==1.4.0
elasticsearch-dsl==0.0.3
Flask==0.10.1
Flask-Migrate==1.3.1
Flask-Script==2.0.5
Flask-SQLAlchemy==2.0
itsdangerous==0.24
Jinja2==2.7.3
kombu==3.0.33
Mako==1.0.3
MarkupSafe==0.23
mock==1.0.1
mypy-lang==0.2.0
pbr==1.8.1
pg8000==1.10.1
py==1.4.25
pytest==2.6.3
pytest-cov==1.8.0
python-dateutil==2.4.2
python-editor==0.5
requests==2.5.1
responses==0.3.0
six==1.10.0
SQLAlchemy==0.9.8
stevedore==1.11.0
urllib3==1.14
virtualenv==14.0.6
virtualenv-clone==0.2.6
virtualenvwrapper==4.7.1
Werkzeug==0.9.6
wheel==0.29.0
<file_sep>import logging # type: ignore
import json # type: ignore
from kombu import BrokerConnection, Exchange, Queue, Producer # type: ignore
from config import QUEUE_DICT # type: ignore
from typing import Dict # type: ignore
logger = logging.getLogger(__name__)
USER_SEARCH_INSERT = 2
# Loosely derived from kombu /examples/complete_send_manual.py
def create_legacy_queue_connection():
logger.debug('Start create_legacy_queue_connection')
OUTGOING_QUEUE = QUEUE_DICT['OUTGOING_QUEUE'] # type: ignore
OUTGOING_QUEUE_HOSTNAME = QUEUE_DICT['OUTGOING_QUEUE_HOSTNAME'] # type: ignore
outgoing_exchange = Exchange("legacy_transmission", type='direct')
logger.info('Creating queue using queue: {}, hostname: {}, exchange: {}'.
format(OUTGOING_QUEUE, OUTGOING_QUEUE_HOSTNAME, outgoing_exchange))
queue = Queue(OUTGOING_QUEUE, outgoing_exchange, routing_key="legacy_transmission")
connection = BrokerConnection(hostname=OUTGOING_QUEUE_HOSTNAME,
userid=QUEUE_DICT['OUTGOING_QUEUE_USERID'], # type: ignore
password=<PASSWORD>['<PASSWORD>ING_QUEUE_PASSWORD'], # type: ignore
virtual_host="/")
# Queue must be declared, otherwise messages are silently sent to a 'black hole'!
logger.info('Declaring queue')
bound_queue = queue(connection)
bound_queue.declare()
logger.info('Queue declared')
producer = Producer(connection, exchange=outgoing_exchange, routing_key="legacy_transmission")
logger.debug('End create_legacy_queue_connection. Returning producer.')
return producer
def send_legacy_transmission(user_search_result: Dict):
logger.debug('Start send_legacy_transmission using {}'.format(user_search_result))
producer = create_legacy_queue_connection()
user_search_transmission = create_user_search_message(user_search_result)
if user_search_transmission:
logger.info('Message created and sending to queue')
producer.publish(user_search_transmission, serializer="json", compression="zlib")
logger.info('End send_legacy_transmission. Message sent')
return True
else:
logger.error('End send_legacy_transmission. Error sending message')
return False
def create_user_search_message(user_search_result: Dict):
logger.debug('Start create_user_search_message')
# Prepare for serialisation: values must be sent as strings.
user_search_transmission = {k: str(v) for k, v in user_search_result.items()}
# Add the relevant event id.
if user_search_transmission:
user_search_transmission['EVENT_ID'] = USER_SEARCH_INSERT # type: ignore
logger.debug('End create_user_search_message. Returning: {}'.format(user_search_transmission))
return json.dumps(user_search_transmission)
<file_sep>import os
from typing import Dict, Union
user = os.environ['POSTGRES_USER']
password = os.environ['<PASSWORD>GRES_PASSWORD']
host = os.environ['POSTGRES_HOST']
port = os.environ['POSTGRES_PORT']
database = os.environ['POSTGRES_DB']
max_number = int(os.environ['MAX_NUMBER_SEARCH_RESULTS'])
search_results = int(os.environ['SEARCH_RESULTS_PER_PAGE'])
db_uri_template = 'postgresql+pg8000://{0}:{1}@{2}:{3}/{4}'
sql_alchemy_uri = db_uri_template.format(user, password, host, port, database)
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
fault_log_file_path = os.environ['FAULT_LOG_FILE_PATH']
elasticsearch_endpoint_uri = os.environ['ELASTICSEARCH_ENDPOINT_URI']
elasticsearch_index_name = os.environ['ELASTICSEARCH_INDEX_NAME']
postcode_search_doc_type = os.environ['POSTCODE_SEARCH_DOC_TYPE']
address_search_doc_type = os.environ['ADDRESS_SEARCH_DOC_TYPE']
address_search_api_url = os.environ['ADDRESS_SEARCH_API']
nominal_price = os.getenv('NOMINAL_PRICE', '300') # Nominal price, in pence.
view_window_time = os.getenv('VIEW_WINDOW_TIME', '60') # Viewing access duration, in minutes.
logger_level = os.getenv('LOGGING_LEVEL', 'WARN')
QUEUE_DICT = {
'OUTGOING_QUEUE': os.environ.get('OUTGOING_QUEUE', 'legacy_transmission_queue'),
'OUTGOING_QUEUE_HOSTNAME': os.environ.get('OUTGOING_QUEUE_HOSTNAME', 'localhost'),
'OUTGOING_QUEUE_USERID': os.environ.get('OUTGOING_QUEUE_USERID', "guest"),
'OUTGOING_QUEUE_PASSWORD': os.environ.get('OUTGOING_QUEUE_PASSWORD', "guest"),
}
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'SQLALCHEMY_DATABASE_URI': sql_alchemy_uri,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'FAULT_LOG_FILE_PATH': fault_log_file_path,
'ELASTICSEARCH_ENDPOINT_URI': elasticsearch_endpoint_uri,
'ELASTICSEARCH_INDEX_NAME': elasticsearch_index_name,
'MAX_NUMBER_SEARCH_RESULTS': max_number,
'SEARCH_RESULTS_PER_PAGE': search_results,
'POSTCODE_SEARCH_DOC_TYPE': postcode_search_doc_type,
'ADDRESS_SEARCH_DOC_TYPE': address_search_doc_type,
'ADDRESS_SEARCH_API': address_search_api_url,
'NOMINAL_PRICE': nominal_price,
'VIEW_WINDOW_TIME': view_window_time,
'LOGGING_LEVEL': logger_level,
} # type: Dict[str, Union[bool, str, int]]
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['TESTING'] = True
CONFIG_DICT['FAULT_LOG_FILE_PATH'] = '/dev/null'
<file_sep>"""Create lr_uprn column with a GIN index
Revision ID: <KEY>
Revises: <KEY>
Create Date: 2015-09-22 10:36:04.307515
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('title_register_data', sa.Column('lr_uprns', postgresql.ARRAY(sa.String()), nullable=True))
op.create_index('idx_title_uprns', 'title_register_data', ['lr_uprns'], unique=False, postgresql_using='gin')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index('idx_title_uprns', table_name='title_register_data')
op.drop_column('title_register_data', 'lr_uprns')
### end Alembic commands ###
<file_sep>#!/usr/bin/python
import argparse
import csv
import logging
from logging.config import dictConfig # type: ignore
import os
import pg8000 # type: ignore
LOGGER = logging.getLogger(__name__)
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '%(asctime)s level=[%(levelname)s] logger=[%(name)s] thread=[%(threadName)s] message=[%(message)s] exception=[%(exc_info)s]'
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'default',
'stream': 'ext://sys.stdout'
}
},
'root': {
'level': 'INFO',
'handlers': ['console']
}
}
def import_mapping_data(input_file_path, lines_to_skip, overwrite_existing, clear_data, page_size):
"""Reads the input CSV file and saves its lines in the database"""
_log_data_import_started(input_file_path, lines_to_skip, clear_data, overwrite_existing)
connection = None
try:
with open(input_file_path) as file:
reader = csv.reader(file, delimiter=',', quotechar='"')
connection = _connect_to_db()
db_cursor = connection.cursor()
if clear_data:
_clear_mapping_table(db_cursor)
db_cursor.connection.commit()
overwrite_db_rows = overwrite_existing and not clear_data
_process_input_lines(reader, db_cursor, lines_to_skip, overwrite_db_rows, page_size)
LOGGER.info('Completed import')
except Exception as e:
LOGGER.error('An error occurred when importing mapping data', exc_info=e)
finally:
if connection:
connection.close()
def _process_uprn_mapping(cursor, uprn, lr_uprn, overwrite, row_buffer, page_size):
updated_buffer = row_buffer + [(uprn, lr_uprn)]
if len(updated_buffer) >= page_size:
_flush_to_db(cursor, overwrite, updated_buffer)
return []
return updated_buffer
def _flush_to_db(db_cursor, overwrite_existing, row_buffer):
"""Saves the content of the cache (row_buffer) into the database"""
if overwrite_existing:
uprns = [str(row[0]) for row in row_buffer]
_delete_entries_by_uprn(db_cursor, uprns)
_insert_mapping_data(db_cursor, row_buffer)
db_cursor.connection.commit()
def _process_input_lines(csv_reader, db_cursor, lines_to_skip, overwrite, page_size):
if lines_to_skip > 0:
LOGGER.info('Skipping first {} lines'.format(lines_to_skip))
current_line_number = 1
row_buffer = []
for row in csv_reader:
if current_line_number > lines_to_skip:
uprn = row[1].replace('"', '').strip()
lr_uprn = row[0].strip()
row_buffer = _process_uprn_mapping(db_cursor, uprn, lr_uprn, overwrite, row_buffer, page_size)
if not row_buffer:
_log_records_saved(page_size, total=current_line_number - lines_to_skip)
current_line_number += 1
total_records = current_line_number - lines_to_skip - 1
_process_remaining_buffered_data(row_buffer, db_cursor, overwrite, total_records)
def _process_remaining_buffered_data(row_buffer, db_cursor, overwrite, total_records):
nof_remaining_records = len(row_buffer)
if nof_remaining_records > 0:
_flush_to_db(db_cursor, overwrite, row_buffer)
_log_records_saved(nof_remaining_records, total_records)
def _log_data_import_started(input_file_path, lines_to_skip, clear_data, overwrite_existing):
LOGGER.info('Starting data import. From file: {}, lines to skip: {}, clear DB: {}, overwrite existing {}'.format(
input_file_path, lines_to_skip, clear_data, overwrite_existing
))
def _log_records_saved(number_of_records, total):
LOGGER.info('Saved {} records. Total saved: {}'.format(number_of_records, total))
def _setup_logging():
try:
dictConfig(LOGGING_CONFIG)
except IOError as e:
raise(Exception('Failed to load logging configuration', e))
def _connect_to_db():
return pg8000.connect(
host=os.environ['POSTGRES_HOST'],
port=int(os.environ['POSTGRES_PORT']),
database=os.environ['POSTGRES_DB'],
user=os.environ['POSTGRES_USER'],
password=<PASSWORD>['<PASSWORD>'],
)
def _parse_command_line_args():
parser = argparse.ArgumentParser(
description='This script imports mapping data (from URPN to Land Registry "UPRN") from a CSV file into the database'
)
parser.add_argument('-f', '--file', type=str, required=True, help='Source CSV file path')
parser.add_argument('-s', '--skip', type=int, default=0, help='Number of first records to skip')
parser.add_argument('-o', '--overwrite', nargs='?', const=True, default=False, help='When present, existing records are overwritten')
parser.add_argument('-c', '--clear', nargs='?', const=True, default=False, help='When present, DB data is cleared before the import')
parser.add_argument('-p', '--page_size', default=5000, help='Page size - number of records to save into to DB at once')
return parser.parse_args()
def _insert_mapping_data(db_cursor, rows):
try:
db_cursor.executemany('insert into uprn_mapping (uprn, lr_uprn) values (%s, %s)', rows)
except Exception:
LOGGER.error('An error occurred whilst inserting rows. The process will carry on and skip this one.')
def _delete_entries_by_uprn(db_cursor, uprns):
# TODO: this shouldn't be done using string.format, but I couldn't get pg8000 to work with lists
db_cursor.execute("delete from uprn_mapping where uprn in ('{}')".format("','".join(uprns)))
def _clear_mapping_table(db_cursor):
db_cursor.execute('delete from uprn_mapping')
if __name__ == '__main__':
args = _parse_command_line_args()
_setup_logging()
import_mapping_data(args.file, args.skip, args.overwrite, args.clear, args.page_size)
<file_sep># digital-register-api
This is the repo for the backend of the digital register service. It is written in Python, with the Flask framework.
### Digital Register API build status
[/badge/icon)](http://52.16.47.1/job/digital-register-api-unit-test%20(Master)/)
### Digital Register Acceptance tests status
[](http://52.16.47.1/job/digital-register-frontend-acceptance-tests/)
## Setup
To create a virtual env, run the following from a shell:
```
mkvirtualenv -p /usr/bin/python3 digital-register-api
source environment.sh
pip install -r requirements.txt
```
## Run unit tests
To run unit tests for the Digital Register, go to its folder and run `lr-run-tests`.
## Run integration tests
In order to run Digital Register API integration tests, go to its folder and run `./run_integration_tests.sh`.
This script creates the test database (test_register_data) and test elasticsearch index (test-landregistry)
and runs the tests against them.
Make sure you have postgresql and elasticsearch services running (by executing the `lr-start-services` command).
## Run the acceptance tests
To run the acceptance tests for the Digital Register, go to the `acceptance-tests` folder inside the `digital-register-frontend` repository and run:
```
./run-tests.sh
```
You will need to have a Postgres database running (see `db/lr-start-db` and `db/insert-fake-data` scripts in the [centos-dev-env](https://github.com/LandRegistry/centos-dev-env) project), as well as the digital-register-frontend and digital-register-api applications running on your development VM.
## Run the server
### Run in dev mode
To run the server in dev mode, execute the following command:
./run_flask_dev.sh
### Run using gunicorn
To run the server using gunicorn, activate your virtual environment
and execute the following commands:
pip install gunicorn
gunicorn -p /tmp/gunicorn.pid service.server:app -c gunicorn_settings.py
## Jenkins builds
We use three separate builds:
- [branch](http://192.168.127.12/job/digital-register-api-unit-test%20(Branch)/)
- [master](http://192.168.127.12/job/digital-register-api-unit-test%20(Master)/)
- [acceptance](http://5192.168.3.11/job/digital-register-frontend-acceptance-tests/)
## Database migrations
We use Flask-Migrate (a project which integrates Flask with Alembic, a migration
tool from the author of SQLAlchemy) to handle database migrations. Every time a
model is added or modified, a migration script should be created and committed
to our version control system.
From inside a virtual environment, and after sourcing environment.sh, run the
following to add a new migration script:
python3 manage.py db migrate -m "add foobar field"
Should you ever need to write a migration script from scratch (to migrate data
for instance) you should use the revision command instead of migrate:
python3 manage.py db revision -m "do something complicated"
Read Alembic's documentation to learn more.
Once you have a migration script, the next step is to apply it to the database.
To do this run the upgrade command:
python3 manage.py db upgrade
## Populate the mapping table
Once you have the new uprn_mapping table, you may want to have some data in it.
Assume you have created and working on the digital-register-api virtual environment:
python3 import_uprn_mapping_data.py -file path/to/file.csv
Some useful operators:
-f path/to/file.csv This will import a CSV file.
-s <number> This will start the file read from <number>. Handy if the import stopped half way through a million records and you need to start again around 500000.
-o This will delete and replace any existing entries
-c This will clear the whole table and start again
<file_sep>#!/bin/bash
source /usr/bin/virtualenvwrapper.sh
workon digital-register-api
source environment.sh
source environment_integration_test.sh
sudo su postgres -c "dropdb test_register_data"
sudo su postgres -c "createdb test_register_data"
python3 manage.py db upgrade
py.test integration_tests/
deactivate | d50460ed488c9ebf93bceda37e6c72cf6c2c90b8 | [
"Markdown",
"Python",
"Text",
"Shell"
] | 26 | Python | LandRegistry/digital-register-api | 853e5f5a8fcb5369c3679bb893cd88bf03c89855 | 2da4467515045a297080bcff7f3dc3616ce9cd94 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import c3 from 'c3';
import './Chart.css';
import PropTypes from 'prop-types';
class Chart extends Component {
static propTypes = {
columns: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number]))),
chartType: PropTypes.string,
};
componentDidMount() {
// When the component mounts the first time we update
// the chart.
this.updateChart();
}
componentDidUpdate() {
// When we receive a new prop then we update the chart again.
this.updateChart();
}
updateChart() {
const { columns, chartType } = this.props;
c3.generate({
bindto: '#chart',
data: {
columns,
type: chartType
}
});
}
render() {
return <div id="chart" />;
}
}
export default Chart;
<file_sep>import React, { Component } from 'react';
import moment from 'moment';
import PropTypes from 'prop-types';
import './Notes.css';
import shortid from 'shortid';
const formatTime = 'YYYY-MM-DD HH:mm:ss';
class Notes extends Component {
static propTypes = {
notes: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.string,
content: PropTypes.string
})).isRequired
};
constructor() {
super();
// We save the first date when the data is
// rendered at the beginning
this.state = {
lastUpdate: moment().format(formatTime).toString()
};
}
componentWillReceiveProps(nextProps) {
const { notes } = this.props;
// If the prop notes has changed...
if (nextProps.notes !== notes) {
this.setState({
lastUpdate: moment().format(formatTime).toString()
});
}
}
componentWillUnmount() {
document.body.style = 'background: black;';
document.getElementById('unmountMessage').style.color = 'white';
}
render() {
const { notes } = this.props;
const { lastUpdate } = this.state;
return (
<div className="Notes">
<h1>Notes:</h1>
<ul>
{notes.map((note) => (
<li key={shortid.generate()}>
{note.title}
{' '}
-
{' '}
{note.content}
</li>
))}
</ul>
<p>
Last Update:
<strong>{lastUpdate}</strong>
</p>
</div>
);
}
}
export default Notes;
<file_sep>import React, { Component } from 'react';
import { element } from 'prop-types';
import '../App.css';
import './Person/Popup.css';
import Popup from 'react-popup';
import Helmet from 'react-helmet';
import Header from '../shared/components/layout/Header';
import Footer from '../shared/components/layout/Footer';
import Content from '../shared/components/layout/Content';
// import Home from './Home/Home';
// import Todo from './Todo/Todo';
// import Timer from './Pomodoro/Timer';
// import Coins from './Coins/Coins';
// import Notes from './Notes/Notes';
// import Chart from './Chart/Chart';
// import Animation from './Animation/Animation';
// import Numbers from './Numbers/Numbers';
// import Xss from './Xss/Xss';
// import Calculator from './Calculator/Calculator';
// This is our fake data...
import { notes1, notes2 } from './Notes/data';
// import Person from './Person/Person';
class App extends Component {
static propTypes = {
children: element
};
constructor() {
super();
// The first time we load the notes1...
this.state = {
notes: notes1,
// chartType: 'line'
};
this.columns = [
['BTC', 3000, 6000, 10000, 15000, 13000, 11000],
['ETH', 2000, 3000, 5000, 4000, 3000, 940],
['XRP', 100, 200, 300, 500, 400, 300],
];
}
componentDidMount() {
const { notes } = this.state;
// After 10 seconds (10000 milliseconds) we concatenate our
// data with notes2...
setTimeout(() => {
this.setState({
notes: [...notes, ...notes2]
});
}, 10000);
}
// setBarChart = () => {
// this.setState({
// chartType: 'bar'
// });
// }
//
// setLineChart = () => {
// this.setState({
// chartType: 'line'
// });
// }
render() {
// const { chartType, notes } = this.state;
const { children } = this.props;
return (
<div className="App">
<Helmet
title="Person Information"
meta={[
{ name: 'title', content: 'Person Information' },
{ name: 'description', content: 'This recipe talks about React Helmet' }
]}
/>
<Header title="The new header title" />
<Content>
{children}
{/* <Person /> */}
{/* <Calculator /> */}
{/* <Xss /> */}
{/* <Numbers /> */}
{/* <Animation /> */}
{/* <Chart */}
{/* columns={this.columns} */}
{/* chartType={chartType} */}
{/* /> */}
{/* <p> */}
{/* Chart Type */}
{/* <button type="button" onClick={this.setBarChart}>Bar</button> */}
{/* <button type="button" onClick={this.setLineChart}>Line</button> */}
{/* </p> */}
{/* <Notes notes={notes} /> */}
{/* <Coins /> */}
{/* <Timer /> */}
{/* <Todo /> */}
{/* <Home /> */}
</Content>
<Footer />
<Popup />
</div>
);
}
}
export default App;
<file_sep>/* eslint react/jsx-filename-extension: "off" */
/* global window */
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { BrowserRouter as Router } from 'react-router-dom';
// Routes
import { Provider } from 'react-redux';
import AppRoutes from './routes';
import * as serviceWorker from './serviceWorker';
// Redux store
import configureStore from './shared/redux/configureStore';
// configure redux store
const store = configureStore(window.initialState);
const unmountButton = document.getElementById('unmount');
// Is not very common to remove a Component from the DOM,
// but this will be just to understand how
// componentWillUnmount works.
function unmount() {
ReactDOM.unmountComponentAtNode(
document.getElementById('root')
);
document.getElementById('unmountMessage')
.style.display = 'block';
unmountButton.remove();
}
unmountButton.addEventListener('click', unmount);
document.getElementById('unmountMessage')
.style.display = 'none';
ReactDOM.render(
<Provider store={store}>
<Router>
<AppRoutes />
</Router>
</Provider>,
document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
<file_sep>/**
* Creates new state from state and newState. NewState overwrites state properties.
* @param state
* @param newState
* @returns {*}
*/
export function getNewState(state, newState) {
return Object.assign({}, state, newState);
}
/**
* Check if data is empty or not when we try first time to render the component.
* @param items
* @returns {boolean}
*/
export function isFirstRender(items) {
return !items || items.length === 0 || Object.keys(items).length === 0;
}
| cc7d82864c97a8479bfd52c44a917d80dff9d47a | [
"JavaScript"
] | 5 | JavaScript | pagas/first-react-app | 9a11334bb15b6c0390f244857a3abdae15109c91 | f3cbd9c68706c4f49e76c89a929c8855f5f1ad1d |
refs/heads/master | <file_sep>//
// UsersTableViewCell.swift
// GitHubUsers
//
// Created by <NAME> on 2019/4/11.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class UsersTableViewCell: UITableViewCell {
@IBOutlet weak var imgvwAvatar: UIImageView!
@IBOutlet weak var lblName: UILabel!
@IBOutlet weak var lblDetailURL: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// HomeViewController.swift
// GitHubUsers
//
// Created by <NAME> on 2019/4/10.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import Moya
import Result
import RxSwift
import RxCocoa
import NSObject_Rx
import Kingfisher
import MJRefresh
import PKHUD
class HomeViewController: UIViewController {
var viewModel = HomeViewModel()
@IBOutlet weak var tableView: UITableView!
var searchController: UISearchController?
override func viewDidAppear(_ animated: Bool) {
if #available(iOS 11.0, *) {
navigationItem.hidesSearchBarWhenScrolling = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// build UI
self.automaticallyAdjustsScrollViewInsets = false
tableView.register(UINib(nibName: "UsersTableViewCell", bundle: nil), forCellReuseIdentifier: "UsersTableViewCell")
tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
HUD.show(.progress)
// page numbering is 1-based
self?.viewModel.page.accept(1)
})
tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { [weak self] in
if let pageIndex = self?.viewModel.page.value {
HUD.show(.progress)
self?.viewModel.page.accept(pageIndex + 1)
}
})
// search bar
if let searchUsersViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SearchUsersViewController") as? SearchUsersViewController {
searchController = UISearchController(searchResultsController: searchUsersViewController)
self.definesPresentationContext = true
if #available(iOS 11.0, *) {
navigationItem.searchController = searchController;
navigationItem.hidesSearchBarWhenScrolling = false
searchController?.searchBar.placeholder = "Search News"
} else {
tableView.tableHeaderView = searchController?.searchBar
}
searchController?.searchBar.rx.text.bind(to: searchUsersViewController.viewModel.keyWord).disposed(by: rx.disposeBag)
}
// bind viewModel and view
viewModel.result.subscribe(onNext: { [weak self] result in
HUD.hide()
self?.tableView.mj_header.endRefreshing()
self?.tableView.mj_footer.endRefreshing()
}).disposed(by: rx.disposeBag)
viewModel.users.bind(to: tableView.rx.items) { (tableView, row, user) in
if let cell = tableView.dequeueReusableCell(withIdentifier: "UsersTableViewCell") as? UsersTableViewCell {
cell.lblName.text = user.login
cell.lblDetailURL.text = user.html_url
cell.imgvwAvatar.kf.setImage(with: URL(string: user.avatar_url))
return cell
} else {
return UITableViewCell()
}
}.disposed(by: rx.disposeBag)
tableView.rx.modelSelected(User.self).subscribe(onNext: { user in
let detailViewController = DetailViewController()
detailViewController.strURL = user.html_url
self.navigationController?.pushViewController(detailViewController, animated: true)
}).disposed(by: rx.disposeBag)
//
viewModel.page.accept(1)
}
}
<file_sep>//
// DetailViewController.swift
// GitHubUsers
//
// Created by <NAME> on 2019/4/10.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import WebKit
import SnapKit
import PKHUD
class DetailViewController: UIViewController {
var strURL: String?
override func viewDidLoad() {
super.viewDidLoad()
HUD.show(.progress)
let webConfiguration = WKWebViewConfiguration()
let webView = WKWebView(frame: view.bounds, configuration: webConfiguration)
webView.navigationDelegate = self
if let strURL = self.strURL, let url = URL(string: strURL) {
webView.load(URLRequest(url: url))
}
view.addSubview(webView)
webView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
}
}
extension DetailViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
HUD.hide()
}
}
<file_sep>//
// HomeViewModel.swift
// GitHubUsers
//
// Created by <NAME> on 2019/4/10.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import RxSwift
import Moya
import Result
import RxCocoa
enum APIError: Error {
case JsonParseError(String)
case NetworkError(String)
}
class HomeViewModel {
var users = BehaviorRelay<[User]>(value: [])
var result = PublishSubject<Result<HomeResult,APIError>>()
var page = BehaviorRelay<Int>(value: 1)
var disposeBag = DisposeBag()
init() {
page.subscribe(onNext: { [weak self] pageIndex in
let provider = MoyaProvider<APIManager>()
_ = provider.rx.request(.SwiftUsers(pageIndex)).subscribe(onSuccess: { response in
do {
let decoder = JSONDecoder()
let homeResult = try decoder.decode(HomeResult.self, from: response.data)
if pageIndex == 1 {
self?.users.accept(homeResult.items)
} else {
if let users = self?.users.value {
self?.users.accept(users + homeResult.items)
}
}
self?.result.onNext(Result.success(homeResult))
} catch {
self?.result.onNext(Result.failure(.JsonParseError("json prase error")))
}
}, onError: { error in
self?.result.onNext(Result.failure(.JsonParseError("network error")))
})
}).disposed(by: disposeBag)
}
}
<file_sep>//
// GitHubUsersTests.swift
// GitHubUsersTests
//
// Created by <NAME> on 2019/4/10.
// Copyright © 2019 <NAME>. All rights reserved.
//
import XCTest
@testable import GitHubUsers
class GitHubUsersTests: XCTestCase {
var homeViewModel: HomeViewModel!
var searchUsersViewModel: SearchUsersViewModel!
override func setUp() {
homeViewModel = HomeViewModel()
searchUsersViewModel = SearchUsersViewModel()
}
func testSwiftUser() {
homeViewModel.page.accept(1)
_ = homeViewModel.result.subscribe(onNext: { result in
switch result {
case .success(let homeResult):
XCTAssertNil(homeResult)
case .failure(let error):
XCTFail(error.localizedDescription)
}
})
}
func testSearchUser() {
searchUsersViewModel.keyWord.onNext("oc")
_ = searchUsersViewModel.result.subscribe(onNext: { result in
switch result {
case .success(let homeResult):
XCTAssertNil(homeResult)
case .failure(let error):
XCTFail(error.localizedDescription)
}
})
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
}
<file_sep># Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
target 'GitHubUsers' do
use_frameworks!
pod 'RxSwift', '~> 4.0'
pod 'RxCocoa', '~> 4.0'
pod 'Kingfisher', '~> 4.9.0'
pod 'NSObject+Rx'
pod 'Moya/RxSwift', '~> 12.0'
pod 'SnapKit', '~> 4.2.0'
pod 'MJRefresh', '~> 3.1.16'
pod 'PKHUD'
target 'GitHubUsersTests' do
inherit! :search_paths
# Pods for testing
end
end
<file_sep>//
// SearchResultViewController.swift
// GitHubUsers
//
// Created by <NAME> on 2019/4/10.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import Moya
import Result
import RxSwift
import RxCocoa
import NSObject_Rx
import Kingfisher
import MJRefresh
import SnapKit
//tab
let navigationHeight = 64
class SearchUsersViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var viewModel = SearchUsersViewModel()
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
tableView.register(UINib(nibName: "UsersTableViewCell", bundle: nil), forCellReuseIdentifier: "UsersTableViewCell")
if #available(iOS 11,*) {
} else {
tableView.snp.updateConstraints { maker in
maker.top.equalToSuperview().offset(navigationHeight)
}
}
// bind viewModel and view
viewModel.users.bind(to: tableView.rx.items) { (tableView, row, user) in
if let cell = tableView.dequeueReusableCell(withIdentifier: "UsersTableViewCell") as? UsersTableViewCell {
cell.lblName.text = user.login
cell.lblDetailURL.text = user.html_url
cell.imgvwAvatar.kf.setImage(with: URL(string: user.avatar_url))
return cell
} else {
return UITableViewCell()
}
}.disposed(by: rx.disposeBag)
}
}
<file_sep>//
// SearchNewsViewModel.swift
// GitHubUsers
//
// Created by <NAME> on 2019/4/11.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import RxSwift
import Moya
import Result
import RxCocoa
class SearchUsersViewModel {
var keyWord = PublishSubject<String?>()
var users = BehaviorRelay<[User]>(value: [])
var result = PublishSubject<Result<HomeResult,APIError>>()
var disposBag = DisposeBag()
init() {
keyWord.map { text -> String in
if let keyWord = text {
return keyWord
} else {
return ""
}
}.filter { text -> Bool in
if text.isEmpty {
return false
}
return true
}.subscribe(onNext: { [weak self] text in
let provider = MoyaProvider<APIManager>()
_ = provider.rx.request(.SearchUsers(text)).subscribe(onSuccess: { response in
do {
let decoder = JSONDecoder()
let homeResult = try decoder.decode(HomeResult.self, from: response.data)
self?.users.accept(homeResult.items)
self?.result.onNext(Result.success(homeResult))
} catch {
self?.result.onNext(Result.failure(.JsonParseError("json prase error")))
}
}, onError: { error in
self?.result.onNext(Result.failure(.JsonParseError("network error")))
})
}).disposed(by: disposBag)
}
}
<file_sep>//
// NetworkService.swift
// GitHubUsers
//
// Created by <NAME> on 2019/4/10.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Moya
enum APIManager {
case SwiftUsers(Int)
case SearchUsers(String)
}
extension APIManager: TargetType {
var baseURL: URL {
return URL(string: "https://api.github.com")!
}
var path: String {
switch self {
case .SwiftUsers,.SearchUsers:
return "search/users"
}
}
var method: Method {
switch self {
case .SwiftUsers, .SearchUsers:
return .get
}
}
// for test
var sampleData: Data {
return "".data(using: String.Encoding.utf8)!
}
var task: Task {
switch self {
case .SwiftUsers(let page):
return .requestParameters(parameters: ["q":"swift","page":page], encoding: URLEncoding.default)
case .SearchUsers(let keyWord):
return .requestParameters(parameters: ["q":keyWord], encoding: URLEncoding.default)
}
}
var headers: [String : String]? {
return nil
}
}
<file_sep>//
// Model.swift
// GitHubUsers
//
// Created by <NAME> on 2019/4/10.
// Copyright © 2019 <NAME>. All rights reserved.
//
// home
struct HomeResult: Codable {
var total_count: Int
var items: [User]
}
struct User: Codable {
var login: String
var avatar_url: String
var html_url: String
}
| 4dedcb319ef25d3f25b32219de2febd3302c855f | [
"Swift",
"Ruby"
] | 10 | Swift | gaojian922188/test-mobile | 2cbb731051e8d9079b58b5b0b20aa90e17b24089 | ed34d926e6c2db7d585b67ed6df5bde98c616220 |
refs/heads/master | <repo_name>yudg1987/springboot-dubbo<file_sep>/boot-dubbo-api/src/main/java/com/boot/service/TestService.java
package com.boot.service;
import com.boot.domain.User;
import com.boot.bo.ToClickHouseBo;
import com.github.pagehelper.PageInfo;
public interface TestService {
String sayHello(String str);
User findUser();
ToClickHouseBo findRecord(Integer id);
int addRecord(ToClickHouseBo bo);
int deleteById(Integer id);
PageInfo<ToClickHouseBo> selectByByPage(ToClickHouseBo bo);
}
<file_sep>/boot-dubbo-provider/src/main/java/com/boot/task/WebTask.java
package com.boot.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class WebTask {
@Scheduled(cron = "0/5 * * * * ?")
public void doTask() {
System.out.println("我做任务了");
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.boot</groupId>
<artifactId>boot-dubbo</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 这里是我们子模块的设置 -->
<modules>
<module>boot-dubbo-api</module>
<module>boot-dubbo-provider</module>
<module>boot-dubbo-consumer</module>
</modules>
<!-- 在这里设置打包类型为pom,作用是为了实现多模块项目 -->
<packaging>pom</packaging>
<!-- 第一步:添加Springboot的parent -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<!-- 设置我们项目的一些版本属性 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<dubbo.version>2.5.5</dubbo.version>
<zkclient.version>3.4.8</zkclient.version>
<lombok.version>1.16.18</lombok.version>
<spring-boot.version>2.0.2.RELEASE</spring-boot.version>
<mysql-connector-java.version>8.0.11</mysql-connector-java.version>
</properties>
<!-- 声明一些项目依赖管理,方便我们的依赖版本管理 -->
<dependencyManagement>
<dependencies>
<!-- Springboot依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot.version}</version>
<exclusions>
<!--显示排除掉默认的日志起步依赖(Logback)-->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Springboot-web依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<!-- 使用lombok实现JavaBean的get、set、toString、hashCode、equals等方法的自动生成 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- Dubbo依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>${dubbo.version}</version>
</dependency>
<!-- zookeeper的客户端依赖 -->
<!--<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>${zkclient.version}</version>
</dependency>-->
<!--<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>-->
<!-- 引入mybatis支持-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<!-- 引入MySQL连接的依赖包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
</dependencyManagement>
</project><file_sep>/boot-dubbo-api/src/main/java/com/boot/base/ReqPageBO.java
package com.boot.base;
import lombok.Data;
@Data
public class ReqPageBO {
/** */
private static final long serialVersionUID = -7485827693286591127L;
/**
* 第几页
*/
private int pageNo = 0;
/**
* 每页的数量
*/
private int pageSize = 10;
private String sortName;
private String sortOrder;
}
<file_sep>/boot-dubbo-provider/src/main/java/com/boot/bo/ToClickHouse.java
package com.boot.bo;
import lombok.Data;
import java.util.Date;
@Data
public class ToClickHouse {
private Integer idColumn;
private Byte tinyintColumn;
private Byte tinyintUnsignedColumn;
private Short smallintColumn;
private Short smallintUnsignedColumn;
private Integer mediumintColumn;
private Integer mediumintUnsignedColumn;
private Integer intColumn;
private Integer intUnsignedColumn;
private Long bigintColumn;
private Long bigintUnsignedColumn;
private Double doubleColumn;
private Double doubleUnsignedColumn;
private Float floatColumn;
private Float floatUnsignedColumn;
private Long decimalColumn;
private Long decimalUnsignedColumn;
private String charColumn;
private String varcharColumn;
private Date dateColumn;
private Date timeColumn;
private Date yearColumn;
private Date timestampColumn;
private Date datetimeColumn;
private String tinytextColumn;
private String enumColumn;
private Boolean bitColumn;
}<file_sep>/boot-dubbo-provider/src/main/java/com/boot/page/MyBatisConfiguration.java
package com.boot.page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* yudg
*/
@Configuration
public class MyBatisConfiguration {
private static final Logger logger = LoggerFactory.getLogger(MyBatisConfiguration.class);
@Bean
public PageHelper geHelper() {
logger.info("注册mybatis分页插件");
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("offsetAsPageNum", "true");
properties.setProperty("rowBoundsWithCount", "true");
properties.setProperty("reasonable", "true");
pageHelper.setProperties(properties);
return pageHelper;
}
}
<file_sep>/boot-dubbo-api/src/main/java/com/boot/cache/CacheService.java
package com.boot.cache;
import java.util.Map;
import java.util.Set;
/** <br>
* 标题: 通用缓存接口<br>
* 描述: 提供基本的get、set、delete方法<br>
* 公司: www.tydic.com<br>
*
* @autho liuce
* @time 2016-7-18 下午1:06:30 */
public interface CacheService {
/** 往缓存中存放值(永不过期)<br>
* 适用场景: 需要常驻缓存中的数据<br>
* 调用方式: <br>
* 业务逻辑说明<br>
*
* @param key
* @param value
* @return
* @autho liuce
* @time 2016-7-18 下午1:21:38 */
public void put(String key, Object value);
/** 往缓存中存放值(一段时间内有效)<br>
* 适用场景: 需要常驻缓存中的数据<br>
* 调用方式: <br>
* 业务逻辑说明<br>
*
* @param key
* @param value
* @param expire
* 失效时间,0表示用不失效
* @return
* @autho liuce
* @time 2016-7-18 下午1:21:38 */
public void put(String key, Object value, int expire);
/** 从缓存中获取值<br>
* 适用场景: <br>
* 调用方式: <br>
* 业务逻辑说明<br>
*
* @param key
* @return
* @autho liuce
* @time 2016-7-18 下午1:22:59 */
public Object get(String key);
/** 从缓存中获取指定类型的结果<br>
* 适用场景: <br>
* 调用方式: <br>
* 业务逻辑说明<br>
*
* @param key
* @param requiredType
* @return
* @autho liuce
* @time 2016年9月9日 下午3:15:49 */
public <T> T get(String key, Class<T> requiredType);
/** 从缓存中删除指定的key<br>
* 适用场景: <br>
* 调用方式: <br>
* 业务逻辑说明<br>
*
* @param key
* @autho liuce
* @time 2016-7-18 下午1:23:43 */
public void delete(String key);
/** 穿透查询<br>
* 适用场景: <br>
* 调用方式: 同步HSF方式调用<br>
* 业务逻辑说明<br>
* 做穿透查询,缓存中查询不到的数据通过本地查询执行器回调改执行器得到数据,最后放入缓存
*
* @param <T>
* @param executer
* 本地查询执行器
* @param key
* 支持多个参数,以多个String参数连接作为key
* @return
* @autho liuce
* @time 2016-7-27 下午1:55:13 */
public <T> T getFinal(CacheExecuterService<T> executer, String... key);
/** 根据表达式获取前缀一样的Key集合<br>
* 适用场景: <br>
* 调用方式: <br>
* 业务逻辑说明<br>
*
* @param pattern
* @return
* @autho liuce
* @time 2016年9月25日 下午3:11:59 */
public Set<String> getkeys(String pattern);
/** 获取key的失效时间<br>
* 适用场景: <br>
* 调用方式: <br>
* 业务逻辑说明<br>
*
* @param key
* @return
* @autho liuce
* @time 2016年11月9日 上午12:10:41 */
public Long getExpireTimeByKey(String key);
/** <br>
* 适用场景: 获取组合服务响应码<br>
* 调用方式: <br>
* 业务逻辑说明<br>
*
* @param executer
* @param key
* @return
* @autho QIJIANFEI
* @time 2017年8月4日 下午8:52:35 */
Map<String, String> getOuterCodeByKey(CacheExecuterService<Map<String, String>> executer, String... key);
/** <br>
* 适用场景:获取业务服务响应码 <br>
* 调用方式: <br>
* 业务逻辑说明<br>
*
* @param executer
* @param key
* @return
* @autho QIJIANFEI
* @time 2017年8月4日 下午8:52:59 */
Map<String, String> getInnerCodeByKey(CacheExecuterService<Map<String, String>> executer, String... key);
}
<file_sep>/boot-dubbo-provider/src/main/java/com/boot/mapper/ToClickHouseMapper.java
package com.boot.mapper;
import com.boot.bo.ToClickHouseBo;
import com.boot.bo.ToClickHouseWithBLOBs;
import java.util.List;
public interface ToClickHouseMapper {
int deleteByPrimaryKey(Integer idColumn);
int insert(ToClickHouseWithBLOBs record);
int insertSelective(ToClickHouseWithBLOBs record);
ToClickHouseWithBLOBs selectByPrimaryKey(Integer idColumn);
int updateByPrimaryKeySelective(ToClickHouseWithBLOBs record);
int updateByPrimaryKeyWithBLOBs(ToClickHouseWithBLOBs record);
int updateByPrimaryKey(ToClickHouseBo record);
List<ToClickHouseWithBLOBs> selectByListByPage(ToClickHouseWithBLOBs toClickHouseWithBLOBs);
} | 3580311af79c0d198a4426e998fe61699fd14073 | [
"Java",
"Maven POM"
] | 8 | Java | yudg1987/springboot-dubbo | 743eb6b2d3cdeb7bc4771d06859694174a4969e3 | 46cc2abb3d4b5795994c35ec284ca8376ea13af0 |
refs/heads/master | <file_sep><?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>a.add_credit_card_info</name>
<tag></tag>
<isRerun>false</isRerun>
<lastRun>2018-05-23T14:51:56</lastRun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<testSuiteGuid>f5c56dfd-b5d0-44c8-9004-4c7567c024ce</testSuiteGuid>
<testCaseLink>
<guid>fe2221db-8b7b-404e-b780-023f2e48b8f4</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/access_merchant_login_URL</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>50eafaa2-5d04-4013-8811-8dd7197a6efb</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/login</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>49fcdc80-8574-4d9f-95f6-cc8f86d98fd1</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>aa839031-b432-4670-b3de-b6af569f048f</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>c889c884-2f8b-4e63-94f9-500f30ed6a95</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Module Access/Account</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>ed83fd62-a698-4fd7-98fe-d5c56b3875f7</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Account/Payment Details/Payment Details Modules/add_credit_card</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>c269ab18-ccd8-4545-a9c6-b635a3e416d9</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>379a8229-3f69-41a6-816d-4f3f7ffda18b</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>f5adc968-6fa4-4dac-90ba-cf958163d1f8</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>9a40f559-5213-45d6-9038-4280608e88d0</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>8e84ad83-0261-4032-8065-024957b61803</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>42dae4fb-b252-44fe-8ad3-004c03ee905c</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/logout</testCaseId>
</testCaseLink>
</TestSuiteEntity>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>TS001 verify all case</name>
<tag></tag>
<isRerun>false</isRerun>
<lastRun>2018-06-26T16:58:13</lastRun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<testSuiteGuid>574ecd24-ac48-401f-b66d-137c73ca22ff</testSuiteGuid>
<testCaseLink>
<guid>05e617a7-42ca-4605-b84f-8ecb15bfaebd</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/TC001 Login - verify all case</testCaseId>
<testDataLink>
<combinationType>ONE</combinationType>
<id>7f02414d-74ef-4a93-9330-1b3ac84a9b85</id>
<iterationEntity>
<iterationType>ALL</iterationType>
<value></value>
</iterationEntity>
<testDataId>Data Files/Merchant/Login/DF001 - Username_Password</testDataId>
</testDataLink>
<variableLink>
<testDataLinkId>7f02414d-74ef-4a93-9330-1b3ac84a9b85</testDataLinkId>
<type>DATA_COLUMN</type>
<value>username</value>
<variableId>19779c58-c925-46ac-a11b-aa8fb1e376c7</variableId>
</variableLink>
<variableLink>
<testDataLinkId>7f02414d-74ef-4a93-9330-1b3ac84a9b85</testDataLinkId>
<type>DATA_COLUMN</type>
<value>password</value>
<variableId>72a8bdde-4721-4019-b177-39febaad3a74</variableId>
</variableLink>
<variableLink>
<testDataLinkId>7f02414d-74ef-4a93-9330-1b3ac84a9b85</testDataLinkId>
<type>DATA_COLUMN</type>
<value>expectedresult</value>
<variableId>b0ac40ce-7485-43ab-b50b-77a3671c57a4</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>e6ff24a5-6c4e-416e-a3ab-8ef25c718782</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>82aa0433-e10b-4c5d-93a8-f82fb86540cb</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/close browser</testCaseId>
</testCaseLink>
</TestSuiteEntity>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>c.add_remove_credit_card_Info</name>
<tag></tag>
<isRerun>false</isRerun>
<lastRun>2018-05-22T22:56:22</lastRun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<testSuiteGuid>6649dd4c-2cfc-4412-bc9d-1fecafc8717e</testSuiteGuid>
<testCaseLink>
<guid>fc73a5b0-2665-484f-93ca-dcf8f71ae72f</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/access_merchant_login_URL</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>829de198-35ce-4b33-9bba-20a19ff23b28</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/login</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>49fcdc80-8574-4d9f-95f6-cc8f86d98fd1</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>aa839031-b432-4670-b3de-b6af569f048f</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>05af7d16-db31-48d2-b9bf-77abf2806e7a</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Module Access/Account</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>0dc2a3bc-3962-4c0d-86f9-3b67342c2a7e</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Account/Payment Details/Payment Details Modules/add_credit_card</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>c269ab18-ccd8-4545-a9c6-b635a3e416d9</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>379a8229-3f69-41a6-816d-4f3f7ffda18b</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>f5adc968-6fa4-4dac-90ba-cf958163d1f8</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>9a40f559-5213-45d6-9038-4280608e88d0</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>8e84ad83-0261-4032-8065-024957b61803</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>79caecd9-f17b-430c-8b71-2b9bf37f2f64</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Account/Payment Details/Payment Details Modules/remove_credit_card</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>62374010-ce23-43fa-9dec-c3105cbd011d</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/logout</testCaseId>
</testCaseLink>
</TestSuiteEntity>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>subscribe_package_paid</name>
<tag></tag>
<isRerun>false</isRerun>
<lastRun>2018-05-30T18:06:10</lastRun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<testSuiteGuid>f3fa5f37-721d-4483-8f19-de4f607db37a</testSuiteGuid>
<testCaseLink>
<guid>a1fc4e76-74e5-40e6-869d-e166880177ac</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Sign Up/Package Subscribe/Module Access/package_home_URL</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>3e82fe35-54b0-4140-a0d9-f62eb4325e1f</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Sign Up/Package Subscribe/Module Access/subscribe_pacakage_paid</testCaseId>
</testCaseLink>
</TestSuiteEntity>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>b.remove_credit_card_info</name>
<tag></tag>
<isRerun>false</isRerun>
<lastRun>2018-05-23T14:51:03</lastRun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<testSuiteGuid>1faf3066-336f-46bb-826b-55dc874299a3</testSuiteGuid>
<testCaseLink>
<guid>9904497d-33cb-4f53-be1c-9e203a23e1a4</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/access_merchant_login_URL</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>cb5f6329-4437-477e-94e7-817a0f2b48bc</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/login</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>49fcdc80-8574-4d9f-95f6-cc8f86d98fd1</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>aa839031-b432-4670-b3de-b6af569f048f</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>5fc0f716-fa79-4762-a5d3-b68f62600993</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Module Access/Account</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>a777dbb8-4150-43db-bc9e-72d91053fa28</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Account/Payment Details/Payment Details Modules/remove_credit_card</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>14fb9fc9-1f48-4e8c-9b68-bb6e073a6ed2</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/logout</testCaseId>
</testCaseLink>
</TestSuiteEntity>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>subscribe_package_free</name>
<tag></tag>
<isRerun>false</isRerun>
<lastRun>2018-05-30T18:04:35</lastRun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<testSuiteGuid>2d75fba2-8d33-400f-bb0a-863b0d8aae2d</testSuiteGuid>
<testCaseLink>
<guid>c1ef1101-f044-478e-8a92-baa4793eceb9</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Sign Up/Package Subscribe/Module Access/package_home_URL</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>63b41b0c-5315-4a77-b7ea-d582d9a772c4</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Sign Up/Package Subscribe/Module Access/subscribe_package_free</testCaseId>
</testCaseLink>
</TestSuiteEntity>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>package_unsubscribe</name>
<tag></tag>
<isRerun>false</isRerun>
<lastRun>2018-05-14T18:06:23</lastRun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<testSuiteGuid>b3d221a7-2d95-4c53-9198-45d9739e8625</testSuiteGuid>
<testCaseLink>
<guid>b73c044d-4379-4a71-9450-665e629cea19</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/access_merchant_login_URL</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>0607e3b5-1b61-4f02-b661-6904d7010194</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/login</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>49fcdc80-8574-4d9f-95f6-cc8f86d98fd1</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>aa839031-b432-4670-b3de-b6af569f048f</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>b3939aec-6f67-4ecd-be96-fdca998ed137</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Module Access/Account</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>ae3d9a73-a271-4947-a371-40a614c629e6</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Account/Package Unsubscribe/unsubscribe_paid_package</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>593c318a-7225-4d5f-b327-96fe6638f13c</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/logout</testCaseId>
</testCaseLink>
</TestSuiteEntity>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>TS002 Edit Campaign with negative testing</name>
<tag></tag>
<isRerun>false</isRerun>
<lastRun>2018-07-24T14:57:48</lastRun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<testSuiteGuid>a0e70a14-b568-4e35-a87c-ab97e25b12af</testSuiteGuid>
<testCaseLink>
<guid>28ea2bd7-cefa-4c4a-b436-3ec9f36dad7b</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/login</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>49fcdc80-8574-4d9f-95f6-cc8f86d98fd1</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>aa839031-b432-4670-b3de-b6af569f048f</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>64b61406-d5b5-4a3b-99dd-0886895db499</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Campaign/TC001 Campaign - verify all case</testCaseId>
<testDataLink>
<combinationType>ONE</combinationType>
<id>742e2cba-c95f-4f6b-87a5-8dd871212bc3</id>
<iterationEntity>
<iterationType>ALL</iterationType>
<value></value>
</iterationEntity>
<testDataId>Data Files/Merchant/Campaign/DF002 - Edit Campaign</testDataId>
</testDataLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>5c3602e2-1da3-4027-8428-662f2c24817c</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>companyName</value>
<variableId>ea91b2c0-932c-496b-b763-d373f9e35bc1</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>campaignInstruc</value>
<variableId>b1f0779c-28df-4819-94f1-8fe84b40168b</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>radioEmail</value>
<variableId>5a3ce14d-561d-4455-ac52-786733b0dbff</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>radioMobileno</value>
<variableId>b81f89d2-04aa-41dd-8a0c-9baaced5ab76</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>radioName</value>
<variableId>61937bd3-3c55-499e-b03c-8a52a8d709d7</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>radioGender</value>
<variableId>399dd5ea-f7f6-4434-8d2e-2e81d3bd0b4a</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>radioDOB</value>
<variableId>58b08ea9-8d06-496a-ab84-8481aaea327f</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>campaignImage</value>
<variableId>9aa7908a-89ae-4a9e-a6f3-20bd0ce37ee5</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>tcURL</value>
<variableId>d4361a6a-9b80-4381-a192-46db8eab9d1f</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>emailSender</value>
<variableId>a44e77a2-830a-44b6-9e09-f2fc18dfadcb</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>emailSubject</value>
<variableId>d4fc5625-8f94-428d-aa8f-1bd33a351f3b</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>emailContent</value>
<variableId>39eb6231-d40e-4275-b3b5-8d493b463add</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>companyLogo</value>
<variableId>e8b9d8c9-ae04-4fed-9050-6eefd32db4d9</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>7d8f78f5-557a-4a3a-8545-e3e40d843d69</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>c9ed8c3e-deb9-4884-883f-89902ef3a46a</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>469b1905-783b-4dc3-865f-373e62fb3854</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>390360ea-2f80-4db2-a1f5-e0be8c15e3dc</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>6df0b4eb-cc53-4df6-b544-95b875f13fad</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>69d4cedd-46b6-4fce-86b4-e02b6d815827</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>fedca9ea-8d5e-488f-976b-2ae3d5643300</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>1bc9c1aa-0fc4-48a3-b3bc-89247ea7e825</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>e93ba66d-2571-4a14-95f4-c343ed79664d</variableId>
</variableLink>
<variableLink>
<testDataLinkId>742e2cba-c95f-4f6b-87a5-8dd871212bc3</testDataLinkId>
<type>DATA_COLUMN</type>
<value>expectedResult</value>
<variableId>4bc9b59a-42b2-49df-9ba7-68a1ed9835c1</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>a0846d71-89e6-4b88-aafc-d58bc58c798d</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/logout</testCaseId>
</testCaseLink>
</TestSuiteEntity>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>package_upgrade_free_to_pay</name>
<tag></tag>
<isRerun>false</isRerun>
<lastRun>2018-05-15T10:31:38</lastRun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<testSuiteGuid>fa0af70a-c937-42d4-966c-4f0ede665317</testSuiteGuid>
<testCaseLink>
<guid>9a751f9e-6ade-4851-9dd6-97f0660d4e5a</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/access_merchant_login_URL</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>f383fd99-c357-4d25-a0a8-8636ada438a5</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/login</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>49fcdc80-8574-4d9f-95f6-cc8f86d98fd1</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>aa839031-b432-4670-b3de-b6af569f048f</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>733e0567-55a6-4227-bbb1-2b374ac149eb</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Module Access/Account</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>e7c578b8-9939-4c0f-932c-77052539d2a4</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Account/Package Upgrade/upgrade_free_to_pay</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>5f812c46-795c-47d6-934b-ec5d9b9e9d0a</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/logout</testCaseId>
</testCaseLink>
</TestSuiteEntity>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>TS002 logout</name>
<tag></tag>
<isRerun>false</isRerun>
<lastRun>2018-05-18T11:53:40</lastRun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<testSuiteGuid>d8185d11-99fa-4654-829c-0b0915664248</testSuiteGuid>
<testCaseLink>
<guid>3b25a05a-1084-4263-aa3f-0004dbee567a</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/TC001 Login - verify all case</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>19779c58-c925-46ac-a11b-aa8fb1e376c7</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>72a8bdde-4721-4019-b177-39febaad3a74</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>b0ac40ce-7485-43ab-b50b-77a3671c57a4</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>e6ff24a5-6c4e-416e-a3ab-8ef25c718782</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>b5be9c07-4347-4ce7-b3f0-98bf00342257</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/logout</testCaseId>
</testCaseLink>
</TestSuiteEntity>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<TestSuiteEntity>
<description></description>
<name>package_upgrade_no_package</name>
<tag></tag>
<isRerun>false</isRerun>
<lastRun>2018-05-15T10:22:28</lastRun>
<mailRecipient></mailRecipient>
<numberOfRerun>0</numberOfRerun>
<pageLoadTimeout>30</pageLoadTimeout>
<pageLoadTimeoutDefault>true</pageLoadTimeoutDefault>
<rerunFailedTestCasesOnly>false</rerunFailedTestCasesOnly>
<testSuiteGuid>2150e4af-5800-4d41-be50-7b17c0744a45</testSuiteGuid>
<testCaseLink>
<guid>3e728e1d-be37-42f3-8ed4-55958128fbbc</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/access_merchant_login_URL</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>13600aa7-dca3-43d1-a52a-6a4a9a062c41</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/login</testCaseId>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>49fcdc80-8574-4d9f-95f6-cc8f86d98fd1</variableId>
</variableLink>
<variableLink>
<testDataLinkId></testDataLinkId>
<type>DEFAULT</type>
<value></value>
<variableId>aa839031-b432-4670-b3de-b6af569f048f</variableId>
</variableLink>
</testCaseLink>
<testCaseLink>
<guid>0ee3b8e2-dfc0-44bf-8789-247ef760ebc0</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Module Access/Account</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>bf169d84-b444-47bc-b775-62ae3ad1ac13</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Account/Package Upgrade/upgrade_with_no_package</testCaseId>
</testCaseLink>
<testCaseLink>
<guid>6ddc2759-47ed-4c74-95bf-1276fa2926cb</guid>
<isReuseDriver>false</isReuseDriver>
<isRun>true</isRun>
<testCaseId>Test Cases/Merchant Portal/Login_Logout/Login Modules/logout</testCaseId>
</testCaseLink>
</TestSuiteEntity>
| 880e7f8023870b7d3653241b427725ae3360c56a | [
"TypeScript"
] | 11 | TypeScript | alanchan-kl/BOLD.Reward | fbb796ec965ed475b5d1f509274474a347d02cdd | fd165762904a2efaf0474286792706867f034b2a |
refs/heads/master | <file_sep>package com.klayzz.designpattern.structure.proxy.staticproxy;
import com.klayzz.designpattern.structure.proxy.staticproxy.controller.UserController;
import com.klayzz.designpattern.structure.proxy.staticproxy.entity.RequestInfo;
import com.klayzz.designpattern.structure.proxy.staticproxy.entity.UserVo;
import com.klayzz.designpattern.structure.proxy.staticproxy.service.MetricsCollector;
public class UserControllerProxy1 extends UserController {
private MetricsCollector metricsCollector;
public UserControllerProxy1() {
this.metricsCollector = new MetricsCollector();
}
public UserVo login(String telephone, String password) {
long startTimestamp = System.currentTimeMillis();
UserVo userVo = super.login(telephone, password);
long endTimeStamp = System.currentTimeMillis();
long responseTime = endTimeStamp - startTimestamp;
RequestInfo requestInfo = new RequestInfo("login", responseTime, startTimestamp);
metricsCollector.recordRequest(requestInfo);
return userVo;
}
public UserVo register(String telephone, String password) {
long startTimestamp = System.currentTimeMillis();
UserVo userVo = super.register(telephone, password);
long endTimeStamp = System.currentTimeMillis();
long responseTime = endTimeStamp - startTimestamp;
RequestInfo requestInfo = new RequestInfo("register", responseTime, startTimestamp);
metricsCollector.recordRequest(requestInfo);
return userVo;
}
}<file_sep>## 建造者模式
### 设计意图
创建复杂对象
### 实现原理
通过设置不同的可选参数,定制化的创建不同的对象,原理较为简单
### 应用场景
当创建对象有很多成员变量,通过new的方式的话会导致参数列表过长,
影响可读性,虽然我们通过set()方法来解决
但是
1. 如果类中的属性之间 有一定的依赖关系或者约束条件
2. 或者我们希望创建的对象是不可变对象,不允许暴露set方法
<file_sep>package com.klayzz.designpattern.creation.fatory.factorymethod.factory;
import com.klayzz.designpattern.creation.fatory.simplefactory.parser.IRuleConfigParser;
/**
* 定义一个工厂接口
* 新增新的工厂类只需要实现该接口即可,更加符合开闭原则
*/
public interface IRuleConfigParserFactory {
IRuleConfigParser createParser();
}
<file_sep>package com.klayzz.designpattern.behavior.observer.eventbus.service;
public interface NotificationService {
void sendInboxMessage(Long userId, String message);
}
<file_sep>package com.klayzz.designpattern.structure.adapter.example.example3.a;
// 外部系统A
public interface IA {
//...
void fa();
}
<file_sep>package com.klayzz.designpattern.behavior.strategy.annotation;
import lombok.Data;
/**
* @Author pengyu
* @Date 2020/9/22 9:16
*/
@Data
public class SortAlgType {
public static final int QuickSort = 1;
public static final int ExternalSort = 2;
public static final int ConcurrentExternalSort = 3;
public static final int MapReduceSort = 4;
}
<file_sep>package com.klayzz.designpattern.creation.fatory.simplefactory.parser.impl;
import com.klayzz.designpattern.creation.fatory.simplefactory.parser.IRuleConfigParser;
import com.klayzz.designpattern.creation.fatory.simplefactory.config.RuleConfig;
public class PropertiesRuleConfigParser implements IRuleConfigParser {
@Override
public RuleConfig parse(String configText) {
return null;
}
}
<file_sep>
##代理模式
### 设计意图
在不改变原始类的情况下,为原始类生成定义一个代理类,主要是为了控制访问
提高可扩展性
### 实现原理
一般情况下,我们让代理类和原始类实现同样的接口,或者让代理类继承原始类的方法来实现
代理模式有两种,分别是静态代理和动态代理
静态代理,我们每次为一个类新增代理,都要手写一边,并且每个代理类的代码有点像模板
模式的重复代理,增加了维护成本和开发成本
动态代理,对于静态代理存在的问题,我们可以通过动态代理来解决。
我们不事先为每个原始类编写代理类,而是在运行时,动态的生成代理类,然后在系统中用代理类替换掉原始类。
在java中,很好的支持了代理模式,关键类是Proxy,invocationHandler。
### 应用场景
代理模式常用在业务系统中开发一些非功能性需求,
比如:监控、统计、鉴权、限流、事务、幂等、日志。
我们将这些附加功能与业务功能解耦,放到代理类统一处理,
让程序员只需要关注业务方面的开发。除此之外,代理模式还可以用在
RPC、缓存等应用场景中。
<file_sep>package com.klayzz.designpattern.creation.fatory.simplefactory;
import com.klayzz.designpattern.creation.fatory.simplefactory.parser.*;
import com.klayzz.designpattern.creation.fatory.simplefactory.parser.impl.JsonRuleConfigParser;
import com.klayzz.designpattern.creation.fatory.simplefactory.parser.impl.PropertiesRuleConfigParser;
import com.klayzz.designpattern.creation.fatory.simplefactory.parser.impl.XmlRuleConfigParser;
import com.klayzz.designpattern.creation.fatory.simplefactory.parser.impl.YamlRuleConfigParser;
/**
* 把一推的if-else放到工厂类中,每次调用都要创建一个新的parser对象
*/
public class RuleConfigParserFactory {
public static IRuleConfigParser createParser(String configFormat) {
IRuleConfigParser parser = null;
if ("json".equalsIgnoreCase(configFormat)) {
parser = new JsonRuleConfigParser();
} else if ("xml".equalsIgnoreCase(configFormat)) {
parser = new XmlRuleConfigParser();
} else if ("yaml".equalsIgnoreCase(configFormat)) {
parser = new YamlRuleConfigParser();
} else if ("properties".equalsIgnoreCase(configFormat)) {
parser = new PropertiesRuleConfigParser();
}
return parser;
}
}
<file_sep>package com.klayzz.designpattern.structure.proxy.staticproxy.controller;
import com.klayzz.designpattern.structure.proxy.staticproxy.entity.UserVo;
import com.klayzz.designpattern.structure.proxy.staticproxy.service.MetricsCollector;
public class UserController implements IUserController{
//...省略其他属性和方法...
private MetricsCollector metricsCollector; // 依赖注入
public UserVo login(String telephone, String password) {
//...省略login逻辑...
//请求记录
metricsCollector.recordRequest(null);
return new UserVo();
}
public UserVo register(String telephone, String password) {
//...省略register逻辑...
//请求记录
metricsCollector.recordRequest(null);
return new UserVo();
}
}
<file_sep>package com.klayzz.designpattern.behavior.observer.skeleton;
public class Message {
}
<file_sep>package com.klayzz.designpattern.behavior.templatemethod.callback;
public class BClass {
//发现也能起到代码复用以及扩展的效果
//类似与模板方法
public void process(ICallback callback) {
//...
callback.methodToCallback();
//...
}
}
<file_sep>package com.klayzz.designpattern.structure.adapter.example.example3;
import com.klayzz.designpattern.structure.adapter.example.example3.a.IA;
// 在我们的项目中,外部系统A的使用示例
public class ADemo {
private IA a;
public ADemo(IA a) {
this.a = a;
}
//...
}<file_sep>package com.klayzz.designpattern.structure.adapter.example.example3.b;
// 外部系统A
public interface IB {
//...
void fb();
}
<file_sep>package com.klayzz.designpattern.behavior.strategy.annotation.factory;
import com.klayzz.designpattern.behavior.strategy.annotation.SortAlg;
import com.klayzz.designpattern.behavior.strategy.annotation.sortalg.ISortAlg;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.HashMap;
import java.util.Map;
public class SortAlgFactory implements ApplicationContextAware {
private static final Map<Integer, ISortAlg> algs = new HashMap<>();
public static ISortAlg getSortAlg(Integer type) {
if (type == null) {
throw new IllegalArgumentException("type should not be empty.");
}
return algs.get(type);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//获取所有策略注解的Bean
Map<String, Object> sorterStrategyMap = applicationContext.getBeansWithAnnotation(SortAlg.class);
sorterStrategyMap.forEach((k,v)->{
//获取策略实现类
Class<ISortAlg> sorterStrategyClass = (Class<ISortAlg>) v.getClass();
//获取策略实现类的注解值。
int type = sorterStrategyClass.getAnnotation(SortAlg.class).value();
algs.put(type,applicationContext.getBean(sorterStrategyClass));
});
}
}
<file_sep>package com.klayzz.designpattern.behavior.templatemethod.skeleton;
/**
* 经典模板方法骨架测试用例
*/
public class app {
public static void main(String[] args) {
AbstractClass demo = new ConcreteClass1();
demo.templateMethod();
System.out.println("-----------------------");
AbstractClass demo1 = new ConcreteClass2();
demo1.templateMethod();
}
}
<file_sep>package com.klayzz.designpattern.structure.adapter.example.example1;
//这个类来自外部sdk,我们无权修改它的代码
public class CD {
public static void staticFunction1() {
//...
System.out.println("CD 原始静态方法。。");
}
public void uglyNamingFunction2() {
//...
System.out.println("CD 原始的丑陋的命名方法。。");
}
public void tooManyParamsFunction3(int paramA, int paramB) {
//...
System.out.println("CD 原始的多参数方法");
}
public void lowPerformanceFunction4() {
//...
System.out.println("CD 原始的低性能方法");
}
}<file_sep>
##动态代理原理
Proxy.newProxyInstance()创建代理对象
进入这个方法,主要是这三个方法
* Class<?> cl = getProxyClass0() 生成动态代理类字节码文件,并加载
* Constructor<?> cons = cl.getConstructor();
* cons.newInstance(); //反射生成代理对象
其中最为重要的是getProxyClass0()方法,缓存存在直接缓存获取,
不存在则创建,在这方法里面
* Object subKey = subKeyFactory.apply();
* Factory factory = new Factory(subKey);
* factory.get()--> valueFactory.apply(key, parameter)这个方法生成字节码文件
再继续点进去,最终是
* byte[] proxyClassFile = ProxyGenerator.generateProxyClass();
生成代理类对象
* 往下是defineClass0();加载返回
网上找到的一个生成的字节码文件,反编译后得到的文件
$Proxy11
结合着看啥都懂了/。。。。
<file_sep>package com.klayzz.designpattern.structure.adapter.example.example1;
import com.klayzz.designpattern.structure.adapter.example.example1.model.ParamsWrapperDefinition;
// 注意:适配器类的命名不一定非得末尾带Adaptor
public class CDAdaptor extends CD implements ITarget {
//...
public void function1() {
super.staticFunction1();
}
public void function2() {
super.uglyNamingFunction2();
}
public void function3(ParamsWrapperDefinition paramsWrapper) {
super.tooManyParamsFunction3(paramsWrapper.getParamA(), paramsWrapper.getParamB());
}
public void function4() {
//...reimplement it...
System.out.println("适配后的高性能方法");
}
}
<file_sep>package com.klayzz.designpattern.structure.adapter.example.example2.outfilter;
// A敏感词过滤系统提供的接口
public class ASensitiveWordsFilter {
//text是原始文本,函数输出用***替换敏感词之后的文本
public String filterSexyWords(String text) {
// ...
return text;
}
public String filterPoliticalWords(String text) {
// ...
return text;
}
}
<file_sep>package com.klayzz.designpattern.behavior.strategy.annotation.sortalg;
import com.klayzz.designpattern.behavior.strategy.annotation.SortAlg;
import com.klayzz.designpattern.behavior.strategy.annotation.SortAlgType;
import org.springframework.stereotype.Component;
@Component
@SortAlg(SortAlgType.QuickSort)
public class QuickSort implements ISortAlg {
@Override
public void sort(String filePath) {
}
}
<file_sep>
## 策略模式
### 设计意图
解耦策略的定义,创建和使用
控制代码的复杂度,让每个部分都不至于过于复杂、代码量过多
### 定义
策略模式定义一族算法类,将每个算法分别封装起来,让它们可以互相替换
### 应用场景
利用它来避免冗长的 if-else 或 switch 分支判断
另外,尽管利用了策略模式,对于添加新的策略类,还是需要在工厂类中修改代码
稍微违反了开闭原则
但是我们是可以接受的
如果想要真正的满足开闭原则,可以使用配置文件启动加载或者自定义注解
<file_sep>package com.klayzz.designpattern.behavior.observer.eventbus.observer;
import com.google.common.eventbus.Subscribe;
import com.klayzz.designpattern.behavior.observer.eventbus.service.PromotionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RegPromotionObserver {
@Autowired
private PromotionService promotionService; // 依赖注入
@Subscribe
public void handleRegSuccess(Long userId) throws InterruptedException {
Thread.currentThread().sleep(3*1000);
promotionService.issueNewUserExperienceCash(userId);
}
}
<file_sep>package com.klayzz.designpattern.behavior.observer.skeleton;
public interface Observer {
void update(Message message);
}
<file_sep>
## 装饰器模式
### 设计意图
解决继承关系过于复杂问题,
### 实现模式
通过组合来替换继承,给原始类添加功能。
除此之外,装饰器模式还有一个特点,
那就是可以对原始类嵌套使用多个装饰器。
为了满足这样的需求,在设计的时候,装饰器类需要跟原始类继承相同的抽象类或者接口。
### 应用场景
JDK的IO
<file_sep>package com.klayzz.designpattern.behavior.templatemethod.callback;
/**
* 回调
*/
public interface ICallback {
void methodToCallback();
}
<file_sep>package com.klayzz.designpattern.behavior.observer.eventbus.service;
public interface UserService {
long register(String telephone, String password);
}
<file_sep>package com.klayzz.designpattern.structure.adapter.classadapter;
public class Adaptor extends Adaptee implements ITarget {
public void f1() {
super.fa();
}
public void f2() {
//...重新实现f2()...
}
// 这里fc()不需要实现,直接继承自Adaptee,这是跟对象适配器最大的不同点}
}
<file_sep>package com.klayzz.designpattern.structure.adapter.example.example2.adapter.impl;
import com.klayzz.designpattern.structure.adapter.example.example2.adapter.ISensitiveWordsFilter;
import com.klayzz.designpattern.structure.adapter.example.example2.outfilter.ASensitiveWordsFilter;
public class ASensitiveWordsFilterAdaptor implements ISensitiveWordsFilter {
private ASensitiveWordsFilter aFilter;
public String filter(String text) {
String maskedText = aFilter.filterSexyWords(text);
maskedText = aFilter.filterPoliticalWords(maskedText);
return maskedText;
}
}
<file_sep>
##模板模式
它是在一个模板方法中定义一个算法骨架,并将某些步骤推迟到子类中实现
### 设计意图
复用代码以及扩展
### 实现原理
实现原理比较简单,模板方法定义一个算法骨架,该方法用final修饰,避免子类去重写他
暴露某些算法步骤(方法),延迟到子类去实现,这些方法用absract修饰,强迫子类去实现它。
但是也不是必须的,这些方法也可以抛异常,子类不重写它调用就会抛异常
### 应用场景
在javaJDk中的inpuStream,Writer等的read()方法就用到了模板方法,还有Java Servlet中的service()方法
模板方法多用与框架中...
##回调
A类事先注册某个函数F到B类中,A类在调用B类P 函数的时候,B类反过来调用A类注册给他的F函数
这里的F函数就是回调函数
同步回调和模板方法很是类似,都能起到复用代码和扩展的作用,
比如Spring框架中的JDBCTemplate等等一些模板类,用的设计模式并不是模板模式,
而是回调
模板方法是基于继承的方式来实现,而回调是基于组合的方式。
我们常说,组合优于继承,所以回调比模板方法更灵活
<file_sep>### 替换依赖的外部系统
当我们把项目中依赖的一个外部系统替换为另一个外部系统的时候,利用适配器模式,可以减少对代码的改动
<file_sep>## 工厂模式
###设计意图:对象的创建和使用相分离
###应用场景:
当创建的逻辑比较复杂,是一个“大工程”的时候,我们可以使用工厂模式
那到底使用简单工厂还是工厂方法呢?还是抽象方法?
1. 当我们需要在运行时动态的根据type来创建对象时,
那么这时候我们可以把一大陀的if-else放在工厂类中,推荐使用简单工厂。
但是,当创建的对象比较复杂,可以把创建每个对象的逻辑剥离出来
也就是使用工厂方法
2. 另外,尽管我们不需要根据type来判断创建不同大的对象,但是单个对象的创建逻辑本身就很复杂,
这时候我们也可以使用工厂方法
<file_sep>package com.klayzz.designpattern.behavior.strategy.annotation;
import com.klayzz.designpattern.behavior.strategy.annotation.factory.SortAlgFactory;
import com.klayzz.designpattern.behavior.strategy.annotation.sortalg.ISortAlg;
import java.io.File;
/**
* 自定义注解扩展策略模式
*/
public class Sorter {
private static final long GB = 1000 * 1000 * 1000;
public void sortFile(String filePath) {
// 省略校验逻辑
File file = new File(filePath);
long fileSize = file.length();
ISortAlg sortAlg;
if (fileSize < 6 * GB) { // [0, 6GB)
sortAlg = SortAlgFactory.getSortAlg(SortAlgType.QuickSort);
} else if (fileSize < 10 * GB) { // [6GB, 10GB)
sortAlg = SortAlgFactory.getSortAlg(SortAlgType.ExternalSort);
} else if (fileSize < 100 * GB) { // [10GB, 100GB)
sortAlg = SortAlgFactory.getSortAlg(SortAlgType.ConcurrentExternalSort);
} else { // [100GB, ~)
sortAlg = SortAlgFactory.getSortAlg(SortAlgType.MapReduceSort);
}
sortAlg.sort(filePath);
}
}
<file_sep>package com.klayzz.designpattern.creation.builder;
public class TestMain {
public static void main(String[] args) {
// 这段代码会抛出IllegalArgumentException,因为minIdle>maxIdle
ResourcePoolConfig config = new ResourcePoolConfig.Builder()
.setName("dbconnectionpool")
.setMaxTotal(16)
.setMaxIdle(10)
.setMinIdle(12)
.build();
}
}
<file_sep>package com.klayzz.designpattern.creation.fatory.factorymethod;
import com.klayzz.designpattern.creation.fatory.factorymethod.factory.IRuleConfigParserFactory;
import com.klayzz.designpattern.creation.fatory.simplefactory.config.RuleConfig;
import com.klayzz.designpattern.creation.fatory.simplefactory.parser.IRuleConfigParser;
public class RuleConfigSource {
public RuleConfig load(String ruleConfigFilePath) {
String ruleConfigFileExtension = getFileExtension(ruleConfigFilePath);
//获取该类型的工厂类
IRuleConfigParserFactory parserFactory = RuleConfigParserFactoryMap.getParserFactory(ruleConfigFileExtension);
if (parserFactory == null) {
throw new RuntimeException("Rule config file format is not supported: " + ruleConfigFilePath);
}
IRuleConfigParser parser = parserFactory.createParser();
String configText = "";
//从ruleConfigFilePath文件中读取配置文本到configText中
RuleConfig ruleConfig = parser.parse(configText);
return ruleConfig;
}
private String getFileExtension(String filePath) {
//...解析文件名获取扩展名,比如rule.json,返回json
return "json";
}
}
<file_sep>package com.klayzz.designpattern.structure.proxy.staticproxy.controller;
import com.klayzz.designpattern.structure.proxy.staticproxy.entity.UserVo;
public interface IUserController {
UserVo login(String telephone, String password);
UserVo register(String telephone, String password);
}
<file_sep>### 封装有缺陷的接口设计
假设我们依赖的外部系统在接口设计方面有缺陷
比如包含大量静态方法),引入之后会影响到我们自身代码的可测试性。
为了隔离设计上的缺陷,我们希望对外部系统提供的接口进行二次封装,
抽象出更好的接口设计,这个时候就可以使用适配器模式了。
<file_sep>package com.klayzz.designpattern.structure.adapter.example.example3;
import com.klayzz.designpattern.structure.adapter.example.example3.a.A;
import com.klayzz.designpattern.structure.adapter.example.example3.b.B;
public class app {
public static void main(String[] args) {
//A系统
ADemo a = new ADemo(new A());
//引入B系统
// 借助BAdaptor,Demo的代码中,调用IA接口的地方都无需改动,
// 只需要将BAdaptor如下注入到Demo即可。
ADemo b = new ADemo(new BAdaptor(new B()));
}
}
<file_sep>### 统一多个类的接口设计
某个功能的实现依赖多个外部系统(或者说类)。通过适配器模式,将它们的接口适配为统一的接口定义,然后我们就可以使用多态的特性来复用代码逻辑<file_sep>package com.klayzz.designpattern.creation.fatory.factorymethod.factory;
import com.klayzz.designpattern.creation.fatory.simplefactory.parser.IRuleConfigParser;
public class XmlRuleConfigParserFactory implements IRuleConfigParserFactory {
@Override
public IRuleConfigParser createParser() {
return null;
}
}
<file_sep>
## 观察者模式
### 设计意图
解耦观察者代码和被观察者代码
### 实现方式
在不同的场景和需求下,观察者模式有截然不同的实现方式,
有同步阻塞(传统的经典模式)和异步非阻塞(EventBus)
有进程内的实现方式和跨进程的实现方式(典型的消息对队列,解耦最彻底)
### 应用场景
观察者模式的应用场景非常广泛,小到代码层面的解耦,
大到架构层面的系统解耦,再或者一些产品的设计思路,
都有这种模式的影子,比如,邮件订阅、消息队列,spring中的事件
本质上都是观察者模式。
| 6ee67fbeaa7cbd880c20328f935e0036cf748e41 | [
"Markdown",
"Java"
] | 41 | Java | Pngyul/design-pattern | 0e73b8020d8905a357daaf7e750a779a139b9dd7 | 2c450076091303158622bf67df25d59505e9cd2d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.